@runtypelabs/persona 4.28.0 → 4.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +25 -0
  2. package/dist/{approval-ui-QAKWNFNM.js → approval-ui-OBBI62ES.js} +1 -1
  3. package/dist/approval-ui.cjs +2 -2
  4. package/dist/approval-ui.d.cts +7 -5
  5. package/dist/approval-ui.d.ts +7 -5
  6. package/dist/approval-ui.js +2 -2
  7. package/dist/artifacts-ui.d.cts +7 -5
  8. package/dist/artifacts-ui.d.ts +7 -5
  9. package/dist/{chunk-NQLDCJAP.js → chunk-D4TDKCT5.js} +2 -2
  10. package/dist/chunk-FNXK3VTC.js +1 -0
  11. package/dist/{client-history-LV3KHEFA.js → client-history-QGAFMCBE.js} +1 -1
  12. package/dist/client-history.js +1 -1
  13. package/dist/{client-stream-N22JHTLE.js → client-stream-WXD2FL23.js} +1 -1
  14. package/dist/client-stream.js +3 -3
  15. package/dist/codegen.cjs +4 -4
  16. package/dist/codegen.js +5 -5
  17. package/dist/context-mentions.d.cts +7 -5
  18. package/dist/context-mentions.d.ts +7 -5
  19. package/dist/event-stream-view.d.cts +7 -5
  20. package/dist/event-stream-view.d.ts +7 -5
  21. package/dist/forms-ui.d.cts +7 -5
  22. package/dist/forms-ui.d.ts +7 -5
  23. package/dist/index.cjs +40 -40
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +32 -30
  26. package/dist/index.d.ts +32 -30
  27. package/dist/index.global.js +1 -1
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +41 -41
  30. package/dist/index.js.map +1 -1
  31. package/dist/session-reconnect.d.cts +7 -5
  32. package/dist/session-reconnect.d.ts +7 -5
  33. package/dist/smart-dom-reader.d.cts +7 -5
  34. package/dist/smart-dom-reader.d.ts +7 -5
  35. package/dist/theme-editor-preview.cjs +51 -51
  36. package/dist/theme-editor-preview.d.cts +7 -5
  37. package/dist/theme-editor-preview.d.ts +7 -5
  38. package/dist/theme-editor-preview.js +4 -4
  39. package/dist/theme-editor.d.cts +8 -6
  40. package/dist/theme-editor.d.ts +8 -6
  41. package/dist/{voice-runtime-LVUMPUDS.js → voice-runtime-TWFJ4UUS.js} +1 -1
  42. package/dist/voice-runtime.cjs +1 -1
  43. package/dist/voice-runtime.d.cts +7 -5
  44. package/dist/voice-runtime.d.ts +7 -5
  45. package/dist/voice-runtime.js +1 -1
  46. package/dist/webmcp-runtime-5Q3IHAHP.js +6 -0
  47. package/dist/webmcp-runtime.cjs +2 -2
  48. package/dist/webmcp-runtime.d.cts +22 -26
  49. package/dist/webmcp-runtime.d.ts +22 -26
  50. package/dist/webmcp-runtime.js +2 -2
  51. package/package.json +5 -2
  52. package/src/generated/runtype-openapi-contract.ts +3 -0
  53. package/src/theme-editor/webmcp/types.ts +1 -1
  54. package/src/types.ts +7 -5
  55. package/src/webmcp-bridge.test.ts +87 -21
  56. package/src/webmcp-bridge.ts +21 -26
  57. package/src/webmcp-polyfill.integration.test.ts +339 -0
  58. package/src/webmcp-polyfill.ts +7 -4
  59. package/src/webmcp-runtime-bundle.test.ts +1 -1
  60. package/src/webmcp-runtime-entry.ts +34 -19
  61. package/dist/chunk-AALCT54S.js +0 -1
  62. package/dist/webmcp-runtime-V6ZWW3PI.js +0 -6
@@ -1,25 +1,25 @@
1
- "use strict";var qk=Object.create;var Fd=Object.defineProperty;var jk=Object.getOwnPropertyDescriptor;var Kk=Object.getOwnPropertyNames;var Gk=Object.getPrototypeOf,Yk=Object.prototype.hasOwnProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var En=(e,t)=>{for(var n in t)Fd(e,n,{get:t[n],enumerable:!0})},hC=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Kk(t))!Yk.call(e,r)&&r!==n&&Fd(e,r,{get:()=>t[r],enumerable:!(o=jk(t,r))||o.enumerable});return e};var yC=(e,t,n)=>(n=e!=null?qk(Gk(e)):{},hC(t||!e||!e.__esModule?Fd(n,"default",{value:e,enumerable:!0}):n,e)),Xk=e=>hC(Fd({},"__esModule",{value:!0}),e);var Je,ao=ie(()=>{"use strict";Je=(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 i=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([d,p])=>{d!=="stroke"&&c.setAttribute(d,String(p))}),r.appendChild(c)}),r}});function Zo(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];bC(s)&&bC(r)?n[o]=Zo(s,r):n[o]=r}return n}var bC,Vd=ie(()=>{"use strict";bC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function $d(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Dm(o)?$d(o,r):[r]})}function vC(e,t){for(let n of t.split(".")){if(!Dm(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function CC(e,t){return e?.[Bm]??t.filter(n=>vC(e,n)==="explicit")}function _m(e,t){return Object.defineProperty(e,Bm,{value:t,enumerable:!0,configurable:!0}),e}function Om(e,t,n){return _m(e,CC(t,$d(n)))}function wC(e,t,n){let o=t[Bm];if(o)return o;let r=new Set(CC(e,n));for(let s of n){let i=vC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function xC(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!Dm(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var Bm,Dm,Nm=ie(()=>{"use strict";Bm=Symbol("persona.defaultsProvenance"),Dm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var SC,Fm,vi,Ud,Qk,Ur,Vm,$m,AC,ha=ie(()=>{"use strict";SC="var(--persona-components-panel-width)",Fm=Symbol("persona.panelAliasProvenance"),vi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Ud=(e,t)=>vi(e,t)&&e[t]!==void 0,Qk=e=>({launcherWidth:Ud(e?.launcher,"width"),legacyLauncherWidth:Ud(e,"launcherWidth"),sidebarWidth:Ud(e?.launcher,"sidebarWidth"),dockWidth:Ud(e?.launcher?.dock,"width")}),Ur=e=>{let t=e?.[Fm];return t?{...t}:Qk(e)},Vm=(e,t)=>(Object.defineProperty(e,Fm,{value:t,enumerable:!0,configurable:!0}),e),$m=(e,t)=>Vm(e,Ur(t)),AC=(e,t)=>{let n=t[Fm];if(n)return{...n};let o=Ur(e);return vi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),vi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(vi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),vi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),vi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:vi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});var zd=ie(()=>{"use strict"});function Ts(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function qd(e){let t=Ts(e)==="v5"?Ci:eL;return Zo(Zk,t)}function MC(e,t){if(!(!e&&!t))return e?t?Zo(e,t):e:t}function jd(e){let t=qd(e);return e?Om($m({...t,...e,theme:MC(t.theme,e.theme),darkTheme:MC(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,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,d=e.features?.streamAnimation,p=t.features?.askUserQuestion,f=e.features?.askUserQuestion,m=t.features?.history,g=e.features?.history,h=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},b=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&d===void 0?void 0:{...c,...d},S=p===void 0&&f===void 0?void 0:{...p,...f,styles:{...p?.styles,...f?.styles}},E=m===void 0&&g===void 0?void 0:{...m,...g,copy:{...m?.copy,...g?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...h!==void 0?{artifacts:h}:{},...A!==void 0?{streamAnimation:A}:{},...S!==void 0?{askUserQuestion:S}:{},...E!==void 0?{history:E}:{}}})(),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,Ci):Om($m(t),void 0,Ci)}var Um,Ll,zm,zr,wi,Jk,Zk,eL,tL,Ci,m1,er=ie(()=>{"use strict";Vd();Nm();ha();zd();Um="min(440px, calc(100vw - 24px))",Ll="40px",zm="How can I help...",zr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},wi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Jk={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:Um,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Ll,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)"},Zk={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:Jk,copy:{inputPlaceholder:zm,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:zr,reasoningDisplay:wi,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},eL={},tL={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ci={launcher:tL,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"}}}};m1=qd()});var v,TC,F,Jt,Ge=ie(()=>{"use strict";v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},TC=()=>document.createDocumentFragment(),F=(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,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Jt=(...e)=>e.filter(Boolean).join(" ")});var Wt,Bn=ie(()=>{"use strict";Wt=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(f=>(r=f,f)).catch(f=>{throw s=null,f}),s),provide:p=>{r=p},getSync:()=>r}}});var EC={};En(EC,{EXTRA_LUCIDE_ICONS:()=>nL});var ae,nL,kC=ie(()=>{"use strict";ae=require("lucide"),nL={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var oL,rL,qm,Kd,Gd=ie(()=>{"use strict";Bn();({setLoader:oL,load:rL}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(kC(),EC))})),qm=oL,Kd=rL});var ue,sL,iL,Yd,ya,jm,Xd,aL,LC,lL,Km,cL,dL,We,ln=ie(()=>{"use strict";ao();Gd();ue=require("lucide"),sL={activity:ue.Activity,"arrow-down":ue.ArrowDown,"arrow-up":ue.ArrowUp,"arrow-up-right":ue.ArrowUpRight,bot:ue.Bot,"chevron-down":ue.ChevronDown,"chevron-up":ue.ChevronUp,"chevron-right":ue.ChevronRight,"chevron-left":ue.ChevronLeft,check:ue.Check,clipboard:ue.Clipboard,"clipboard-copy":ue.ClipboardCopy,"code-xml":ue.CodeXml,copy:ue.Copy,file:ue.File,"file-code":ue.FileCode,"file-spreadsheet":ue.FileSpreadsheet,"file-text":ue.FileText,"image-plus":ue.ImagePlus,loader:ue.Loader,"loader-circle":ue.LoaderCircle,mic:ue.Mic,paperclip:ue.Paperclip,quote:ue.Quote,"refresh-cw":ue.RefreshCw,search:ue.Search,send:ue.Send,"shield-alert":ue.ShieldAlert,"shield-check":ue.ShieldCheck,"shield-x":ue.ShieldX,square:ue.Square,"thumbs-down":ue.ThumbsDown,"thumbs-up":ue.ThumbsUp,upload:ue.Upload,"volume-2":ue.Volume2,x:ue.X,"at-sign":ue.AtSign,"arrow-left":ue.ArrowLeft,"arrow-right":ue.ArrowRight,"external-link":ue.ExternalLink,ellipsis:ue.Ellipsis,"ellipsis-vertical":ue.EllipsisVertical,menu:ue.Menu,"panel-left":ue.PanelLeft,plus:ue.Plus,minus:ue.Minus,pencil:ue.Pencil,trash:ue.Trash,"trash-2":ue.Trash2,download:ue.Download,maximize:ue.Maximize,minimize:ue.Minimize,"message-square":ue.MessageSquare,star:ue.Star,eye:ue.Eye,history:ue.History},iL=["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"],Yd=new Map(Object.entries(sL)),ya=new Set,jm=!1,Xd=new Set,aL=e=>{let t=[...Xd];e&&Xd.clear();for(let n of t)try{n()}catch{}},LC=e=>jm?()=>{}:(Xd.add(e),()=>{Xd.delete(e)}),lL=()=>{let e=0;for(let t of[...ya]){let n=Yd.get(t.name);if(!n)continue;ya.delete(t),e++;let o=Je(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},Km=!1,cL=()=>{Kd().then(e=>{if(!jm){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Yd.has(t)||Yd.set(t,n);jm=!0,lL(),aL(!0)}}).catch(e=>{Km=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},dL=(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},We=(e,t=24,n="currentColor",o=2)=>{let r=Yd.get(e);if(r)return Je(r,t,n,o);if(iL.includes(e)){Km&&(Km=!1);let s=dL(t,n,o);if(ya.size>=500){let i=ya.values().next().value;i&&ya.delete(i)}return ya.add({el:s,name:e,size:t,color:n,strokeWidth:o}),cL(),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}});var gL,xi,Ym,Xm=ie(()=>{"use strict";gL=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),xi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=gL(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Ym=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}});var DC={};En(DC,{DOMPurify:()=>BC.default,Marked:()=>WC.Marked});var WC,BC,_C=ie(()=>{"use strict";WC=require("marked"),BC=yC(require("dompurify"),1)});var B1,yL,bL,Qm,sp,OC,NC,va,Jm,Oo,Si=ie(()=>{"use strict";Bn();({setLoader:B1,load:yL,provide:bL,getSync:Qm}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(_C(),DC))})),sp=new Set,OC=()=>{let e=[...sp];sp.clear();for(let t of e)try{t()}catch{}},NC=()=>{let e=Qm();return e?Promise.resolve(e):yL().then(t=>(OC(),t))},va=e=>Qm()?()=>{}:(sp.add(e),()=>{sp.delete(e)}),Jm=e=>{bL(e),OC()},Oo=Qm});var vL,Zm,ip,O1,jr,ap=ie(()=>{"use strict";Si();vL=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}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,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,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},Zm=e=>{let t=null;return n=>{let o=Oo();if(!o)return jr(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 i=vL(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},ip=e=>e?Zm({markedOptions:e.options,renderer:e.renderer}):Zm(),O1=Zm(),jr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")});var CL,wL,xL,lp,eg=ie(()=>{"use strict";ap();Si();CL={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"]},wL=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,xL=()=>{let e=null;return t=>{let n=Oo();if(!n)return jr(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 i=s.attrValue;i.toLowerCase().startsWith("data:")&&!wL.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,CL)}},lp=e=>e===!1?null:typeof e=="function"?e:xL()});function QC(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}:${TL(t.join(""))}`}function YC(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 TL(e){let t=YC(e,0).toString(36),n=YC(e,2654435761).toString(36);return`${t}.${n}`}var Kr,ng,XC,cp,GC,EL,Ca,JC,Ai=ie(()=>{"use strict";Kr="webmcp:",ng=new Map,XC=e=>{ng.clear();for(let t of e){let n=t.title?.trim();n&&ng.set(t.name,n)}},cp=e=>ng.get(EL(e)),GC=null;EL=e=>e.startsWith(Kr)?e.slice(Kr.length):e,Ca=e=>e.startsWith(Kr),JC=()=>GC?GC():import("@mcp-b/webmcp-polyfill")});function No(e){return e==="card"?"collapsed":e}function wa(e){return e.split(";",1)[0].trim().toLowerCase()}function kL(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(wa(r)===t)return{mode:No(s),selector:wa(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(wa(r)===o)return{mode:No(s),selector:o}}function LL(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:No(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?wa(t.file.mimeType):void 0,c=l?kL(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:No(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:No(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:No(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:No(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:No(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ks(e,t){return LL(e,t).mode}function Il(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 Hl=ie(()=>{"use strict"});var xa,ZC,tr,PL,ew,IL,HL,tw,RL,nw,dp,Wl,pp,og,up,Rl,WL,Bl,ow,rw,sw,iw,Gr=ie(()=>{"use strict";xa=require("partial-json"),ZC=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),tr=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)}},PL=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`},ew=e=>e.status==="complete"?PL(e):e.status==="pending"?"Waiting":"",IL=15e3,HL=1200,tw=(e,t)=>{let n=t?.durationMs??IL,o=t?.chars??HL;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},RL=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`},nw=e=>e.status==="complete"?RL(e):"Using tool...",dp=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Wl=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 dp(t)},pp=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return dp(t)},og=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Wl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},up=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Rl(o,n.slice(s,i.index),[]),i[1]!==void 0?Rl(o,i[1],["bold"]):i[2]!==void 0?Rl(o,i[2],["italic"]):i[3]!==void 0&&Rl(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Rl(o,n.slice(s),[]),o},Rl=(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})},WL=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ "use strict";var jk=Object.create;var Fd=Object.defineProperty;var Kk=Object.getOwnPropertyDescriptor;var Gk=Object.getOwnPropertyNames;var Yk=Object.getPrototypeOf,Xk=Object.prototype.hasOwnProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var En=(e,t)=>{for(var n in t)Fd(e,n,{get:t[n],enumerable:!0})},hC=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Gk(t))!Xk.call(e,r)&&r!==n&&Fd(e,r,{get:()=>t[r],enumerable:!(o=Kk(t,r))||o.enumerable});return e};var yC=(e,t,n)=>(n=e!=null?jk(Yk(e)):{},hC(t||!e||!e.__esModule?Fd(n,"default",{value:e,enumerable:!0}):n,e)),Qk=e=>hC(Fd({},"__esModule",{value:!0}),e);var Je,ao=ie(()=>{"use strict";Je=(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 i=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([d,p])=>{d!=="stroke"&&c.setAttribute(d,String(p))}),r.appendChild(c)}),r}});function Zo(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];bC(s)&&bC(r)?n[o]=Zo(s,r):n[o]=r}return n}var bC,Vd=ie(()=>{"use strict";bC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function $d(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Dm(o)?$d(o,r):[r]})}function vC(e,t){for(let n of t.split(".")){if(!Dm(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function CC(e,t){return e?.[Bm]??t.filter(n=>vC(e,n)==="explicit")}function _m(e,t){return Object.defineProperty(e,Bm,{value:t,enumerable:!0,configurable:!0}),e}function Om(e,t,n){return _m(e,CC(t,$d(n)))}function wC(e,t,n){let o=t[Bm];if(o)return o;let r=new Set(CC(e,n));for(let s of n){let i=vC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function xC(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!Dm(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var Bm,Dm,Nm=ie(()=>{"use strict";Bm=Symbol("persona.defaultsProvenance"),Dm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var SC,Fm,vi,Ud,Jk,Ur,Vm,$m,AC,ha=ie(()=>{"use strict";SC="var(--persona-components-panel-width)",Fm=Symbol("persona.panelAliasProvenance"),vi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Ud=(e,t)=>vi(e,t)&&e[t]!==void 0,Jk=e=>({launcherWidth:Ud(e?.launcher,"width"),legacyLauncherWidth:Ud(e,"launcherWidth"),sidebarWidth:Ud(e?.launcher,"sidebarWidth"),dockWidth:Ud(e?.launcher?.dock,"width")}),Ur=e=>{let t=e?.[Fm];return t?{...t}:Jk(e)},Vm=(e,t)=>(Object.defineProperty(e,Fm,{value:t,enumerable:!0,configurable:!0}),e),$m=(e,t)=>Vm(e,Ur(t)),AC=(e,t)=>{let n=t[Fm];if(n)return{...n};let o=Ur(e);return vi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),vi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(vi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),vi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),vi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:vi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});var zd=ie(()=>{"use strict"});function Ts(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function qd(e){let t=Ts(e)==="v5"?Ci:tL;return Zo(eL,t)}function MC(e,t){if(!(!e&&!t))return e?t?Zo(e,t):e:t}function jd(e){let t=qd(e);return e?Om($m({...t,...e,theme:MC(t.theme,e.theme),darkTheme:MC(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,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,d=e.features?.streamAnimation,p=t.features?.askUserQuestion,f=e.features?.askUserQuestion,m=t.features?.history,g=e.features?.history,h=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},b=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&d===void 0?void 0:{...c,...d},S=p===void 0&&f===void 0?void 0:{...p,...f,styles:{...p?.styles,...f?.styles}},E=m===void 0&&g===void 0?void 0:{...m,...g,copy:{...m?.copy,...g?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...h!==void 0?{artifacts:h}:{},...A!==void 0?{streamAnimation:A}:{},...S!==void 0?{askUserQuestion:S}:{},...E!==void 0?{history:E}:{}}})(),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,Ci):Om($m(t),void 0,Ci)}var Um,Ll,zm,zr,wi,Zk,eL,tL,nL,Ci,g1,er=ie(()=>{"use strict";Vd();Nm();ha();zd();Um="min(440px, calc(100vw - 24px))",Ll="40px",zm="How can I help...",zr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},wi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Zk={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:Um,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Ll,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)"},eL={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:Zk,copy:{inputPlaceholder:zm,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:zr,reasoningDisplay:wi,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},tL={},nL={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ci={launcher:nL,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"}}}};g1=qd()});var v,TC,F,Jt,Ge=ie(()=>{"use strict";v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},TC=()=>document.createDocumentFragment(),F=(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,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Jt=(...e)=>e.filter(Boolean).join(" ")});var Wt,Bn=ie(()=>{"use strict";Wt=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(f=>(r=f,f)).catch(f=>{throw s=null,f}),s),provide:p=>{r=p},getSync:()=>r}}});var EC={};En(EC,{EXTRA_LUCIDE_ICONS:()=>oL});var ae,oL,kC=ie(()=>{"use strict";ae=require("lucide"),oL={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var rL,sL,qm,Kd,Gd=ie(()=>{"use strict";Bn();({setLoader:rL,load:sL}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(kC(),EC))})),qm=rL,Kd=sL});var ue,iL,aL,Yd,ya,jm,Xd,lL,LC,cL,Km,dL,pL,We,ln=ie(()=>{"use strict";ao();Gd();ue=require("lucide"),iL={activity:ue.Activity,"arrow-down":ue.ArrowDown,"arrow-up":ue.ArrowUp,"arrow-up-right":ue.ArrowUpRight,bot:ue.Bot,"chevron-down":ue.ChevronDown,"chevron-up":ue.ChevronUp,"chevron-right":ue.ChevronRight,"chevron-left":ue.ChevronLeft,check:ue.Check,clipboard:ue.Clipboard,"clipboard-copy":ue.ClipboardCopy,"code-xml":ue.CodeXml,copy:ue.Copy,file:ue.File,"file-code":ue.FileCode,"file-spreadsheet":ue.FileSpreadsheet,"file-text":ue.FileText,"image-plus":ue.ImagePlus,loader:ue.Loader,"loader-circle":ue.LoaderCircle,mic:ue.Mic,paperclip:ue.Paperclip,quote:ue.Quote,"refresh-cw":ue.RefreshCw,search:ue.Search,send:ue.Send,"shield-alert":ue.ShieldAlert,"shield-check":ue.ShieldCheck,"shield-x":ue.ShieldX,square:ue.Square,"thumbs-down":ue.ThumbsDown,"thumbs-up":ue.ThumbsUp,upload:ue.Upload,"volume-2":ue.Volume2,x:ue.X,"at-sign":ue.AtSign,"arrow-left":ue.ArrowLeft,"arrow-right":ue.ArrowRight,"external-link":ue.ExternalLink,ellipsis:ue.Ellipsis,"ellipsis-vertical":ue.EllipsisVertical,menu:ue.Menu,"panel-left":ue.PanelLeft,plus:ue.Plus,minus:ue.Minus,pencil:ue.Pencil,trash:ue.Trash,"trash-2":ue.Trash2,download:ue.Download,maximize:ue.Maximize,minimize:ue.Minimize,"message-square":ue.MessageSquare,star:ue.Star,eye:ue.Eye,history:ue.History},aL=["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"],Yd=new Map(Object.entries(iL)),ya=new Set,jm=!1,Xd=new Set,lL=e=>{let t=[...Xd];e&&Xd.clear();for(let n of t)try{n()}catch{}},LC=e=>jm?()=>{}:(Xd.add(e),()=>{Xd.delete(e)}),cL=()=>{let e=0;for(let t of[...ya]){let n=Yd.get(t.name);if(!n)continue;ya.delete(t),e++;let o=Je(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},Km=!1,dL=()=>{Kd().then(e=>{if(!jm){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Yd.has(t)||Yd.set(t,n);jm=!0,cL(),lL(!0)}}).catch(e=>{Km=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},pL=(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},We=(e,t=24,n="currentColor",o=2)=>{let r=Yd.get(e);if(r)return Je(r,t,n,o);if(aL.includes(e)){Km&&(Km=!1);let s=pL(t,n,o);if(ya.size>=500){let i=ya.values().next().value;i&&ya.delete(i)}return ya.add({el:s,name:e,size:t,color:n,strokeWidth:o}),dL(),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}});var hL,xi,Ym,Xm=ie(()=>{"use strict";hL=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),xi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=hL(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Ym=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}});var DC={};En(DC,{DOMPurify:()=>BC.default,Marked:()=>WC.Marked});var WC,BC,_C=ie(()=>{"use strict";WC=require("marked"),BC=yC(require("dompurify"),1)});var D1,bL,vL,Qm,sp,OC,NC,va,Jm,Oo,Si=ie(()=>{"use strict";Bn();({setLoader:D1,load:bL,provide:vL,getSync:Qm}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(_C(),DC))})),sp=new Set,OC=()=>{let e=[...sp];sp.clear();for(let t of e)try{t()}catch{}},NC=()=>{let e=Qm();return e?Promise.resolve(e):bL().then(t=>(OC(),t))},va=e=>Qm()?()=>{}:(sp.add(e),()=>{sp.delete(e)}),Jm=e=>{vL(e),OC()},Oo=Qm});var CL,Zm,ip,N1,jr,ap=ie(()=>{"use strict";Si();CL=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}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,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,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},Zm=e=>{let t=null;return n=>{let o=Oo();if(!o)return jr(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 i=CL(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},ip=e=>e?Zm({markedOptions:e.options,renderer:e.renderer}):Zm(),N1=Zm(),jr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")});var wL,xL,SL,lp,eg=ie(()=>{"use strict";ap();Si();wL={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"]},xL=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,SL=()=>{let e=null;return t=>{let n=Oo();if(!n)return jr(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 i=s.attrValue;i.toLowerCase().startsWith("data:")&&!xL.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,wL)}},lp=e=>e===!1?null:typeof e=="function"?e:SL()});function QC(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}:${EL(t.join(""))}`}function YC(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 EL(e){let t=YC(e,0).toString(36),n=YC(e,2654435761).toString(36);return`${t}.${n}`}var Kr,ng,XC,cp,GC,kL,Ca,JC,Ai=ie(()=>{"use strict";Kr="webmcp:",ng=new Map,XC=e=>{ng.clear();for(let t of e){let n=t.title?.trim();n&&ng.set(t.name,n)}},cp=e=>ng.get(kL(e)),GC=null;kL=e=>e.startsWith(Kr)?e.slice(Kr.length):e,Ca=e=>e.startsWith(Kr),JC=()=>GC?GC():import("@mcp-b/webmcp-polyfill")});function No(e){return e==="card"?"collapsed":e}function wa(e){return e.split(";",1)[0].trim().toLowerCase()}function LL(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(wa(r)===t)return{mode:No(s),selector:wa(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(wa(r)===o)return{mode:No(s),selector:o}}function PL(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:No(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?wa(t.file.mimeType):void 0,c=l?LL(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:No(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:No(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:No(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:No(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:No(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ks(e,t){return PL(e,t).mode}function Il(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 Hl=ie(()=>{"use strict"});var xa,ZC,tr,IL,ew,HL,RL,tw,WL,nw,dp,Wl,pp,og,up,Rl,BL,Bl,ow,rw,sw,iw,Gr=ie(()=>{"use strict";xa=require("partial-json"),ZC=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),tr=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)}},IL=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`},ew=e=>e.status==="complete"?IL(e):e.status==="pending"?"Waiting":"",HL=15e3,RL=1200,tw=(e,t)=>{let n=t?.durationMs??HL,o=t?.chars??RL;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},WL=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`},nw=e=>e.status==="complete"?WL(e):"Using tool...",dp=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Wl=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 dp(t)},pp=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return dp(t)},og=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Wl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},up=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Rl(o,n.slice(s,i.index),[]),i[1]!==void 0?Rl(o,i[1],["bold"]):i[2]!==void 0?Rl(o,i[2],["italic"]):i[3]!==void 0&&Rl(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Rl(o,n.slice(s),[]),o},Rl=(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})},BL=()=>{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,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).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()=>{}}},Bl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ow=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},rw=()=>{let e=WL();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)}},sw=()=>{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,xa.parse)(n,xa.STR|xa.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ZC(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ZC(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},iw=()=>{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 Ls,rg,Dl,Sa,BL,DL,lw,cw,_L,OL,NL,FL,VL,sg,ig,dw,ag,pw,$L,UL,aw,uw,Mi,lg,Aa,_l,zL,qL,jL,fw,KL,GL,YL,mw,XL,QL,Ti,gw,Fo,JL,Ma,Ps,ZL,eP,fp,hw,yw,cg,tP,nP,bw,Ei,dg,Is,mp,gp=ie(()=>{"use strict";Ls=require("partial-json");Ge();rg="ask_user_question",Dl=8,Sa="data-persona-ask-sheet-for",BL="Other",DL="Other\u2026",lw="Type your own answer here",cw="Send",_L="Next",OL="Back",NL="Submit all",FL="Skip",VL=3,sg="data-ask-current-index",ig="data-ask-question-count",dw="data-ask-answers",ag="data-ask-grouped",pw="data-ask-layout",$L=e=>e.layout==="pills"?"pills":"rows",UL=e=>e.getAttribute(pw)==="pills"?"pills":"rows",aw=!1,uw=e=>e.replace(/["\\]/g,"\\$&"),Mi=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===rg,lg=e=>e?.features?.askUserQuestion??{},Aa=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,Ls.parse)(r,Ls.STR|Ls.OBJ|Ls.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},_l=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Dl&&!aw&&(aw=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Dl}.`)),t.slice(0,Dl)},zL=e=>_l(e)[0]??null,qL=(e,t)=>_l(e)[t]??null,jL=(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))},fw=(e,t,n)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},KL=(e,t,n,o)=>{let s=v("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 i=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let d=v("span","persona-ask-row-description");d.textContent=e.description,i.appendChild(d)}s.appendChild(i);let c=fw(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},GL=e=>{let n=v("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},YL=(e,t,n,o)=>{let s=v("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 i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!n){for(let p=0;p<VL;p++)s.appendChild(GL(o));return s}if(c.forEach((p,f)=>{s.appendChild(KL(p,f,o,i))}),e?.allowFreeText!==!1){let p=o==="rows"?BL:DL;if(o==="rows"){let f=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(c.length)),f.setAttribute("data-ask-other-row","true");let m=v("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??lw,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??p),m.appendChild(g),f.appendChild(m);let h=fw(o,i,c.length);h&&f.appendChild(h),s.appendChild(f)}else{let f=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??p,s.appendChild(f)}}return s},mw=(e,t)=>{let o=v("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??lw,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??cw,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},XL=e=>{let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??cw,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},QL=(e,t,n)=>{let o=v("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=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??OL,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=v("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??FL,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??NL:n.nextLabel??_L,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ti=e=>{let t=e.getAttribute(dw);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},gw=(e,t)=>{e.setAttribute(dw,JSON.stringify(t))},Fo=e=>{let t=Number(e.getAttribute(sg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},JL=(e,t)=>{e.setAttribute(sg,String(Math.max(0,Math.floor(t))))},Ma=e=>{let t=Number(e.getAttribute(ig)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ps=e=>e.getAttribute(ag)==="true",ZL=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},eP=(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)))},fp=(e,t)=>{let{payload:n}=Aa(t),o=_l(n),r=Ti(e),s={},i=new Set;return o.forEach((l,c)=>{let d=typeof l?.question=="string"?l.question:"";d&&(i.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),i.add(d),Object.prototype.hasOwnProperty.call(r,c)&&(s[d]=r[c]))}),s},hw=e=>{let t=Ti(e),n=Fo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let d=c.getAttribute("data-option-label")??"",p=r.has(d);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},yw=e=>{if(!Ps(e))return;let t=Ti(e),n=Fo(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 i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},cg=(e,t,n)=>{let o=lg(n),r=UL(e),{payload:s,complete:i}=Aa(t),l=Ps(e),c=Fo(e),d=Ma(e),p=l?qL(s,c):zL(s),f=!!p?.multiSelect,m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=l?`${c+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let S=typeof p?.question=="string"?p.question:"";h.textContent=S,h.classList.toggle("persona-ask-question-skeleton",!S&&!i)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let S=YL(p,o,i,r);b.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(mw(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!C?e.appendChild(XL(o)):(!f||l)&&C&&C.remove(),e.setAttribute("data-multi-select",f?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=QL(c,d,o);A?A.replaceWith(S):e.appendChild(S)}else A&&A.remove();hw(e),yw(e)},tP=(e,t,n)=>{let o=lg(t),r=$L(o),s=e.toolCall.id,i=_l(n),l=Math.max(1,i.length),c=l>1,d=ZL(e,i),p=c?eP(e,l):0,f=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sa,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(ig,String(l)),f.setAttribute(sg,String(p)),f.setAttribute(ag,c?"true":"false"),f.setAttribute(pw,r),gw(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),jL(f,o);let m=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=v("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",m.appendChild(g);let h=v("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",m.appendChild(h),f.appendChild(m);let C=v("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 C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),f.appendChild(C),r!=="rows"&&f.appendChild(mw(o,r)),cg(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},nP=(e,t,n)=>{let{payload:o}=Aa(t),r=Math.max(1,_l(o).length);r>Ma(e)&&(e.setAttribute(ig,String(r)),r>1&&!Ps(e)&&e.setAttribute(ag,"true")),cg(e,t,n)},bw=(e,t,n)=>{if(!n||!Mi(e)||lg(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sa}]`).forEach(d=>{d.getAttribute(Sa)!==r&&d.remove()});let i=n.querySelector(`[${Sa}="${uw(r)}"]`);if(i){nP(i,e,t);return}let{payload:l}=Aa(e),c=tP(e,t,l);n.appendChild(c)},Ei=(e,t)=>{if(!e)return;let n=t?`[${Sa}="${uw(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)})},dg=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=Fo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,gw(e,n),hw(e),yw(e)},mp=(e,t,n,o)=>{let r=Ma(e),s=Math.max(0,Math.min(r-1,o));JL(e,s),cg(e,t,n)}});var Yr,oP,Cw,ww,Ol,rP,xw,vw,sP,Hs,Nl=ie(()=>{"use strict";Yr="suggest_replies",oP={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},Cw={name:Yr,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:oP,origin:"sdk",annotations:{readOnlyHint:!0}},ww=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ol=e=>e.variant==="tool"&&e.toolCall?.name===Yr,rP=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 i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});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},xw=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ol(n))continue;let o=rP(n.toolCall?.args);return o.length>0?o:null}return null},vw=new Set,sP=(e,t,n)=>{let o=`${e}:${t}:${n}`;vw.has(o)||(vw.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Hs=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&sP(i,c,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 iP,aP,Fl,pg=ie(()=>{"use strict";gp();Nl();iP={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Dl,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},aP={name:rg,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:iP,origin:"sdk",annotations:{readOnlyHint:!0}},Fl=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(aP),Hs(e).expose&&t.push(Cw),t}});var Cn,Jn,Ta,hp,nr=ie(()=>{"use strict";Cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Jn=1e5,Ta=Jn+1,hp="https://api.runtype.com"});async function Sw(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(d,p)=>fetch(`${e.clientApiBase()}${d}`,{method:"POST",headers:o,body:JSON.stringify({...p,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let d=await c.clone().json().catch(()=>null);if(!d||d.error==="Not Found")return s(i)}return c}async function Aw(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||hp}/resume`,i,l=null;if(r){let p=await e.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(d.sessionId=i),r&&i){let p=[...Fl(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:f,commit:m}=await e.sendWithClientToolsDiff(i,p,g=>{let h={...d,...g};return e.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(s,{method:"POST",headers:c,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return f.ok&&m(),f}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(d),signal:o?.signal})}var Mw=ie(()=>{"use strict";pg();nr()});var kw={};En(kw,{preferFinalStructuredContent:()=>Ew,resolveApproval:()=>Sw,resumeFlow:()=>Aw,streamResponse:()=>dP});function lP(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"}function Ew(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=Tw(n);if(!Tw(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=Bl(e);return Bl(t)!==null&&i===null?t:e}async function cP(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=p=>{let f={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=f,r(f),f},d=p=>o.current?o.current:c(p);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let p=d(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)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.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 function dP(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),d=0,p=()=>c+d++,f=U=>{let R=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,G=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,ne=U.tools?U.tools.map(Z=>({...Z,chunks:Z.chunks?[...Z.chunks]:void 0})):void 0;return{...U,reasoning:R,toolCall:G,tools:ne}},m=U=>{if(U.role!=="assistant"||U.variant)return!0;let R=Array.isArray(U.contentParts)&&U.contentParts.length>0,G=typeof U.rawContent=="string"&&U.rawContent.trim()!=="";return typeof U.content=="string"&&U.content.trim()!==""||R||G||!!U.stopReason},g=U=>{m(U)&&n({type:"message",message:f(U)})},h=null,b=null,C={current:null},A={current:null},S=null,E="",k=new Map,D=new Map,z=new Map,Y=new Map,T=new Map,W=o,L=!1,w=()=>{if(h)return h;let U,R="",G=S;return!L&&W?(U=W,L=!0,R=r??""):W&&G?U=`${W}_${G}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:U,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(h),h},x=U=>{let R=Y.get(U);if(R)return R;let G={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:U,status:"streaming",chunks:[]}};return Y.set(U,G),g(G),G},P=new Set,I=new Map,J=new Set,_=new Map,j=U=>{if(!U)return!1;let R=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return R==="emit_artifact_markdown"||R==="emit_artifact_component"},te=U=>{let R=T.get(U);if(R)return R;let G={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:U,status:"pending"}};return T.set(U,G),g(G),G},K=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let R=Number(U);if(!Number.isNaN(R)&&Number.isFinite(R))return R;let G=Date.parse(U);if(!Number.isNaN(G))return G}return Date.now()},X=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},oe=new Map,de=new Map,xe=(U,R)=>{let G=X(R),ne=de.get(U.id),Z=Ew(ne,G);U.rawContent=Z;let le=oe.get(U.id),Me=qe=>{let nt=U.content??"";qe.trim()!==""&&(nt.trim().length===0||qe.startsWith(nt)||qe.trimStart().startsWith(nt.trim()))&&(U.content=qe)},Ie=()=>{if(le){let qe=le.close?.();qe instanceof Promise&&qe.catch(()=>{})}oe.delete(U.id),de.delete(U.id),U.streaming=!1,g(U)};if(!le){Me(G),Ie();return}let _e=Bl(Z);if(_e!==null&&_e.trim()!==""){Me(_e),Ie();return}let ct=qe=>{let nt=typeof qe=="string"?qe:qe?.text??null;if(nt!==null&&nt.trim()!=="")return nt;let Ut=le.getExtractedText();return Ut!==null&&Ut.trim()!==""?Ut:G},Tt;try{Tt=le.processChunk(Z)}catch{Me(G),Ie();return}if(Tt instanceof Promise){Tt.then(qe=>{Me(ct(qe)),Ie()}).catch(()=>{Me(G),Ie()});return}Me(ct(Tt)),Ie()},Te=null,re=(U,R,G,ne)=>{U.rawContent=R,oe.has(U.id)||oe.set(U.id,e.createStreamParser());let Z=oe.get(U.id),le=R.trim().startsWith("{")||R.trim().startsWith("[");if(le&&de.set(U.id,R),Z.__isPlainTextParser===!0){U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U);return}let Ie=Z.processChunk(R);if(Ie instanceof Promise)Ie.then(_e=>{let ct=typeof _e=="string"?_e:_e?.text??null;ct!==null&&ct.trim()!==""?(U.content=ct,g(U)):!le&&!R.trim().startsWith("<")&&(U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U))}).catch(()=>{U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U)});else{let _e=typeof Ie=="string"?Ie:Ie?.text??null;_e!==null&&_e.trim()!==""?(U.content=_e,g(U)):!le&&!R.trim().startsWith("<")&&(U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U))}},N=(U,R)=>{let G=R??U.content;if(G==null||G===""){U.streaming=!1,g(U);return}let Z=de.get(U.id)??X(G);U.rawContent=Z;let le=oe.get(U.id),Me=null,Ie=!1;if(le&&(Me=le.getExtractedText(),Me===null&&(Me=Bl(Z)),Me===null)){let _e=le.processChunk(Z);_e instanceof Promise?(Ie=!0,_e.then(ct=>{let Tt=typeof ct=="string"?ct:ct?.text??null;Tt!==null&&(U.content=Tt,U.streaming=!1,oe.delete(U.id),de.delete(U.id),g(U))}).catch(()=>{})):Me=typeof _e=="string"?_e:_e?.text??null}if(!Ie){Me!==null&&Me.trim()!==""?U.content=Me:de.has(U.id)||(U.content=X(G));let _e=oe.get(U.id);if(_e){let ct=_e.close?.();ct instanceof Promise&&ct.catch(()=>{}),oe.delete(U.id)}de.delete(U.id),U.streaming=!1,g(U)}},ke=(U,R,G)=>{let ne=D.get(U);if(ne)return ne;let Z={id:`nested-${R}-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...G?{variant:G}:{},...G==="reasoning"?{reasoning:{id:U,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:R}};return D.set(U,Z),g(Z),Z},ve=[],tt,xt=new Map,ht=0,lt="agent",Ye=!1,dt=null,Pe=null,Se=e.config().iterationDisplay??"separate";for(tt=()=>{for(let U=0;U<ve.length;U++){let R=ve[U];if(!Ye&&lt!=="flow"&&typeof R.stepType=="string"&&(lt="flow"),R.type==="reasoning_start"){let G=typeof R.id=="string"?R.id:null,ne=typeof R.parentToolCallId=="string"&&R.parentToolCallId?R.parentToolCallId:null;if(G&&ne){k.set(G,ne),ke(G,ne,"reasoning");continue}let Z=R.id,le=x(Z);le.reasoning=le.reasoning??{id:Z,status:"streaming",chunks:[]},le.reasoning.startedAt=le.reasoning.startedAt??Date.now(),le.reasoning.completedAt=void 0,le.reasoning.durationMs=void 0,(R.scope==="loop"||R.scope==="turn")&&(le.reasoning.scope=R.scope),le.streaming=!0,le.reasoning.status="streaming",g(le)}else if(R.type==="reasoning_delta"){let G=typeof R.id=="string"?R.id:null;if(G&&k.has(G)&&D.has(G)){let le=D.get(G),Me=R.delta;Me&&le.reasoning&&(le.reasoning.chunks.push(String(Me)),g(le));continue}let ne=R.id,Z=x(ne);Z.reasoning=Z.reasoning??{id:ne,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Date.now(),R.delta&&Z.reasoning.chunks.push(R.delta),Z.reasoning.status="streaming",Z.streaming=!0,g(Z)}else if(R.type==="reasoning_complete"){let G=typeof R.id=="string"?R.id:null;if(G&&k.has(G)&&D.has(G)){let Me=D.get(G);if(Me.reasoning){let Ie=typeof R.text=="string"?R.text:"";Ie&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Ie),Me.reasoning.status="complete",Me.streaming=!1,g(Me)}k.delete(G),D.delete(G);continue}let ne=R.id,Z=typeof R.text=="string"?R.text:"";!Y.get(ne)&&(Z||R.scope==="loop")&&x(ne);let le=Y.get(ne);if(le?.reasoning){(R.scope==="loop"||R.scope==="turn")&&(le.reasoning.scope=R.scope),Z&&le.reasoning.chunks.length===0&&le.reasoning.chunks.push(Z),le.reasoning.status="complete",le.reasoning.completedAt=Date.now();let Me=le.reasoning.startedAt??Date.now();le.reasoning.durationMs=Math.max(0,(le.reasoning.completedAt??Date.now())-Me),le.streaming=!1,g(le)}}else if(R.type==="tool_start"){h&&(h.streaming=!1,g(h),h=null),typeof R.iteration=="number"&&(ht=R.iteration);let G=R.toolCallId,ne=R.toolName;if(j(ne)){P.add(G);continue}let Z=te(G),le=Z.toolCall??{id:G,status:"pending"};le.name=ne??le.name,le.status="running",le.success=void 0,le.error=void 0,le.duration=void 0,R.parameters!==void 0&&(le.args=R.parameters),le.startedAt=le.startedAt??K(R.startedAt),le.completedAt=void 0,le.durationMs=void 0,Z.toolCall=le,Z.streaming=!0,R.executionId&&(Z.agentMetadata={executionId:R.executionId,iteration:R.iteration}),g(Z)}else if(R.type==="tool_output_delta"){let G=R.toolCallId;if(P.has(G))continue;let ne=te(G),Z=ne.toolCall??{id:G,status:"running"};Z.startedAt=Z.startedAt??Date.now();let le=R.delta;le&&(Z.chunks=Z.chunks??[],Z.chunks.push(String(le))),Z.status="running",ne.toolCall=Z,ne.streaming=!0,R.executionId&&(ne.agentMetadata=ne.agentMetadata??{executionId:R.executionId,iteration:ht}),g(ne)}else if(R.type==="tool_complete"){let G=R.toolCallId;if(P.has(G)){P.delete(G);continue}let ne=te(G),Z=ne.toolCall??{id:G,status:"running"};Z.status="complete",R.result!==void 0&&(Z.result=R.result),Z.name=R.toolName??Z.name,Z.success=R.success,Z.error=R.error,Z.completedAt=Date.now();let le=R.executionTime;if(typeof le=="number")Z.durationMs=le,Z.duration=le;else{let Me=Z.startedAt??Date.now();Z.durationMs=Math.max(0,(Z.completedAt??Date.now())-Me)}ne.toolCall=Z,ne.streaming=!1,R.executionId&&(ne.agentMetadata=ne.agentMetadata??{executionId:R.executionId,iteration:R.iteration??ht}),g(ne)}else if(R.type==="await"&&R.toolName){let G=typeof R.toolCallId=="string"&&R.toolCallId.length>0?R.toolCallId:void 0,ne=G??R.toolId??`local-${p()}`,Z=te(ne),le=R.toolName,Me=R.origin==="webmcp"&&!Ca(le)?`webmcp:${le}`:le,Ie=Ca(Me),_e=Z.toolCall??{id:ne,status:"pending"};_e.name=Me,_e.args=R.parameters,_e.status=Ie?"running":"complete",_e.chunks=_e.chunks??[],_e.startedAt=_e.startedAt??K(R.awaitedAt),Ie?(_e.completedAt=void 0,_e.duration=void 0,_e.durationMs=void 0):_e.completedAt=_e.completedAt??_e.startedAt,Z.toolCall=_e,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:R.executionId??Z.agentMetadata?.executionId,awaitingLocalTool:!0,...G?{webMcpToolCallId:G}:{}},g(Z)}else if(R.type==="text_start"){let G=typeof R.id=="string"?R.id:null,ne=typeof R.parentToolCallId=="string"&&R.parentToolCallId?R.parentToolCallId:null;if(G&&ne){k.set(G,ne);continue}let Z=h;Z&&(lt==="flow"?(N(Z),Te=Z):(Z.streaming=!1,g(Z)),h=null),S=typeof R.id=="string"?R.id:S,E=""}else if(R.type==="text_delta"){let G=typeof R.id=="string"?R.id:null,ne=G?k.get(G):void 0;if(G&&ne){let Me=typeof R.delta=="string"?R.delta:"",Ie=(z.get(G)??"")+Me;if(z.set(G,Ie),Ie.trim()==="")continue;let _e=ke(G,ne);_e.agentMetadata={..._e.agentMetadata,executionId:R.executionId,parentToolId:ne},re(_e,Ie,Me,void 0);continue}if(S=typeof R.id=="string"?R.id:S,lt==="flow"){let Me=typeof R.delta=="string"?R.delta:"";if(E+=Me,E.trim()==="")continue;let Ie=w();Ie.agentMetadata={executionId:R.executionId,iteration:ht},re(Ie,E,Me,void 0),b=Ie;continue}let Z=typeof R.delta=="string"?R.delta:"";E+=Z;let le=w();le.agentMetadata={executionId:R.executionId,iteration:ht,turnId:dt??void 0,agentName:Pe?.agentName},re(le,E,Z,void 0),b=le}else if(R.type==="text_complete"){let G=typeof R.id=="string"?R.id:null;if(G&&k.has(G)){let Z=D.get(G);Z&&N(Z),k.delete(G),z.delete(G),D.delete(G);continue}let ne=h;ne&&(lt==="flow"?(N(ne),Te=ne):((ne.content??"")===""&&typeof R.text=="string"&&(ne.content=R.text),ne.streaming=!1,g(ne)),h=null),S=null,E=""}else if(R.type==="step_complete"){if(R.stepType==="tool")continue;if(R.success===!1){let G=R.error||"Step failed";n({type:"error",error:new Error(G)});let ne=h;ne&&ne.streaming&&(ne.streaming=!1,g(ne)),n({type:"status",status:"idle"});continue}{let G=Te;Te=null;let ne=R.stopReason,le=(R.result&&typeof R.result=="object"?R.result:null)?.response;if(G)ne&&(G.stopReason=ne),le!=null?xe(G,le):G.streaming!==!1&&(oe.delete(G.id),de.delete(G.id),G.streaming=!1,g(G));else{let Me=le!=null&&le!=="";if(Me||!!ne&&ne!=="end_turn"&&ne!=="unknown"){let _e=w();ne&&(_e.stopReason=ne),Me?N(_e,le):(_e.streaming=!1,g(_e))}}continue}}else if(R.type==="execution_start")lt=R.kind==="flow"?"flow":"agent",Ye=!0,lt==="agent"&&(Pe={executionId:R.executionId,agentId:R.agentId??"virtual",agentName:R.agentName??""});else if(R.type==="turn_start"){let G=typeof R.iteration=="number"?R.iteration:ht;if(G!==ht){if(Se==="separate"&&G>1){let ne=h;ne&&(ne.streaming=!1,g(ne),h=null)}ht=G}dt=typeof R.id=="string"?R.id:null,b=null}else if(R.type==="tool_input_delta"){let G=R.toolCallId;if(G){let ne=T.get(G);ne?.toolCall&&(ne.toolCall.chunks=ne.toolCall.chunks??[],ne.toolCall.chunks.push(R.delta??""),g(ne))}}else if(R.type==="tool_input_complete"){if(P.has(R.toolCallId))continue;let G=te(R.toolCallId),ne=G.toolCall;ne.args=R.parameters,ne.name=R.toolName??ne.name,g(G)}else if(R.type==="turn_complete"){let G=R.stopReason,ne=h??b;if(G&&ne!==null){let Z=R.id;(!Z||ne.agentMetadata?.turnId===Z)&&(ne.stopReason=G,g(ne))}dt===R.id&&(dt=null)}else if(R.type==="media_start"){let G=String(R.id);xt.set(G,{mediaType:typeof R.mediaType=="string"?R.mediaType:void 0,toolCallId:R.toolCallId,parts:[]})}else if(R.type==="media_delta"){let G=xt.get(String(R.id));G&&typeof R.delta=="string"&&G.parts.push(R.delta)}else if(R.type==="media_complete"){let G=String(R.id),ne=xt.get(G);xt.delete(G);let Z=(typeof R.mediaType=="string"?R.mediaType:void 0)??ne?.mediaType??"application/octet-stream",le=typeof R.data=="string"?R.data:void 0,Me=typeof R.url=="string"?R.url:ne&&ne.parts.length>0?ne.parts.join(""):void 0,Ie=null;if(le)Ie={type:"media",data:le,mediaType:Z};else if(Me){let qe=Z.toLowerCase();Ie={type:qe==="image"||qe.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Z}}let _e=R.toolCallId??ne?.toolCallId,ct=Ie?[Ie]:[],Tt=[];for(let qe of ct){if(!qe||typeof qe!="object")continue;let nt=qe,Ut=typeof nt.type=="string"?nt.type:void 0,tn=typeof nt.mediaType=="string"?nt.mediaType.toLowerCase():"",ee=null,Re="";if(Ut==="media"){let Fe=typeof nt.data=="string"?nt.data:void 0;if(!Fe)continue;Re=tn.length>0?tn:"application/octet-stream",ee=`data:${Re};base64,${Fe}`}else if(Ut==="image-url"){let Fe=typeof nt.url=="string"?nt.url:void 0;if(!Fe)continue;Re=tn,ee=Fe}else if(Ut==="file-url"){let Fe=typeof nt.url=="string"?nt.url:void 0;if(!Fe)continue;Re=tn,ee=Fe}else continue;if(ee)if(Ut==="image-url"||Re.startsWith("image/"))Tt.push({type:"image",image:ee,...Re.includes("/")?{mimeType:Re}:{}});else if(Re.startsWith("audio/"))Tt.push({type:"audio",audio:ee,mimeType:Re});else if(Re.startsWith("video/"))Tt.push({type:"video",video:ee,mimeType:Re});else{let Fe=Re||"application/octet-stream";Tt.push({type:"file",data:ee,mimeType:Fe,filename:lP(Fe)})}}if(Tt.length>0){let qe=p(),nt=_e,tn={id:`agent-media-${typeof nt=="string"&&nt.length>0?`${nt}-${qe}`:String(qe)}`,role:"assistant",content:"",contentParts:Tt,createdAt:new Date().toISOString(),streaming:!1,sequence:qe,agentMetadata:{executionId:R.executionId,iteration:ht}};g(tn);let ee=h;ee&&(ee.streaming=!1,g(ee)),h=null,C.current=null}}else if(R.type==="execution_complete"){let G=h;G&&(R.kind==="flow"&&G.streaming!==!1?N(G):(G.streaming=!1,g(G)),h=null),S=null,E="",Te=null,n({type:"status",status:"idle",terminal:!0})}else if(R.type==="execution_error"){let G=typeof R.error=="string"?R.error:R.error?.message??"Execution error";n({type:"error",error:new Error(G)})}else if(R.type!=="ping"){if(R.type==="approval_start"){let G=R.approvalId??`approval-${p()}`,ne={id:`approval-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:G,status:"pending",agentId:Pe?.agentId??"virtual",executionId:R.executionId??Pe?.executionId??"",toolName:R.toolName??"",toolType:R.toolType,description:R.description??`Execute ${R.toolName??"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters,...typeof R.toolCallId=="string"&&R.toolCallId?{toolCallId:R.toolCallId}:{}}};g(ne)}else if(R.type==="approval_complete"){let G=R.approvalId;if(G){let Z={id:`approval-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:G,status:R.decision??"approved",agentId:Pe?.agentId??"virtual",executionId:R.executionId??Pe?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};g(Z)}}else if(R.type==="artifact_start"||R.type==="artifact_delta"||R.type==="artifact_update"||R.type==="artifact_complete"){if(R.type==="artifact_start"){let G=R.artifactType,ne=String(R.id),Z=typeof R.title=="string"?R.title:void 0,le=R.file,Me;if(le&&typeof le=="object"&&!Array.isArray(le)&&typeof le.path=="string"&&typeof le.mimeType=="string"&&(Me={path:le.path,mimeType:le.mimeType,...typeof le.language=="string"?{language:le.language}:{}}),n({type:"artifact_start",id:ne,artifactType:G,title:Z,component:typeof R.component=="string"?R.component:void 0,...Me?{file:Me}:{}}),_.set(ne,{markdown:"",title:Z,file:Me}),!J.has(ne)){J.add(ne);let Ie=ks(e.config().features?.artifacts,{artifactType:G,...Me?{file:Me}:{}}),_e=typeof R.component=="string"?R.component:void 0,ct={id:`artifact-ref-${ne}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Il(Ie,{artifactId:ne,title:Z,artifactType:G,status:"streaming",...Me?{file:Me}:{},..._e?{component:_e}:{}})};I.set(ne,ct),g(ct)}}else if(R.type==="artifact_delta"){let G=String(R.id),ne=typeof R.delta=="string"?R.delta:String(R.delta??"");n({type:"artifact_delta",id:G,artDelta:ne});let Z=_.get(G);Z&&(Z.markdown+=ne)}else if(R.type==="artifact_update"){let G=R.props&&typeof R.props=="object"&&!Array.isArray(R.props)?R.props:{};n({type:"artifact_update",id:String(R.id),props:G,component:typeof R.component=="string"?R.component:void 0});let ne=_.get(String(R.id));ne&&(ne.props={...ne.props??{},...G})}else if(R.type==="artifact_complete"){let G=String(R.id);n({type:"artifact_complete",id:G});let ne=I.get(G);if(ne){ne.streaming=!1;try{let Z=JSON.parse(ne.rawContent??"{}");if(Z.props){Z.props.status="complete";let le=_.get(G);le?.markdown&&(Z.props.markdown=le.markdown),le?.file&&(Z.props.file=le.file),Z.component==="PersonaArtifactInline"&&le?.props&&Object.keys(le.props).length>0&&(Z.props.componentProps=le.props)}ne.rawContent=JSON.stringify(Z)}catch{}_.delete(G),g(ne),I.delete(G)}}}else if(R.type==="error"&&R.recoverable===!1&&R.error!=null&&R.error!==""){let G=typeof R.error=="string"?R.error:R.error?.message!=null?String(R.error.message):"Execution error";n({type:"error",error:new Error(G)});let ne=h;ne&&ne.streaming&&(ne.streaming=!1,g(ne)),n({type:"status",status:"idle"})}}}ve.length=0};;){let{done:U,value:R}=await s.read();if(U)break;l+=i.decode(R,{stream:!0});let G=l.split(`
4
+ `).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()=>{}}},Bl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ow=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},rw=()=>{let e=BL();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)}},sw=()=>{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,xa.parse)(n,xa.STR|xa.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ZC(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ZC(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},iw=()=>{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 Ls,rg,Dl,Sa,DL,_L,lw,cw,OL,NL,FL,VL,$L,sg,ig,dw,ag,pw,UL,zL,aw,uw,Mi,lg,Aa,_l,qL,jL,KL,fw,GL,YL,XL,mw,QL,JL,Ti,gw,Fo,ZL,Ma,Ps,eP,tP,fp,hw,yw,cg,nP,oP,bw,Ei,dg,Is,mp,gp=ie(()=>{"use strict";Ls=require("partial-json");Ge();rg="ask_user_question",Dl=8,Sa="data-persona-ask-sheet-for",DL="Other",_L="Other\u2026",lw="Type your own answer here",cw="Send",OL="Next",NL="Back",FL="Submit all",VL="Skip",$L=3,sg="data-ask-current-index",ig="data-ask-question-count",dw="data-ask-answers",ag="data-ask-grouped",pw="data-ask-layout",UL=e=>e.layout==="pills"?"pills":"rows",zL=e=>e.getAttribute(pw)==="pills"?"pills":"rows",aw=!1,uw=e=>e.replace(/["\\]/g,"\\$&"),Mi=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===rg,lg=e=>e?.features?.askUserQuestion??{},Aa=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,Ls.parse)(r,Ls.STR|Ls.OBJ|Ls.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},_l=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Dl&&!aw&&(aw=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Dl}.`)),t.slice(0,Dl)},qL=e=>_l(e)[0]??null,jL=(e,t)=>_l(e)[t]??null,KL=(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))},fw=(e,t,n)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},GL=(e,t,n,o)=>{let s=v("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 i=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let d=v("span","persona-ask-row-description");d.textContent=e.description,i.appendChild(d)}s.appendChild(i);let c=fw(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},YL=e=>{let n=v("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},XL=(e,t,n,o)=>{let s=v("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 i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!n){for(let p=0;p<$L;p++)s.appendChild(YL(o));return s}if(c.forEach((p,f)=>{s.appendChild(GL(p,f,o,i))}),e?.allowFreeText!==!1){let p=o==="rows"?DL:_L;if(o==="rows"){let f=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(c.length)),f.setAttribute("data-ask-other-row","true");let m=v("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??lw,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??p),m.appendChild(g),f.appendChild(m);let h=fw(o,i,c.length);h&&f.appendChild(h),s.appendChild(f)}else{let f=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??p,s.appendChild(f)}}return s},mw=(e,t)=>{let o=v("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??lw,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??cw,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},QL=e=>{let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??cw,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},JL=(e,t,n)=>{let o=v("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=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??NL,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=v("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??VL,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??FL:n.nextLabel??OL,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ti=e=>{let t=e.getAttribute(dw);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},gw=(e,t)=>{e.setAttribute(dw,JSON.stringify(t))},Fo=e=>{let t=Number(e.getAttribute(sg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ZL=(e,t)=>{e.setAttribute(sg,String(Math.max(0,Math.floor(t))))},Ma=e=>{let t=Number(e.getAttribute(ig)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ps=e=>e.getAttribute(ag)==="true",eP=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(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)))},fp=(e,t)=>{let{payload:n}=Aa(t),o=_l(n),r=Ti(e),s={},i=new Set;return o.forEach((l,c)=>{let d=typeof l?.question=="string"?l.question:"";d&&(i.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),i.add(d),Object.prototype.hasOwnProperty.call(r,c)&&(s[d]=r[c]))}),s},hw=e=>{let t=Ti(e),n=Fo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let d=c.getAttribute("data-option-label")??"",p=r.has(d);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},yw=e=>{if(!Ps(e))return;let t=Ti(e),n=Fo(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 i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},cg=(e,t,n)=>{let o=lg(n),r=zL(e),{payload:s,complete:i}=Aa(t),l=Ps(e),c=Fo(e),d=Ma(e),p=l?jL(s,c):qL(s),f=!!p?.multiSelect,m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=l?`${c+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let S=typeof p?.question=="string"?p.question:"";h.textContent=S,h.classList.toggle("persona-ask-question-skeleton",!S&&!i)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let S=XL(p,o,i,r);b.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(mw(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!C?e.appendChild(QL(o)):(!f||l)&&C&&C.remove(),e.setAttribute("data-multi-select",f?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=JL(c,d,o);A?A.replaceWith(S):e.appendChild(S)}else A&&A.remove();hw(e),yw(e)},nP=(e,t,n)=>{let o=lg(t),r=UL(o),s=e.toolCall.id,i=_l(n),l=Math.max(1,i.length),c=l>1,d=eP(e,i),p=c?tP(e,l):0,f=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sa,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(ig,String(l)),f.setAttribute(sg,String(p)),f.setAttribute(ag,c?"true":"false"),f.setAttribute(pw,r),gw(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),KL(f,o);let m=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=v("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",m.appendChild(g);let h=v("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",m.appendChild(h),f.appendChild(m);let C=v("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 C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),f.appendChild(C),r!=="rows"&&f.appendChild(mw(o,r)),cg(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},oP=(e,t,n)=>{let{payload:o}=Aa(t),r=Math.max(1,_l(o).length);r>Ma(e)&&(e.setAttribute(ig,String(r)),r>1&&!Ps(e)&&e.setAttribute(ag,"true")),cg(e,t,n)},bw=(e,t,n)=>{if(!n||!Mi(e)||lg(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sa}]`).forEach(d=>{d.getAttribute(Sa)!==r&&d.remove()});let i=n.querySelector(`[${Sa}="${uw(r)}"]`);if(i){oP(i,e,t);return}let{payload:l}=Aa(e),c=nP(e,t,l);n.appendChild(c)},Ei=(e,t)=>{if(!e)return;let n=t?`[${Sa}="${uw(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)})},dg=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=Fo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,gw(e,n),hw(e),yw(e)},mp=(e,t,n,o)=>{let r=Ma(e),s=Math.max(0,Math.min(r-1,o));ZL(e,s),cg(e,t,n)}});var Yr,rP,Cw,ww,Ol,sP,xw,vw,iP,Hs,Nl=ie(()=>{"use strict";Yr="suggest_replies",rP={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},Cw={name:Yr,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:rP,origin:"sdk",annotations:{readOnlyHint:!0}},ww=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ol=e=>e.variant==="tool"&&e.toolCall?.name===Yr,sP=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 i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});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},xw=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ol(n))continue;let o=sP(n.toolCall?.args);return o.length>0?o:null}return null},vw=new Set,iP=(e,t,n)=>{let o=`${e}:${t}:${n}`;vw.has(o)||(vw.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Hs=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&iP(i,c,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 aP,lP,Fl,pg=ie(()=>{"use strict";gp();Nl();aP={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Dl,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},lP={name:rg,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:aP,origin:"sdk",annotations:{readOnlyHint:!0}},Fl=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(lP),Hs(e).expose&&t.push(Cw),t}});var Cn,Jn,Ta,hp,nr=ie(()=>{"use strict";Cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Jn=1e5,Ta=Jn+1,hp="https://api.runtype.com"});async function Sw(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(d,p)=>fetch(`${e.clientApiBase()}${d}`,{method:"POST",headers:o,body:JSON.stringify({...p,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let d=await c.clone().json().catch(()=>null);if(!d||d.error==="Not Found")return s(i)}return c}async function Aw(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||hp}/resume`,i,l=null;if(r){let p=await e.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(d.sessionId=i),r&&i){let p=[...Fl(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:f,commit:m}=await e.sendWithClientToolsDiff(i,p,g=>{let h={...d,...g};return e.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(s,{method:"POST",headers:c,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return f.ok&&m(),f}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(d),signal:o?.signal})}var Mw=ie(()=>{"use strict";pg();nr()});var kw={};En(kw,{preferFinalStructuredContent:()=>Ew,resolveApproval:()=>Sw,resumeFlow:()=>Aw,streamResponse:()=>pP});function cP(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"}function Ew(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=Tw(n);if(!Tw(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=Bl(e);return Bl(t)!==null&&i===null?t:e}async function dP(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=p=>{let f={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=f,r(f),f},d=p=>o.current?o.current:c(p);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let p=d(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)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.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 function pP(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),d=0,p=()=>c+d++,f=U=>{let R=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,G=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,ne=U.tools?U.tools.map(Z=>({...Z,chunks:Z.chunks?[...Z.chunks]:void 0})):void 0;return{...U,reasoning:R,toolCall:G,tools:ne}},m=U=>{if(U.role!=="assistant"||U.variant)return!0;let R=Array.isArray(U.contentParts)&&U.contentParts.length>0,G=typeof U.rawContent=="string"&&U.rawContent.trim()!=="";return typeof U.content=="string"&&U.content.trim()!==""||R||G||!!U.stopReason},g=U=>{m(U)&&n({type:"message",message:f(U)})},h=null,b=null,C={current:null},A={current:null},S=null,E="",k=new Map,D=new Map,z=new Map,Y=new Map,T=new Map,W=o,L=!1,w=()=>{if(h)return h;let U,R="",G=S;return!L&&W?(U=W,L=!0,R=r??""):W&&G?U=`${W}_${G}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:U,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(h),h},x=U=>{let R=Y.get(U);if(R)return R;let G={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:U,status:"streaming",chunks:[]}};return Y.set(U,G),g(G),G},P=new Set,I=new Map,J=new Set,_=new Map,j=U=>{if(!U)return!1;let R=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return R==="emit_artifact_markdown"||R==="emit_artifact_component"},te=U=>{let R=T.get(U);if(R)return R;let G={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:U,status:"pending"}};return T.set(U,G),g(G),G},K=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let R=Number(U);if(!Number.isNaN(R)&&Number.isFinite(R))return R;let G=Date.parse(U);if(!Number.isNaN(G))return G}return Date.now()},X=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},oe=new Map,de=new Map,xe=(U,R)=>{let G=X(R),ne=de.get(U.id),Z=Ew(ne,G);U.rawContent=Z;let le=oe.get(U.id),Me=qe=>{let nt=U.content??"";qe.trim()!==""&&(nt.trim().length===0||qe.startsWith(nt)||qe.trimStart().startsWith(nt.trim()))&&(U.content=qe)},Ie=()=>{if(le){let qe=le.close?.();qe instanceof Promise&&qe.catch(()=>{})}oe.delete(U.id),de.delete(U.id),U.streaming=!1,g(U)};if(!le){Me(G),Ie();return}let _e=Bl(Z);if(_e!==null&&_e.trim()!==""){Me(_e),Ie();return}let ct=qe=>{let nt=typeof qe=="string"?qe:qe?.text??null;if(nt!==null&&nt.trim()!=="")return nt;let Ut=le.getExtractedText();return Ut!==null&&Ut.trim()!==""?Ut:G},Tt;try{Tt=le.processChunk(Z)}catch{Me(G),Ie();return}if(Tt instanceof Promise){Tt.then(qe=>{Me(ct(qe)),Ie()}).catch(()=>{Me(G),Ie()});return}Me(ct(Tt)),Ie()},Te=null,re=(U,R,G,ne)=>{U.rawContent=R,oe.has(U.id)||oe.set(U.id,e.createStreamParser());let Z=oe.get(U.id),le=R.trim().startsWith("{")||R.trim().startsWith("[");if(le&&de.set(U.id,R),Z.__isPlainTextParser===!0){U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U);return}let Ie=Z.processChunk(R);if(Ie instanceof Promise)Ie.then(_e=>{let ct=typeof _e=="string"?_e:_e?.text??null;ct!==null&&ct.trim()!==""?(U.content=ct,g(U)):!le&&!R.trim().startsWith("<")&&(U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U))}).catch(()=>{U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U)});else{let _e=typeof Ie=="string"?Ie:Ie?.text??null;_e!==null&&_e.trim()!==""?(U.content=_e,g(U)):!le&&!R.trim().startsWith("<")&&(U.content=ne!==void 0?R:U.content+G,de.delete(U.id),oe.delete(U.id),U.rawContent=void 0,g(U))}},N=(U,R)=>{let G=R??U.content;if(G==null||G===""){U.streaming=!1,g(U);return}let Z=de.get(U.id)??X(G);U.rawContent=Z;let le=oe.get(U.id),Me=null,Ie=!1;if(le&&(Me=le.getExtractedText(),Me===null&&(Me=Bl(Z)),Me===null)){let _e=le.processChunk(Z);_e instanceof Promise?(Ie=!0,_e.then(ct=>{let Tt=typeof ct=="string"?ct:ct?.text??null;Tt!==null&&(U.content=Tt,U.streaming=!1,oe.delete(U.id),de.delete(U.id),g(U))}).catch(()=>{})):Me=typeof _e=="string"?_e:_e?.text??null}if(!Ie){Me!==null&&Me.trim()!==""?U.content=Me:de.has(U.id)||(U.content=X(G));let _e=oe.get(U.id);if(_e){let ct=_e.close?.();ct instanceof Promise&&ct.catch(()=>{}),oe.delete(U.id)}de.delete(U.id),U.streaming=!1,g(U)}},ke=(U,R,G)=>{let ne=D.get(U);if(ne)return ne;let Z={id:`nested-${R}-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...G?{variant:G}:{},...G==="reasoning"?{reasoning:{id:U,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:R}};return D.set(U,Z),g(Z),Z},ve=[],tt,xt=new Map,ht=0,lt="agent",Ye=!1,dt=null,Pe=null,Se=e.config().iterationDisplay??"separate";for(tt=()=>{for(let U=0;U<ve.length;U++){let R=ve[U];if(!Ye&&lt!=="flow"&&typeof R.stepType=="string"&&(lt="flow"),R.type==="reasoning_start"){let G=typeof R.id=="string"?R.id:null,ne=typeof R.parentToolCallId=="string"&&R.parentToolCallId?R.parentToolCallId:null;if(G&&ne){k.set(G,ne),ke(G,ne,"reasoning");continue}let Z=R.id,le=x(Z);le.reasoning=le.reasoning??{id:Z,status:"streaming",chunks:[]},le.reasoning.startedAt=le.reasoning.startedAt??Date.now(),le.reasoning.completedAt=void 0,le.reasoning.durationMs=void 0,(R.scope==="loop"||R.scope==="turn")&&(le.reasoning.scope=R.scope),le.streaming=!0,le.reasoning.status="streaming",g(le)}else if(R.type==="reasoning_delta"){let G=typeof R.id=="string"?R.id:null;if(G&&k.has(G)&&D.has(G)){let le=D.get(G),Me=R.delta;Me&&le.reasoning&&(le.reasoning.chunks.push(String(Me)),g(le));continue}let ne=R.id,Z=x(ne);Z.reasoning=Z.reasoning??{id:ne,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Date.now(),R.delta&&Z.reasoning.chunks.push(R.delta),Z.reasoning.status="streaming",Z.streaming=!0,g(Z)}else if(R.type==="reasoning_complete"){let G=typeof R.id=="string"?R.id:null;if(G&&k.has(G)&&D.has(G)){let Me=D.get(G);if(Me.reasoning){let Ie=typeof R.text=="string"?R.text:"";Ie&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Ie),Me.reasoning.status="complete",Me.streaming=!1,g(Me)}k.delete(G),D.delete(G);continue}let ne=R.id,Z=typeof R.text=="string"?R.text:"";!Y.get(ne)&&(Z||R.scope==="loop")&&x(ne);let le=Y.get(ne);if(le?.reasoning){(R.scope==="loop"||R.scope==="turn")&&(le.reasoning.scope=R.scope),Z&&le.reasoning.chunks.length===0&&le.reasoning.chunks.push(Z),le.reasoning.status="complete",le.reasoning.completedAt=Date.now();let Me=le.reasoning.startedAt??Date.now();le.reasoning.durationMs=Math.max(0,(le.reasoning.completedAt??Date.now())-Me),le.streaming=!1,g(le)}}else if(R.type==="tool_start"){h&&(h.streaming=!1,g(h),h=null),typeof R.iteration=="number"&&(ht=R.iteration);let G=R.toolCallId,ne=R.toolName;if(j(ne)){P.add(G);continue}let Z=te(G),le=Z.toolCall??{id:G,status:"pending"};le.name=ne??le.name,le.status="running",le.success=void 0,le.error=void 0,le.duration=void 0,R.parameters!==void 0&&(le.args=R.parameters),le.startedAt=le.startedAt??K(R.startedAt),le.completedAt=void 0,le.durationMs=void 0,Z.toolCall=le,Z.streaming=!0,R.executionId&&(Z.agentMetadata={executionId:R.executionId,iteration:R.iteration}),g(Z)}else if(R.type==="tool_output_delta"){let G=R.toolCallId;if(P.has(G))continue;let ne=te(G),Z=ne.toolCall??{id:G,status:"running"};Z.startedAt=Z.startedAt??Date.now();let le=R.delta;le&&(Z.chunks=Z.chunks??[],Z.chunks.push(String(le))),Z.status="running",ne.toolCall=Z,ne.streaming=!0,R.executionId&&(ne.agentMetadata=ne.agentMetadata??{executionId:R.executionId,iteration:ht}),g(ne)}else if(R.type==="tool_complete"){let G=R.toolCallId;if(P.has(G)){P.delete(G);continue}let ne=te(G),Z=ne.toolCall??{id:G,status:"running"};Z.status="complete",R.result!==void 0&&(Z.result=R.result),Z.name=R.toolName??Z.name,Z.success=R.success,Z.error=R.error,Z.completedAt=Date.now();let le=R.executionTime;if(typeof le=="number")Z.durationMs=le,Z.duration=le;else{let Me=Z.startedAt??Date.now();Z.durationMs=Math.max(0,(Z.completedAt??Date.now())-Me)}ne.toolCall=Z,ne.streaming=!1,R.executionId&&(ne.agentMetadata=ne.agentMetadata??{executionId:R.executionId,iteration:R.iteration??ht}),g(ne)}else if(R.type==="await"&&R.toolName){let G=typeof R.toolCallId=="string"&&R.toolCallId.length>0?R.toolCallId:void 0,ne=G??R.toolId??`local-${p()}`,Z=te(ne),le=R.toolName,Me=R.origin==="webmcp"&&!Ca(le)?`webmcp:${le}`:le,Ie=Ca(Me),_e=Z.toolCall??{id:ne,status:"pending"};_e.name=Me,_e.args=R.parameters,_e.status=Ie?"running":"complete",_e.chunks=_e.chunks??[],_e.startedAt=_e.startedAt??K(R.awaitedAt),Ie?(_e.completedAt=void 0,_e.duration=void 0,_e.durationMs=void 0):_e.completedAt=_e.completedAt??_e.startedAt,Z.toolCall=_e,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:R.executionId??Z.agentMetadata?.executionId,awaitingLocalTool:!0,...G?{webMcpToolCallId:G}:{}},g(Z)}else if(R.type==="text_start"){let G=typeof R.id=="string"?R.id:null,ne=typeof R.parentToolCallId=="string"&&R.parentToolCallId?R.parentToolCallId:null;if(G&&ne){k.set(G,ne);continue}let Z=h;Z&&(lt==="flow"?(N(Z),Te=Z):(Z.streaming=!1,g(Z)),h=null),S=typeof R.id=="string"?R.id:S,E=""}else if(R.type==="text_delta"){let G=typeof R.id=="string"?R.id:null,ne=G?k.get(G):void 0;if(G&&ne){let Me=typeof R.delta=="string"?R.delta:"",Ie=(z.get(G)??"")+Me;if(z.set(G,Ie),Ie.trim()==="")continue;let _e=ke(G,ne);_e.agentMetadata={..._e.agentMetadata,executionId:R.executionId,parentToolId:ne},re(_e,Ie,Me,void 0);continue}if(S=typeof R.id=="string"?R.id:S,lt==="flow"){let Me=typeof R.delta=="string"?R.delta:"";if(E+=Me,E.trim()==="")continue;let Ie=w();Ie.agentMetadata={executionId:R.executionId,iteration:ht},re(Ie,E,Me,void 0),b=Ie;continue}let Z=typeof R.delta=="string"?R.delta:"";E+=Z;let le=w();le.agentMetadata={executionId:R.executionId,iteration:ht,turnId:dt??void 0,agentName:Pe?.agentName},re(le,E,Z,void 0),b=le}else if(R.type==="text_complete"){let G=typeof R.id=="string"?R.id:null;if(G&&k.has(G)){let Z=D.get(G);Z&&N(Z),k.delete(G),z.delete(G),D.delete(G);continue}let ne=h;ne&&(lt==="flow"?(N(ne),Te=ne):((ne.content??"")===""&&typeof R.text=="string"&&(ne.content=R.text),ne.streaming=!1,g(ne)),h=null),S=null,E=""}else if(R.type==="step_complete"){if(R.stepType==="tool")continue;if(R.success===!1){let G=R.error||"Step failed";n({type:"error",error:new Error(G)});let ne=h;ne&&ne.streaming&&(ne.streaming=!1,g(ne)),n({type:"status",status:"idle"});continue}{let G=Te;Te=null;let ne=R.stopReason,le=(R.result&&typeof R.result=="object"?R.result:null)?.response;if(G)ne&&(G.stopReason=ne),le!=null?xe(G,le):G.streaming!==!1&&(oe.delete(G.id),de.delete(G.id),G.streaming=!1,g(G));else{let Me=le!=null&&le!=="";if(Me||!!ne&&ne!=="end_turn"&&ne!=="unknown"){let _e=w();ne&&(_e.stopReason=ne),Me?N(_e,le):(_e.streaming=!1,g(_e))}}continue}}else if(R.type==="execution_start")lt=R.kind==="flow"?"flow":"agent",Ye=!0,lt==="agent"&&(Pe={executionId:R.executionId,agentId:R.agentId??"virtual",agentName:R.agentName??""});else if(R.type==="turn_start"){let G=typeof R.iteration=="number"?R.iteration:ht;if(G!==ht){if(Se==="separate"&&G>1){let ne=h;ne&&(ne.streaming=!1,g(ne),h=null)}ht=G}dt=typeof R.id=="string"?R.id:null,b=null}else if(R.type==="tool_input_delta"){let G=R.toolCallId;if(G){let ne=T.get(G);ne?.toolCall&&(ne.toolCall.chunks=ne.toolCall.chunks??[],ne.toolCall.chunks.push(R.delta??""),g(ne))}}else if(R.type==="tool_input_complete"){if(P.has(R.toolCallId))continue;let G=te(R.toolCallId),ne=G.toolCall;ne.args=R.parameters,ne.name=R.toolName??ne.name,g(G)}else if(R.type==="turn_complete"){let G=R.stopReason,ne=h??b;if(G&&ne!==null){let Z=R.id;(!Z||ne.agentMetadata?.turnId===Z)&&(ne.stopReason=G,g(ne))}dt===R.id&&(dt=null)}else if(R.type==="media_start"){let G=String(R.id);xt.set(G,{mediaType:typeof R.mediaType=="string"?R.mediaType:void 0,toolCallId:R.toolCallId,parts:[]})}else if(R.type==="media_delta"){let G=xt.get(String(R.id));G&&typeof R.delta=="string"&&G.parts.push(R.delta)}else if(R.type==="media_complete"){let G=String(R.id),ne=xt.get(G);xt.delete(G);let Z=(typeof R.mediaType=="string"?R.mediaType:void 0)??ne?.mediaType??"application/octet-stream",le=typeof R.data=="string"?R.data:void 0,Me=typeof R.url=="string"?R.url:ne&&ne.parts.length>0?ne.parts.join(""):void 0,Ie=null;if(le)Ie={type:"media",data:le,mediaType:Z};else if(Me){let qe=Z.toLowerCase();Ie={type:qe==="image"||qe.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Z}}let _e=R.toolCallId??ne?.toolCallId,ct=Ie?[Ie]:[],Tt=[];for(let qe of ct){if(!qe||typeof qe!="object")continue;let nt=qe,Ut=typeof nt.type=="string"?nt.type:void 0,tn=typeof nt.mediaType=="string"?nt.mediaType.toLowerCase():"",ee=null,Re="";if(Ut==="media"){let Fe=typeof nt.data=="string"?nt.data:void 0;if(!Fe)continue;Re=tn.length>0?tn:"application/octet-stream",ee=`data:${Re};base64,${Fe}`}else if(Ut==="image-url"){let Fe=typeof nt.url=="string"?nt.url:void 0;if(!Fe)continue;Re=tn,ee=Fe}else if(Ut==="file-url"){let Fe=typeof nt.url=="string"?nt.url:void 0;if(!Fe)continue;Re=tn,ee=Fe}else continue;if(ee)if(Ut==="image-url"||Re.startsWith("image/"))Tt.push({type:"image",image:ee,...Re.includes("/")?{mimeType:Re}:{}});else if(Re.startsWith("audio/"))Tt.push({type:"audio",audio:ee,mimeType:Re});else if(Re.startsWith("video/"))Tt.push({type:"video",video:ee,mimeType:Re});else{let Fe=Re||"application/octet-stream";Tt.push({type:"file",data:ee,mimeType:Fe,filename:cP(Fe)})}}if(Tt.length>0){let qe=p(),nt=_e,tn={id:`agent-media-${typeof nt=="string"&&nt.length>0?`${nt}-${qe}`:String(qe)}`,role:"assistant",content:"",contentParts:Tt,createdAt:new Date().toISOString(),streaming:!1,sequence:qe,agentMetadata:{executionId:R.executionId,iteration:ht}};g(tn);let ee=h;ee&&(ee.streaming=!1,g(ee)),h=null,C.current=null}}else if(R.type==="execution_complete"){let G=h;G&&(R.kind==="flow"&&G.streaming!==!1?N(G):(G.streaming=!1,g(G)),h=null),S=null,E="",Te=null,n({type:"status",status:"idle",terminal:!0})}else if(R.type==="execution_error"){let G=typeof R.error=="string"?R.error:R.error?.message??"Execution error";n({type:"error",error:new Error(G)})}else if(R.type!=="ping"){if(R.type==="approval_start"){let G=R.approvalId??`approval-${p()}`,ne={id:`approval-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:G,status:"pending",agentId:Pe?.agentId??"virtual",executionId:R.executionId??Pe?.executionId??"",toolName:R.toolName??"",toolType:R.toolType,description:R.description??`Execute ${R.toolName??"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters,...typeof R.toolCallId=="string"&&R.toolCallId?{toolCallId:R.toolCallId}:{}}};g(ne)}else if(R.type==="approval_complete"){let G=R.approvalId;if(G){let Z={id:`approval-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:G,status:R.decision??"approved",agentId:Pe?.agentId??"virtual",executionId:R.executionId??Pe?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};g(Z)}}else if(R.type==="artifact_start"||R.type==="artifact_delta"||R.type==="artifact_update"||R.type==="artifact_complete"){if(R.type==="artifact_start"){let G=R.artifactType,ne=String(R.id),Z=typeof R.title=="string"?R.title:void 0,le=R.file,Me;if(le&&typeof le=="object"&&!Array.isArray(le)&&typeof le.path=="string"&&typeof le.mimeType=="string"&&(Me={path:le.path,mimeType:le.mimeType,...typeof le.language=="string"?{language:le.language}:{}}),n({type:"artifact_start",id:ne,artifactType:G,title:Z,component:typeof R.component=="string"?R.component:void 0,...Me?{file:Me}:{}}),_.set(ne,{markdown:"",title:Z,file:Me}),!J.has(ne)){J.add(ne);let Ie=ks(e.config().features?.artifacts,{artifactType:G,...Me?{file:Me}:{}}),_e=typeof R.component=="string"?R.component:void 0,ct={id:`artifact-ref-${ne}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Il(Ie,{artifactId:ne,title:Z,artifactType:G,status:"streaming",...Me?{file:Me}:{},..._e?{component:_e}:{}})};I.set(ne,ct),g(ct)}}else if(R.type==="artifact_delta"){let G=String(R.id),ne=typeof R.delta=="string"?R.delta:String(R.delta??"");n({type:"artifact_delta",id:G,artDelta:ne});let Z=_.get(G);Z&&(Z.markdown+=ne)}else if(R.type==="artifact_update"){let G=R.props&&typeof R.props=="object"&&!Array.isArray(R.props)?R.props:{};n({type:"artifact_update",id:String(R.id),props:G,component:typeof R.component=="string"?R.component:void 0});let ne=_.get(String(R.id));ne&&(ne.props={...ne.props??{},...G})}else if(R.type==="artifact_complete"){let G=String(R.id);n({type:"artifact_complete",id:G});let ne=I.get(G);if(ne){ne.streaming=!1;try{let Z=JSON.parse(ne.rawContent??"{}");if(Z.props){Z.props.status="complete";let le=_.get(G);le?.markdown&&(Z.props.markdown=le.markdown),le?.file&&(Z.props.file=le.file),Z.component==="PersonaArtifactInline"&&le?.props&&Object.keys(le.props).length>0&&(Z.props.componentProps=le.props)}ne.rawContent=JSON.stringify(Z)}catch{}_.delete(G),g(ne),I.delete(G)}}}else if(R.type==="error"&&R.recoverable===!1&&R.error!=null&&R.error!==""){let G=typeof R.error=="string"?R.error:R.error?.message!=null?String(R.error.message):"Execution error";n({type:"error",error:new Error(G)});let ne=h;ne&&ne.streaming&&(ne.streaming=!1,g(ne)),n({type:"status",status:"idle"})}}}ve.length=0};;){let{done:U,value:R}=await s.read();if(U)break;l+=i.decode(R,{stream:!0});let G=l.split(`
5
5
 
6
6
  `);l=G.pop()??"";for(let ne of G){let Z=ne.split(`
7
- `),le="message",Me="",Ie=null;for(let nt of Z)nt.startsWith("event:")?le=nt.replace("event:","").trim():nt.startsWith("data:")?Me+=nt.replace("data:","").trim():nt.startsWith("id:")&&(Ie=nt.slice(3).trim());let _e=()=>{Ie!==null&&Ie!==""&&n({type:"cursor",id:Ie})};if(!Me){_e();continue}let ct;try{ct=JSON.parse(Me)}catch(nt){n({type:"error",error:nt instanceof Error?nt:new Error("Failed to parse chat stream payload")});continue}let Tt=ct!==null&&typeof ct=="object"&&!Array.isArray(ct)?ct:null,qe=le!=="message"?le:typeof Tt?.type=="string"?Tt.type:"message";if(e.onSSEEvent?.(qe,ct),e.parseSSEEvent){C.current=h;let nt=await cP(e,ct,n,C,g,p,A);if(C.current&&C.current!==h&&(h=C.current),nt){_e();continue}}Tt&&(ve.push({...Tt,type:qe}),tt()),_e()}}tt()}var Tw,Lw=ie(()=>{"use strict";Ai();Hl();Gr();Mw();Tw=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var Iw,fP,yp,vp,mP,bp,gP,hP,yP,or,bP,vP,CP,wP,Hw=ie(()=>{"use strict";Iw="webmcp:",fP=e=>e.startsWith(Iw)?e.slice(Iw.length):e,yp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},vp=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#t=3e4}#e;#t;#n=!1;#o=null;#a=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#c()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let t=this.#c();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return yp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#p(r.name)).map(r=>{let s=gP(r.annotations);return{name:r.name,description:r.description,parametersSchema:hP(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#s(),this.config.enabled!==!0)return or("WebMCP is not enabled on this widget.");let r=this.#c();if(!r){let h=typeof document<"u"&&!!document.modelContext;return or(h?"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=fP(t),i;try{i=await r.getTools()}catch(h){let b=h instanceof Error?h.message:String(h);return or(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(h=>h.name===s);if(!l)return or(`WebMCP tool not registered on this page: ${s}`);if(!this.#p(s))return or(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return or("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),d={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#f(d))return or("User declined the tool call.");if(o?.aborted)return or("Aborted by cancel()");let p=new AbortController,f=!1,m=setTimeout(()=>{f=!0,p.abort()},this.#t),g=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",g,{once:!0}));try{let h=await r.executeTool(l,CP(n),{signal:p.signal});return yP(h)}catch(h){if(f)return or(`WebMCP tool '${s}' timed out after ${this.#t}ms`);if(o?.aborted)return or("Aborted by cancel()");let b=h instanceof Error?h.message:String(h);return or(b)}finally{clearTimeout(m),o&&o.removeEventListener("abort",g)}}#s(){return this.config.enabled!==!0?Promise.resolve():(this.#o||(this.#o=this.#g()),this.#o)}async#g(){try{if(this.#c()){this.#n=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#n=!0}catch(t){yp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#n=!1}}#c(){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.#a||(this.#a=!0,yp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async#f(t){let n=this.#e??bP;try{return await n(t)}catch(o){return yp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#p(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>mP(t,o))}},mP=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},bp={type:"object",properties:{}},gP=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},hP=e=>{if(e===void 0||e==="")return{...bp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...bp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...bp}}catch{return{...bp}}},yP=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:wP(t)}]}},or=e=>({isError:!0,content:[{type:"text",text:e}]}),bP=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=vP(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
7
+ `),le="message",Me="",Ie=null;for(let nt of Z)nt.startsWith("event:")?le=nt.replace("event:","").trim():nt.startsWith("data:")?Me+=nt.replace("data:","").trim():nt.startsWith("id:")&&(Ie=nt.slice(3).trim());let _e=()=>{Ie!==null&&Ie!==""&&n({type:"cursor",id:Ie})};if(!Me){_e();continue}let ct;try{ct=JSON.parse(Me)}catch(nt){n({type:"error",error:nt instanceof Error?nt:new Error("Failed to parse chat stream payload")});continue}let Tt=ct!==null&&typeof ct=="object"&&!Array.isArray(ct)?ct:null,qe=le!=="message"?le:typeof Tt?.type=="string"?Tt.type:"message";if(e.onSSEEvent?.(qe,ct),e.parseSSEEvent){C.current=h;let nt=await dP(e,ct,n,C,g,p,A);if(C.current&&C.current!==h&&(h=C.current),nt){_e();continue}}Tt&&(ve.push({...Tt,type:qe}),tt()),_e()}}tt()}var Tw,Lw=ie(()=>{"use strict";Ai();Hl();Gr();Mw();Tw=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var Iw,mP,yp,vp,gP,bp,hP,yP,bP,vP,or,CP,wP,Hw,xP,Rw=ie(()=>{"use strict";Iw="webmcp:",mP=e=>e.startsWith(Iw)?e.slice(Iw.length):e,yp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},vp=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#t=3e4}#e;#t;#n=!1;#o=null;#a=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#c()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let t=this.#c();if(!t)return[];let n;try{n=(await t.getTools()).filter(Hw)}catch(r){return yp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#p(r.name)).map(r=>{let s=hP(r.annotations);return{name:r.name,description:r.description,parametersSchema:yP(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#s(),this.config.enabled!==!0)return or("WebMCP is not enabled on this widget.");let r=this.#c();if(!r){let h=typeof document<"u"&&!!document.modelContext;return or(h?"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=mP(t),i;try{i=(await r.getTools()).filter(Hw)}catch(h){let b=h instanceof Error?h.message:String(h);return or(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(h=>h.name===s);if(!l)return or(`WebMCP tool not registered on this page: ${s}`);if(!this.#p(s))return or(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return or("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),d={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#f(d))return or("User declined the tool call.");if(o?.aborted)return or("Aborted by cancel()");let p=new AbortController,f=!1,m=setTimeout(()=>{f=!0,p.abort()},this.#t),g=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",g,{once:!0}));try{let h=await r.executeTool(l,vP(n),{signal:p.signal});return bP(h)}catch(h){if(f)return or(`WebMCP tool '${s}' timed out after ${this.#t}ms`);if(o?.aborted)return or("Aborted by cancel()");let b=h instanceof Error?h.message:String(h);return or(b)}finally{clearTimeout(m),o&&o.removeEventListener("abort",g)}}#s(){return this.config.enabled!==!0?Promise.resolve():(this.#o||(this.#o=this.#g()),this.#o)}async#g(){try{if(this.#c()){this.#n=!0;return}let t=await this.#r.loadPolyfill();"initializeWebMCPPolyfill"in t?t.initializeWebMCPPolyfill():t.installWebMCP(),this.#n=!0}catch(t){yp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#n=!1}}#c(){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.#a||(this.#a=!0,yp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async#f(t){let n=this.#e??CP;try{return await n(t)}catch(o){return yp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#p(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>gP(t,o))}},gP=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},bp={type:"object",properties:{}},hP=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},yP=e=>{if(e===void 0||e==="")return{...bp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...bp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...bp}}catch{return{...bp}}},bP=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:xP(t)}]}},vP=e=>{let t;try{t=JSON.stringify(e)??"{}"}catch{t="{}"}let n=JSON.parse(t);if(n===null||typeof n!="object")throw new TypeError("WebMCP tool arguments must be an object or array.");return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},or=e=>({isError:!0,content:[{type:"text",text:e}]}),CP=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=wP(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
8
8
 
9
9
  Arguments:
10
10
  ${t}`:"")+(e.description?`
11
11
 
12
- ${e.description}`:"");return window.confirm(n)},vP=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)}},CP=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},wP=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}}});var Rw={};En(Rw,{WebMcpBridge:()=>vp});var Ww=ie(()=>{"use strict";Hw()});var Fw,Nw=ie(()=>{Fw="4.28.0"});var br,wp=ie(()=>{"use strict";Nw();br=Fw});var Yw={};En(Yw,{deleteAllConversations:()=>OP,deleteConversation:()=>_P,finalizeDisplayProjections:()=>DP,getConversation:()=>BP,historyErrorFor:()=>Gw,listConversations:()=>WP,readErrorCode:()=>mg,recoverFromUnauthorized:()=>Kw,resetVisitor:()=>NP});function LP(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function PP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function IP(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&e.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function HP(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",Uw);return r}async function mg(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Kw(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",zw);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",qw);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",jw);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function Gw(e,t,n){let o=await mg(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",Uw);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",zw)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",qw):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",jw):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function RP(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new e.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new e.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function ka(e,t,n){gg(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;PP(e,n.scope)==="verified-user"&&(s=await IP(e,r,o),s&&(r=await HP(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,d=await e.readVisitorToken();if(!d&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(LP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":br,...d?{"X-Visitor-Token":d}:{},...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 Kw(e,await mg(e,p),s,o);continue}if(!p.ok)throw await Gw(e,p,o);let f=p.headers.get("X-History-Identity-Status"),m=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return RP(e,f,s!==null,o),m}}function gg(e){if(!e.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!e.isHistoryCapable())throw new e.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function WP(e,t){let n=await ka(e,"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($w),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function BP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:$w(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 function DP(e,t,n){gg(e);let o=0;for(let c of n){let d=c.displayContent.length;if(d>Vw)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${Vw} character limit`);o+=d}if(o>fg)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${fg} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ka(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=fg,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function _P(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function OP(e,t){let n=await ka(e,"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 function NP(e){gg(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ka(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Vw,fg,$w,Uw,zw,qw,jw,Xw=ie(()=>{"use strict";wp();Vw=32768,fg=49152,$w=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:""}},Uw="The identity proof was not admitted; account history is unavailable",zw="The identity proof was rejected",qw="The request carried no visitor credential",jw="The stored visitor belongs to a different signed-in user"});function Qw(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function xp(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function vr(e){return{type:"text",text:e}}function Jw(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}function $P(e){return Zw.includes(e)||e.startsWith("image/")}function Sp(e){return $P(e.type)}function ex(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function tx(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Sp(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 nx(e,t=Qr,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 ox(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 La,Zw,VP,Qr,Rs=ie(()=>{"use strict";La="[Image]";Zw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],VP=["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"],Qr=[...Zw,...VP]});function rx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ap(e){return typeof e=="string"?e:void 0}function jP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?vr(t.text):null;case"image":return typeof t.image=="string"?Jw(t.image,{mimeType:Ap(t.mimeType),alt:Ap(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?ex(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Ap(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Ap(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function KP(e,t){let n=rx(t),o=e.map(i=>rx(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,d=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,f=p!==null&&n!==null?Math.min(p,n):p??n;for(let m=0;m<c;m+=1)r[s+m]=f!==null?f-(c-m):d!==null?d+m+1:qP+m;s=l+1}return r.map(i=>new Date(i).toISOString())}function sx(e,t){let n=KP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!zP.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(jP).filter(p=>p!==null),d=Qw(c);o.push({id:r.id,role:i,content:d||(xp(c)?La:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Vl(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 $l(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(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var zP,qP,Mp=ie(()=>{"use strict";Rs();zP=["user","assistant","system"],qP=0});function Tp(e){return e instanceof Li}var Li,zl=ie(()=>{"use strict";Li=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var cx,dx=ie(()=>{"use strict";gp();cx=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(p,f,m)=>{let g=f.trim();if(!g||!o.current)return;let h=p.getAttribute("data-tool-call-id")??"",b=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:h,answer:g,answers:m.structured,values:m.values??(m.source==="multi"?g.split(", "):[g]),isFreeText:b,source:m.source},bubbles:!0,composed:!0})),Ei(n,h);let C=o.current.getMessages().find(A=>A.toolCall?.id===h);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,m.structured??g):o.current.sendMessage(g)},s=p=>{let f=o.current;if(!f)return;let m=p.getAttribute("data-tool-call-id")??"",g=f.getMessages().find(h=>h.toolCall?.id===m);g&&f.persistAskUserQuestionProgress(g,{answers:fp(p,g),currentIndex:Fo(p)})},i=p=>Object.entries(p).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),l=p=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=Fo(p),m=Ma(p);if(f>=m-1)return;let g=o.current?.getMessages().find(h=>h.toolCall?.id===p.getAttribute("data-tool-call-id"));g&&(mp(p,g,e.config(),f+1),s(p))};return{click:p=>{let m=p.target.closest("[data-ask-user-action]");if(!m)return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;let h=m.getAttribute("data-ask-user-action");if(p.preventDefault(),p.stopPropagation(),h==="dismiss"){let b=g.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b);let C=o.current?.getMessages().find(A=>A.toolCall?.id===b);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(h==="pick"){let b=m.getAttribute("data-option-label");if(!b)return;let C=g.getAttribute("data-multi-select")==="true",A=Ps(g);if(A&&C){let S=Ti(g)[Fo(g)],E=new Set(Array.isArray(S)?S:[]);E.has(b)?E.delete(b):E.add(b),Is(g,Array.from(E)),s(g);return}if(A){Is(g,b),s(g),l(g);return}if(C){let S=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",S?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!S);let E=g.querySelector('[data-ask-user-action="submit-multi"]');E&&(E.disabled=dg(g).length===0);return}r(g,b,{source:"pick",values:[b]});return}if(h==="submit-multi"){let b=dg(g);if(b.length===0)return;r(g,b.join(", "),{source:"multi",values:b});return}if(h==="open-free-text"){let b=g.querySelector('[data-ask-free-text-row="true"]');b&&(b.classList.remove("persona-hidden"),b.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(h==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(h==="submit-free-text"){let C=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(Ps(g)){Is(g,C.trim()),s(g),l(g);return}r(g,C,{source:"free-text"});return}if(h==="next"||h==="back"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!C)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(S){let D=Ti(g)[Fo(g)];(typeof D!="string"||D!==S)&&Is(g,S)}let E=h==="next"?1:-1,k=Fo(g)+E;mp(g,C,e.config(),k),s(g);return}if(h==="submit-all"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!C)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";S&&Is(g,S);let E=fp(g,C);o.current.persistAskUserQuestionProgress(C,{answers:E,currentIndex:Fo(g)});let k=i(E);r(g,k||"(submitted)",{source:"submit-all",structured:E});return}if(h==="skip"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(z=>z.toolCall?.id===b);if(!C)return;let A=Ps(g),S=Fo(g),E=Ma(g),k=S>=E-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}Is(g,"");let D=g.querySelector('[data-ask-free-text-input="true"]');if(D&&(D.value=""),k){let z=fp(g,C),Y=i(z);r(g,Y||"(skipped)",{source:"submit-all",structured:z});return}mp(g,C,e.config(),S+1),s(g);return}},keydown:p=>{if(p.key!=="Enter")return;let m=p.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;p.preventDefault();let h=m.value;if(h.trim()){if(Ps(g)){Is(g,h.trim()),s(g),l(g);return}r(g,h,{source:"free-text"})}}}}});function QP(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
13
- `:o===""||px.test(o)}function JP(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return QP(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
14
- `||i==="\uFFFC"||!r&&px.test(i))return null;s--}return null}function ql(e,t,n){for(let o of n){let r=JP(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function ux(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function fx(e,t,n){return{value:e.slice(0,t.triggerIndex)+e.slice(n),caret:t.triggerIndex}}var px,Ep=ie(()=>{"use strict";px=/\s/});function kp(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]}var bg=ie(()=>{"use strict"});function yx(e){e.delayMs!==void 0&&(mx=Pp(e.delayMs)),e.skipDelayMs!==void 0&&(gx=Pp(e.skipDelayMs))}function bx(e){Lp.get(e)?.hide()}function $n(e){Lp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=ZP,viewportPadding:l=eI}=e,c=()=>t.ownerDocument,d=()=>c().defaultView??window,p=null,f=null,m=null,g=null,h,b=!1,C=!1,A=!1,S=()=>(typeof o=="function"?o():o).trim(),E=()=>(typeof r=="function"?r():r??"").trim(),k=()=>Pp(e.delayMs??mx),D=()=>Pp(e.skipDelayMs??gx),z=()=>{h!==void 0&&(d().clearTimeout(h),h=void 0)},Y=()=>{z();let K=p!==null;g?.(),g=null,p?.remove(),p=null,f=null,m=null,K&&nI(D())},T=()=>{if(!p)return;let K=c(),X=d(),oe=t.getBoundingClientRect(),de=p.getBoundingClientRect(),xe=K.documentElement.clientWidth||X.innerWidth,Te=K.documentElement.clientHeight||X.innerHeight,re=xe-l-de.width,N=oe.left+oe.width/2-de.width/2,ke=Cg(N,l,re),ve=oe.top-l,tt=Te-l-oe.bottom,xt=de.height+i,ht=ve>=xt||ve>=tt?"top":"bottom",lt=ht==="top"?oe.top-i-de.height:oe.bottom+i,Ye=Te-l-de.height,dt=Cg(lt,l,Ye),Pe=oe.left+oe.width/2,Se=Math.max(vg,de.width-vg),U=Cg(Pe-ke,vg,Se);p.dataset.placement=ht,p.style.left=`${ke}px`,p.style.top=`${dt}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${U}px`)},W=()=>{if(A||!s||p||!t.isConnected||oI(t))return;let K=S(),X=rI(t);if(!K||!X)return;let oe=c(),de=d();p=oe.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ta);let xe=de.getComputedStyle?.(t);if(xe){for(let xt of sI){let ht=xe.getPropertyValue(xt).trim();ht&&p.style.setProperty(xt,ht)}xe.fontFamily&&(p.style.fontFamily=xe.fontFamily)}f=oe.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=K,p.appendChild(f);let Te=E();Te&&(m=oe.createElement("span"),m.className="persona-control-tooltip__hint",m.textContent=Te,p.appendChild(m));let re=oe.createElement("span");re.className="persona-control-tooltip__arrow",p.appendChild(re),X.appendChild(p),T(),p.dataset.state="open";let N=()=>{if(!t.isConnected){Y();return}f&&(f.textContent=S()),m&&(m.textContent=E()),T()};de.addEventListener("scroll",N,!0),de.addEventListener("resize",N);let ke=t.getRootNode(),ve=vx(ke)?ke:oe.documentElement,tt=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||Y()});tt?.observe(ve,{childList:!0,subtree:!0}),g=()=>{de.removeEventListener("scroll",N,!0),de.removeEventListener("resize",N),tt?.disconnect()}},L=K=>{if(!(A||p)){if(z(),K||k()<=0||tI()){W();return}h=d().setTimeout(()=>{h=void 0,W()},k())}},w=()=>{b||C?L(C):Y()},x=()=>{let K=d();(!K.matchMedia||!K.matchMedia("(hover: none)").matches)&&(b=!0,w())},P=()=>{b=!1,w()},I=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}w()},J=()=>{C=!1,w()},_=()=>{b=!1,C=!1,Y()},j=K=>{K.key==="Escape"&&_()};n.addEventListener("mouseenter",x),n.addEventListener("mouseleave",P),t.addEventListener("focus",I),t.addEventListener("blur",J),t.addEventListener("keydown",j),t.addEventListener("click",_);let te={get isOpen(){return p!==null},show:W,hide:Y,reposition:T,destroy:()=>{A||(A=!0,Y(),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",P),t.removeEventListener("focus",I),t.removeEventListener("blur",J),t.removeEventListener("keydown",j),t.removeEventListener("click",_),Lp.delete(t))}};return Lp.set(t,te),te}var ZP,eI,vg,mx,gx,hx,Pp,tI,nI,Lp,wg,oI,vx,rI,Cg,sI,Pa=ie(()=>{"use strict";nr();zd();ZP=8,eI=8,vg=10,mx=200,gx=300,hx=0,Pp=e=>Math.max(0,e);tI=()=>Date.now()<hx,nI=e=>{hx=e>0?Date.now()+e:0},Lp=new WeakMap,wg="data-persona-tooltip-suppressed",oI=e=>typeof e.closest=="function"&&e.closest(`[${wg}]`)!==null;vx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,rI=e=>{let t=e.getRootNode?.();return vx(t)?t:e.ownerDocument.body},Cg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),sI=[...["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 xg(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 Ip(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Cx(e,t){e.style.maxHeight=`${t*xg(e)}px`,e.style.overflowY="auto"}function jl(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 wx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function xx(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||!wx(t)}function iI(e){return(e.submitKey??"enter")!=="enter"||wx(e)?"enter":"send"}function Hp(e,t){e.setAttribute("enterkeyhint",iI(t))}function Rp(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 Sg(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 Wp=ie(()=>{"use strict"});var Mo,rr,Mg,Co,Bp,Dp,lI,Tg,_p,Ia,Op,Np,Fp,Ws=ie(()=>{"use strict";Xm();Ge();ln();er();Rs();Pa();Wp();Mo="persona-composer-control",rr="persona-composer-control--glyph",Mg=40,Co=24,Bp=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},Dp=(e,t)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??zm,n.dir="auto",Hp(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(n)}),Rp(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=Ip(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 d=parseFloat(l);if(Number.isFinite(d)&&d>0)return d}let c=o*xg(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{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:i}},lI="[data-persona-glyph-stack]",Tg=(e,t,n="send")=>{let o=F("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},_p=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,f=t.size,m=parseFloat(f??"")||Mg,g=t.backgroundColor,h=t.textColor,b=v("div","persona-send-button-wrapper"),C=F("button",{className:Jt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Mo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!h&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?h||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":h||void 0,backgroundColor:n&&g||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}}),A=null,S=null,E=null;if(n){let z=parseFloat(t.iconSize??"")||Math.round(m*.5),Y=t.iconStrokeWidth??2,T=h?.trim()||"currentColor";if(r&&(A=We(r,z,T,Y)),S=We(s,z,T,Y),!t.iconSize)for(let W of[A,S])W&&(W.style.width=`var(--persona-components-composer-sendIconSize, ${z}px)`,W.style.height=`var(--persona-components-composer-sendIconSize, ${z}px)`);A&&S?(E=Tg(A,S),C.appendChild(E)):A?C.appendChild(A):(C.textContent=o,S=null)}else C.textContent=c;C.setAttribute("aria-label",i),b.appendChild(C),$n({anchor:C,trigger:b,text:()=>C.getAttribute("aria-label")??"",enabled:p});let k="send";return{button:C,wrapper:b,setMode:z=>{if(z===k)return;k=z;let Y=z==="stop"?l:i;C.setAttribute("aria-label",Y),C.setAttribute("data-persona-send-mode",z),n?(C.querySelector(lI)??E)?.setAttribute("data-mode",z):C.textContent=z==="stop"?d:c},glyphStack:E}},Ia=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",c=t.iconSize,d=parseFloat(c??"")||Co,p=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,m=v("div","persona-send-button-wrapper"),g=F("button",{className:Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Mo,!c&&rr),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"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}}),b=We(l,d,f||"currentColor",1.5);b?g.appendChild(b):g.textContent="\u{1F3A4}",m.appendChild(g);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return $n({anchor:g,trigger:m,text:()=>g.getAttribute("aria-label")??C,enabled:A}),{button:g,wrapper:m}},Op=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=v("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=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Qr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),i=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Mo} ${rr}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=We(r,Co,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",d=>{d.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return $n({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},Np=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),xi(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=v("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},Fp=()=>F("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function Vp(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),i=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Mo} ${rr}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=We(o,Co,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),$n({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Eg=ie(()=>{"use strict";Ge();ln();Pa();Ws()});var Sx,kg,$p,Up=ie(()=>{"use strict";Sx=null,kg=e=>{Sx=e},$p=(e,t,n,o)=>Sx?.(e,t,n,o)??null});function Mx(e){let{ref:t,config:n,onRemove:o}=e;if(n.renderMentionChip){let g="resolving",h,b=n.renderMentionChip({ref:t,status:g,payload:h,remove:o});return{get el(){return b},setStatus:(A,S)=>{if(A===g&&S===h)return;g=A,h=S;let E=n.renderMentionChip({ref:t,status:g,payload:h,remove:o});b.replaceWith(E),b=E}}}let r=t.iconName??n.chipIconName??"at-sign",s=F("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:t.label}}),i=v("span","persona-mention-chip-icon"),l=g=>{i.replaceChildren();let h=$p(g,13,"currentColor",2);h&&i.appendChild(h)};l(r);let c=v("span","persona-mention-chip-spinner"),d=F("span",{className:"persona-mention-chip-label",text:t.label}),p=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label} context`}}),f=Je(Ax.X,11,"currentColor",2.5);return f?p.appendChild(f):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(c),s.appendChild(d),s.appendChild(p),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="resolving"?(c.parentNode!==s&&s.insertBefore(c,d),i.parentNode===s&&i.remove(),s.setAttribute("title",t.label)):(c.parentNode===s&&c.remove(),i.parentNode!==s&&s.insertBefore(i,d),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${t.label} to context`)):(l(r),s.setAttribute("title",t.label)))}}}var Ax,Tx=ie(()=>{"use strict";Ge();Ax=require("lucide");ao();Up()});function Ha(e){e.style.display=e.childElementCount>0?"flex":"none"}function Pg(e){let t=e.querySelector(Lg);if(t)return t;let n=F("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 Lg,zp=ie(()=>{"use strict";Ge();Lg="[data-persona-composer-chip-row]"});function cI(e){let t=0;for(let n of e.split(`
15
- `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function Kl(e,t){let n="`".repeat(Math.max(3,cI(t)+1));return`${n}${e}
12
+ ${e.description}`:"");return window.confirm(n)},wP=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)}},Hw=e=>(e.window===void 0||typeof window<"u"&&e.window===window)&&(e.origin===void 0||typeof location<"u"&&e.origin===location.origin),xP=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}}});var Ww={};En(Ww,{WebMcpBridge:()=>vp});var Bw=ie(()=>{"use strict";Rw()});var Vw,Fw=ie(()=>{Vw="4.28.1"});var br,wp=ie(()=>{"use strict";Fw();br=Vw});var Xw={};En(Xw,{deleteAllConversations:()=>NP,deleteConversation:()=>OP,finalizeDisplayProjections:()=>_P,getConversation:()=>DP,historyErrorFor:()=>Yw,listConversations:()=>BP,readErrorCode:()=>mg,recoverFromUnauthorized:()=>Gw,resetVisitor:()=>FP});function PP(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function IP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function HP(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&e.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function RP(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",zw);return r}async function mg(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Gw(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qw);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",jw);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",Kw);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function Yw(e,t,n){let o=await mg(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",zw);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qw)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",jw):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Kw):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function WP(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new e.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new e.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function ka(e,t,n){gg(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;IP(e,n.scope)==="verified-user"&&(s=await HP(e,r,o),s&&(r=await RP(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,d=await e.readVisitorToken();if(!d&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(PP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":br,...d?{"X-Visitor-Token":d}:{},...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 Gw(e,await mg(e,p),s,o);continue}if(!p.ok)throw await Yw(e,p,o);let f=p.headers.get("X-History-Identity-Status"),m=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return WP(e,f,s!==null,o),m}}function gg(e){if(!e.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!e.isHistoryCapable())throw new e.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function BP(e,t){let n=await ka(e,"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(Uw),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function DP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Uw(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 function _P(e,t,n){gg(e);let o=0;for(let c of n){let d=c.displayContent.length;if(d>$w)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${$w} character limit`);o+=d}if(o>fg)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${fg} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ka(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=fg,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function OP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function NP(e,t){let n=await ka(e,"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 function FP(e){gg(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ka(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var $w,fg,Uw,zw,qw,jw,Kw,Qw=ie(()=>{"use strict";wp();$w=32768,fg=49152,Uw=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:""}},zw="The identity proof was not admitted; account history is unavailable",qw="The identity proof was rejected",jw="The request carried no visitor credential",Kw="The stored visitor belongs to a different signed-in user"});function Jw(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function xp(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function vr(e){return{type:"text",text:e}}function Zw(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}function UP(e){return ex.includes(e)||e.startsWith("image/")}function Sp(e){return UP(e.type)}function tx(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function nx(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Sp(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 ox(e,t=Qr,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 zP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function rx(e,t){let n=zP(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 La,ex,$P,Qr,Rs=ie(()=>{"use strict";La="[Image]";ex=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$P=["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"],Qr=[...ex,...$P]});function sx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ap(e){return typeof e=="string"?e:void 0}function KP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?vr(t.text):null;case"image":return typeof t.image=="string"?Zw(t.image,{mimeType:Ap(t.mimeType),alt:Ap(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?tx(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Ap(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Ap(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function GP(e,t){let n=sx(t),o=e.map(i=>sx(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,d=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,f=p!==null&&n!==null?Math.min(p,n):p??n;for(let m=0;m<c;m+=1)r[s+m]=f!==null?f-(c-m):d!==null?d+m+1:jP+m;s=l+1}return r.map(i=>new Date(i).toISOString())}function ix(e,t){let n=GP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!qP.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(KP).filter(p=>p!==null),d=Jw(c);o.push({id:r.id,role:i,content:d||(xp(c)?La:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Vl(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 $l(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(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var qP,jP,Mp=ie(()=>{"use strict";Rs();qP=["user","assistant","system"],jP=0});function Tp(e){return e instanceof Li}var Li,zl=ie(()=>{"use strict";Li=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var dx,px=ie(()=>{"use strict";gp();dx=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(p,f,m)=>{let g=f.trim();if(!g||!o.current)return;let h=p.getAttribute("data-tool-call-id")??"",b=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:h,answer:g,answers:m.structured,values:m.values??(m.source==="multi"?g.split(", "):[g]),isFreeText:b,source:m.source},bubbles:!0,composed:!0})),Ei(n,h);let C=o.current.getMessages().find(A=>A.toolCall?.id===h);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,m.structured??g):o.current.sendMessage(g)},s=p=>{let f=o.current;if(!f)return;let m=p.getAttribute("data-tool-call-id")??"",g=f.getMessages().find(h=>h.toolCall?.id===m);g&&f.persistAskUserQuestionProgress(g,{answers:fp(p,g),currentIndex:Fo(p)})},i=p=>Object.entries(p).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),l=p=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=Fo(p),m=Ma(p);if(f>=m-1)return;let g=o.current?.getMessages().find(h=>h.toolCall?.id===p.getAttribute("data-tool-call-id"));g&&(mp(p,g,e.config(),f+1),s(p))};return{click:p=>{let m=p.target.closest("[data-ask-user-action]");if(!m)return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;let h=m.getAttribute("data-ask-user-action");if(p.preventDefault(),p.stopPropagation(),h==="dismiss"){let b=g.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b);let C=o.current?.getMessages().find(A=>A.toolCall?.id===b);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(h==="pick"){let b=m.getAttribute("data-option-label");if(!b)return;let C=g.getAttribute("data-multi-select")==="true",A=Ps(g);if(A&&C){let S=Ti(g)[Fo(g)],E=new Set(Array.isArray(S)?S:[]);E.has(b)?E.delete(b):E.add(b),Is(g,Array.from(E)),s(g);return}if(A){Is(g,b),s(g),l(g);return}if(C){let S=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",S?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!S);let E=g.querySelector('[data-ask-user-action="submit-multi"]');E&&(E.disabled=dg(g).length===0);return}r(g,b,{source:"pick",values:[b]});return}if(h==="submit-multi"){let b=dg(g);if(b.length===0)return;r(g,b.join(", "),{source:"multi",values:b});return}if(h==="open-free-text"){let b=g.querySelector('[data-ask-free-text-row="true"]');b&&(b.classList.remove("persona-hidden"),b.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(h==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(h==="submit-free-text"){let C=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(Ps(g)){Is(g,C.trim()),s(g),l(g);return}r(g,C,{source:"free-text"});return}if(h==="next"||h==="back"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!C)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(S){let D=Ti(g)[Fo(g)];(typeof D!="string"||D!==S)&&Is(g,S)}let E=h==="next"?1:-1,k=Fo(g)+E;mp(g,C,e.config(),k),s(g);return}if(h==="submit-all"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!C)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";S&&Is(g,S);let E=fp(g,C);o.current.persistAskUserQuestionProgress(C,{answers:E,currentIndex:Fo(g)});let k=i(E);r(g,k||"(submitted)",{source:"submit-all",structured:E});return}if(h==="skip"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(z=>z.toolCall?.id===b);if(!C)return;let A=Ps(g),S=Fo(g),E=Ma(g),k=S>=E-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}Is(g,"");let D=g.querySelector('[data-ask-free-text-input="true"]');if(D&&(D.value=""),k){let z=fp(g,C),Y=i(z);r(g,Y||"(skipped)",{source:"submit-all",structured:z});return}mp(g,C,e.config(),S+1),s(g);return}},keydown:p=>{if(p.key!=="Enter")return;let m=p.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;p.preventDefault();let h=m.value;if(h.trim()){if(Ps(g)){Is(g,h.trim()),s(g),l(g);return}r(g,h,{source:"free-text"})}}}}});function JP(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
13
+ `:o===""||ux.test(o)}function ZP(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return JP(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
14
+ `||i==="\uFFFC"||!r&&ux.test(i))return null;s--}return null}function ql(e,t,n){for(let o of n){let r=ZP(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function fx(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function mx(e,t,n){return{value:e.slice(0,t.triggerIndex)+e.slice(n),caret:t.triggerIndex}}var ux,Ep=ie(()=>{"use strict";ux=/\s/});function kp(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]}var bg=ie(()=>{"use strict"});function bx(e){e.delayMs!==void 0&&(gx=Pp(e.delayMs)),e.skipDelayMs!==void 0&&(hx=Pp(e.skipDelayMs))}function vx(e){Lp.get(e)?.hide()}function $n(e){Lp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=eI,viewportPadding:l=tI}=e,c=()=>t.ownerDocument,d=()=>c().defaultView??window,p=null,f=null,m=null,g=null,h,b=!1,C=!1,A=!1,S=()=>(typeof o=="function"?o():o).trim(),E=()=>(typeof r=="function"?r():r??"").trim(),k=()=>Pp(e.delayMs??gx),D=()=>Pp(e.skipDelayMs??hx),z=()=>{h!==void 0&&(d().clearTimeout(h),h=void 0)},Y=()=>{z();let K=p!==null;g?.(),g=null,p?.remove(),p=null,f=null,m=null,K&&oI(D())},T=()=>{if(!p)return;let K=c(),X=d(),oe=t.getBoundingClientRect(),de=p.getBoundingClientRect(),xe=K.documentElement.clientWidth||X.innerWidth,Te=K.documentElement.clientHeight||X.innerHeight,re=xe-l-de.width,N=oe.left+oe.width/2-de.width/2,ke=Cg(N,l,re),ve=oe.top-l,tt=Te-l-oe.bottom,xt=de.height+i,ht=ve>=xt||ve>=tt?"top":"bottom",lt=ht==="top"?oe.top-i-de.height:oe.bottom+i,Ye=Te-l-de.height,dt=Cg(lt,l,Ye),Pe=oe.left+oe.width/2,Se=Math.max(vg,de.width-vg),U=Cg(Pe-ke,vg,Se);p.dataset.placement=ht,p.style.left=`${ke}px`,p.style.top=`${dt}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${U}px`)},W=()=>{if(A||!s||p||!t.isConnected||rI(t))return;let K=S(),X=sI(t);if(!K||!X)return;let oe=c(),de=d();p=oe.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ta);let xe=de.getComputedStyle?.(t);if(xe){for(let xt of iI){let ht=xe.getPropertyValue(xt).trim();ht&&p.style.setProperty(xt,ht)}xe.fontFamily&&(p.style.fontFamily=xe.fontFamily)}f=oe.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=K,p.appendChild(f);let Te=E();Te&&(m=oe.createElement("span"),m.className="persona-control-tooltip__hint",m.textContent=Te,p.appendChild(m));let re=oe.createElement("span");re.className="persona-control-tooltip__arrow",p.appendChild(re),X.appendChild(p),T(),p.dataset.state="open";let N=()=>{if(!t.isConnected){Y();return}f&&(f.textContent=S()),m&&(m.textContent=E()),T()};de.addEventListener("scroll",N,!0),de.addEventListener("resize",N);let ke=t.getRootNode(),ve=Cx(ke)?ke:oe.documentElement,tt=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||Y()});tt?.observe(ve,{childList:!0,subtree:!0}),g=()=>{de.removeEventListener("scroll",N,!0),de.removeEventListener("resize",N),tt?.disconnect()}},L=K=>{if(!(A||p)){if(z(),K||k()<=0||nI()){W();return}h=d().setTimeout(()=>{h=void 0,W()},k())}},w=()=>{b||C?L(C):Y()},x=()=>{let K=d();(!K.matchMedia||!K.matchMedia("(hover: none)").matches)&&(b=!0,w())},P=()=>{b=!1,w()},I=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}w()},J=()=>{C=!1,w()},_=()=>{b=!1,C=!1,Y()},j=K=>{K.key==="Escape"&&_()};n.addEventListener("mouseenter",x),n.addEventListener("mouseleave",P),t.addEventListener("focus",I),t.addEventListener("blur",J),t.addEventListener("keydown",j),t.addEventListener("click",_);let te={get isOpen(){return p!==null},show:W,hide:Y,reposition:T,destroy:()=>{A||(A=!0,Y(),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",P),t.removeEventListener("focus",I),t.removeEventListener("blur",J),t.removeEventListener("keydown",j),t.removeEventListener("click",_),Lp.delete(t))}};return Lp.set(t,te),te}var eI,tI,vg,gx,hx,yx,Pp,nI,oI,Lp,wg,rI,Cx,sI,Cg,iI,Pa=ie(()=>{"use strict";nr();zd();eI=8,tI=8,vg=10,gx=200,hx=300,yx=0,Pp=e=>Math.max(0,e);nI=()=>Date.now()<yx,oI=e=>{yx=e>0?Date.now()+e:0},Lp=new WeakMap,wg="data-persona-tooltip-suppressed",rI=e=>typeof e.closest=="function"&&e.closest(`[${wg}]`)!==null;Cx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,sI=e=>{let t=e.getRootNode?.();return Cx(t)?t:e.ownerDocument.body},Cg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),iI=[...["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 xg(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 Ip(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function wx(e,t){e.style.maxHeight=`${t*xg(e)}px`,e.style.overflowY="auto"}function jl(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 xx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Sx(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||!xx(t)}function aI(e){return(e.submitKey??"enter")!=="enter"||xx(e)?"enter":"send"}function Hp(e,t){e.setAttribute("enterkeyhint",aI(t))}function Rp(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 Sg(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 Wp=ie(()=>{"use strict"});var Mo,rr,Mg,Co,Bp,Dp,cI,Tg,_p,Ia,Op,Np,Fp,Ws=ie(()=>{"use strict";Xm();Ge();ln();er();Rs();Pa();Wp();Mo="persona-composer-control",rr="persona-composer-control--glyph",Mg=40,Co=24,Bp=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},Dp=(e,t)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??zm,n.dir="auto",Hp(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(n)}),Rp(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=Ip(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 d=parseFloat(l);if(Number.isFinite(d)&&d>0)return d}let c=o*xg(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{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:i}},cI="[data-persona-glyph-stack]",Tg=(e,t,n="send")=>{let o=F("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},_p=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,f=t.size,m=parseFloat(f??"")||Mg,g=t.backgroundColor,h=t.textColor,b=v("div","persona-send-button-wrapper"),C=F("button",{className:Jt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Mo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!h&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?h||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":h||void 0,backgroundColor:n&&g||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}}),A=null,S=null,E=null;if(n){let z=parseFloat(t.iconSize??"")||Math.round(m*.5),Y=t.iconStrokeWidth??2,T=h?.trim()||"currentColor";if(r&&(A=We(r,z,T,Y)),S=We(s,z,T,Y),!t.iconSize)for(let W of[A,S])W&&(W.style.width=`var(--persona-components-composer-sendIconSize, ${z}px)`,W.style.height=`var(--persona-components-composer-sendIconSize, ${z}px)`);A&&S?(E=Tg(A,S),C.appendChild(E)):A?C.appendChild(A):(C.textContent=o,S=null)}else C.textContent=c;C.setAttribute("aria-label",i),b.appendChild(C),$n({anchor:C,trigger:b,text:()=>C.getAttribute("aria-label")??"",enabled:p});let k="send";return{button:C,wrapper:b,setMode:z=>{if(z===k)return;k=z;let Y=z==="stop"?l:i;C.setAttribute("aria-label",Y),C.setAttribute("data-persona-send-mode",z),n?(C.querySelector(cI)??E)?.setAttribute("data-mode",z):C.textContent=z==="stop"?d:c},glyphStack:E}},Ia=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",c=t.iconSize,d=parseFloat(c??"")||Co,p=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,m=v("div","persona-send-button-wrapper"),g=F("button",{className:Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Mo,!c&&rr),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"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}}),b=We(l,d,f||"currentColor",1.5);b?g.appendChild(b):g.textContent="\u{1F3A4}",m.appendChild(g);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return $n({anchor:g,trigger:m,text:()=>g.getAttribute("aria-label")??C,enabled:A}),{button:g,wrapper:m}},Op=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=v("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=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Qr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),i=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Mo} ${rr}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=We(r,Co,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",d=>{d.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return $n({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},Np=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),xi(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=v("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},Fp=()=>F("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function Vp(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),i=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Mo} ${rr}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=We(o,Co,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),$n({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Eg=ie(()=>{"use strict";Ge();ln();Pa();Ws()});var Ax,kg,$p,Up=ie(()=>{"use strict";Ax=null,kg=e=>{Ax=e},$p=(e,t,n,o)=>Ax?.(e,t,n,o)??null});function Tx(e){let{ref:t,config:n,onRemove:o}=e;if(n.renderMentionChip){let g="resolving",h,b=n.renderMentionChip({ref:t,status:g,payload:h,remove:o});return{get el(){return b},setStatus:(A,S)=>{if(A===g&&S===h)return;g=A,h=S;let E=n.renderMentionChip({ref:t,status:g,payload:h,remove:o});b.replaceWith(E),b=E}}}let r=t.iconName??n.chipIconName??"at-sign",s=F("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:t.label}}),i=v("span","persona-mention-chip-icon"),l=g=>{i.replaceChildren();let h=$p(g,13,"currentColor",2);h&&i.appendChild(h)};l(r);let c=v("span","persona-mention-chip-spinner"),d=F("span",{className:"persona-mention-chip-label",text:t.label}),p=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label} context`}}),f=Je(Mx.X,11,"currentColor",2.5);return f?p.appendChild(f):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(c),s.appendChild(d),s.appendChild(p),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="resolving"?(c.parentNode!==s&&s.insertBefore(c,d),i.parentNode===s&&i.remove(),s.setAttribute("title",t.label)):(c.parentNode===s&&c.remove(),i.parentNode!==s&&s.insertBefore(i,d),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${t.label} to context`)):(l(r),s.setAttribute("title",t.label)))}}}var Mx,Ex=ie(()=>{"use strict";Ge();Mx=require("lucide");ao();Up()});function Ha(e){e.style.display=e.childElementCount>0?"flex":"none"}function Pg(e){let t=e.querySelector(Lg);if(t)return t;let n=F("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 Lg,zp=ie(()=>{"use strict";Ge();Lg="[data-persona-composer-chip-row]"});function dI(e){let t=0;for(let n of e.split(`
15
+ `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function Kl(e,t){let n="`".repeat(Math.max(3,dI(t)+1));return`${n}${e}
16
16
  ${t}
17
- ${n}`}function dI(e,t,n){return t.includes("</document_content>")?Kl(e,t):`<document index="${n+1}">
17
+ ${n}`}function pI(e,t,n){return t.includes("</document_content>")?Kl(e,t):`<document index="${n+1}">
18
18
  <source>${e}</source>
19
19
  <document_content>
20
20
  ${t}
21
21
  </document_content>
22
- </document>`}function Ex(e,t,n="fenced"){if(typeof n=="function")try{return n(e,t)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Kl(e.label,e.text)}return n==="document"?dI(e.label,e.text,t):Kl(e.label,e.text)}var Ig=ie(()=>{"use strict"});function qp(e,t){return{sourceId:e.id,itemId:t.id,label:t.label,iconName:t.iconName,color:t.color}}var kx,jp,Hg=ie(()=>{"use strict";Tx();zp();Ig();kx=(e,t)=>`${e}\0${t}`,jp=class{constructor(t){this.mentions=[];this.#e=t,this.#s()}#e;get#t(){return this.#e.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(t,n,o=""){let r=kx(t.id,n.id);if(this.mentions.some(l=>l.key===r))return this.#n(t,n,"duplicate");if(this.atLimit())return this.#n(t,n,"limit");let s=qp(t,n),i={key:r,source:t,item:n,ref:s,status:"resolving",args:o};return i.chip=Mx({ref:s,config:this.#e.mentionConfig,onRemove:()=>this.remove(r)}),i.chip.el.setAttribute("data-persona-chip-enter",""),i.chip.el.addEventListener("animationend",()=>i.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.#e.contextRow.appendChild(i.chip.el),this.#o(i),this.#s(),!0}atLimit(){return this.mentions.length>=this.#t}admit(t,n){return this.atLimit()?this.#n(t,n,"limit"):!0}track(t,n,o,r="",s){let i={key:t,source:n,item:o,ref:qp(n,o),status:"resolving",args:r,reportStatus:s};this.#o(i)}#n(t,n,o){return this.#e.mentionConfig.onMentionRejected?.(n,o),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:o}),!1}#o(t){this.mentions.push(t),t.source.resolveOn==="submit"?(t.status="ready",t.chip?.setStatus("ready"),t.reportStatus?.("resolved")):t.resolvePromise=this.#r(t),this.#e.announce(`Added ${t.ref.label} to context`)}#a(t,n,o=this.#e.getComposerText()){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:o,args:n,signal:t}}async#r(t){let n=new AbortController;t.abort=n;try{let o=await t.source.resolve(t.item,this.#a(n.signal,t.args));if(n.signal.aborted)return;t.payload=o,t.status="ready",t.chip?.setStatus("ready",o),t.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;t.status="error",t.chip?.setStatus("error"),t.reportStatus?.("error"),(this.#e.announceError??this.#e.announce)(`Couldn't attach ${t.ref.label} to context`),this.#e.mentionConfig.onMentionResolveError?.(t.item,o),this.#e.emit?.("resolve-error",{sourceId:t.source.id,itemId:t.item.id})}}remove(t){let n=this.mentions.findIndex(r=>r.key===t);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.#s(),this.#e.announce(`Removed ${o.ref.label} from context`)}getRefs(){return this.mentions.map(t=>t.ref)}removeLast(){let t=this.mentions[this.mentions.length-1];return t?(this.remove(t.key),!0):!1}clear(){for(let t of this.mentions)t.abort?.abort(),t.chip?.el.remove();this.mentions.length=0,this.#s()}collectForSubmit(){let t=[...this.mentions],n=t.map(s=>s.ref),o=this.#e.getComposerText();for(let s of t)s.chip?.el.remove();return this.mentions.length=0,this.#s(),{refs:n,finalize:async()=>{let s=await Promise.all(t.map(async p=>{try{return p.source.resolveOn==="submit"?await p.source.resolve(p.item,this.#a(new AbortController().signal,p.args,o)):(p.resolvePromise&&await p.resolvePromise,p.payload??null)}catch(f){try{this.#e.mentionConfig.onMentionResolveError?.(p.item,f)}catch(m){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",m)}return this.#e.emit?.("resolve-error",{sourceId:p.source.id,itemId:p.item.id}),null}})),i=[],l=[],c={},d=new Set;for(let p=0;p<t.length;p++){let f=t[p],m=s[p];if(!m)continue;let g=kx(f.source.id,f.item.id);if(!d.has(g)){if(d.add(g),m.llmAppend&&m.llmAppend.trim())try{i.push(Ex({label:f.ref.label,text:m.llmAppend,ref:f.ref,item:f.item},i.length,this.#e.mentionConfig.llmFormat))}catch(h){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",h)}m.contentParts?.length&&l.push(...m.contentParts),m.context&&((c[f.source.id]??={})[f.item.id]=m.context)}}return{blocks:i,contentParts:l,context:c}}}}#s(){Ha(this.#e.contextRow)}}});function Lx(e){let t=e.getRootNode?.();return t&&Px(t)||t&&Gp(t)?t:e.ownerDocument??document}function Kp(e,t,n){let o=Gp(e)?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(Gp(e)?e:e.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",t),i.textContent=n,o.appendChild(i)}function Yp(e,t,n){if(Gp(e)||Px(e)){Kp(e,t,n);return}let o=e;if(o.isConnected){Kp(Lx(o),t,n);return}let r=o.ownerDocument??document;Kp(r,t,n),queueMicrotask(()=>{let s=Lx(o);s!==r&&Kp(s,t,n)})}function pI(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Bs(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:d,onDismiss:p}=e,f=e.container??pI(t),m=!1,g=null,h=()=>{if(!m)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let S=n.getBoundingClientRect(),E=l?.()??null,k=E!=null?A.top+E:A.top,D=o==="top-start"||o==="top-end"?k-r-S.height:A.bottom+r,Y=o==="bottom-end"||o==="top-end"?A.right-S.width:A.left,T=i?.()??null;if(T!=null){let W=Math.max(A.left,A.right-S.width);Y=Math.min(Math.max(A.left+T,A.left),W)}n.style.top=`${D}px`,n.style.left=`${Y}px`},b=()=>{m&&(m=!1,g&&(g(),g=null),n.remove())},C=()=>{if(m)return;m=!0,c!=null&&(n.style.zIndex=String(c)),f.appendChild(n),h();let A=(t.ownerDocument??document).defaultView??window,S=t.ownerDocument??document,E=()=>{if(!t.isConnected){b(),p?.("anchor-removed");return}h()},k=z=>{let Y=typeof z.composedPath=="function"?z.composedPath():[];Y.includes(n)||Y.includes(t)||(b(),p?.("outside"))},D=A.setTimeout(()=>{S.addEventListener("pointerdown",k,!0)},0);A.addEventListener("scroll",E,!0),A.addEventListener("resize",E),g=()=>{A.clearTimeout(D),S.removeEventListener("pointerdown",k,!0),A.removeEventListener("scroll",E,!0),A.removeEventListener("resize",E)},d?.()};return{get isOpen(){return m},open:C,close:b,toggle:()=>m?b():C(),reposition:h,destroy:b}}function Ix(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Gp,Px,Ra=ie(()=>{"use strict";Gp=e=>e.nodeType===Node.DOCUMENT_NODE,Px=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host!==void 0});var Hx,Rx=ie(()=>{"use strict";Hx=`
22
+ </document>`}function kx(e,t,n="fenced"){if(typeof n=="function")try{return n(e,t)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Kl(e.label,e.text)}return n==="document"?pI(e.label,e.text,t):Kl(e.label,e.text)}var Ig=ie(()=>{"use strict"});function qp(e,t){return{sourceId:e.id,itemId:t.id,label:t.label,iconName:t.iconName,color:t.color}}var Lx,jp,Hg=ie(()=>{"use strict";Ex();zp();Ig();Lx=(e,t)=>`${e}\0${t}`,jp=class{constructor(t){this.mentions=[];this.#e=t,this.#s()}#e;get#t(){return this.#e.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(t,n,o=""){let r=Lx(t.id,n.id);if(this.mentions.some(l=>l.key===r))return this.#n(t,n,"duplicate");if(this.atLimit())return this.#n(t,n,"limit");let s=qp(t,n),i={key:r,source:t,item:n,ref:s,status:"resolving",args:o};return i.chip=Tx({ref:s,config:this.#e.mentionConfig,onRemove:()=>this.remove(r)}),i.chip.el.setAttribute("data-persona-chip-enter",""),i.chip.el.addEventListener("animationend",()=>i.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.#e.contextRow.appendChild(i.chip.el),this.#o(i),this.#s(),!0}atLimit(){return this.mentions.length>=this.#t}admit(t,n){return this.atLimit()?this.#n(t,n,"limit"):!0}track(t,n,o,r="",s){let i={key:t,source:n,item:o,ref:qp(n,o),status:"resolving",args:r,reportStatus:s};this.#o(i)}#n(t,n,o){return this.#e.mentionConfig.onMentionRejected?.(n,o),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:o}),!1}#o(t){this.mentions.push(t),t.source.resolveOn==="submit"?(t.status="ready",t.chip?.setStatus("ready"),t.reportStatus?.("resolved")):t.resolvePromise=this.#r(t),this.#e.announce(`Added ${t.ref.label} to context`)}#a(t,n,o=this.#e.getComposerText()){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:o,args:n,signal:t}}async#r(t){let n=new AbortController;t.abort=n;try{let o=await t.source.resolve(t.item,this.#a(n.signal,t.args));if(n.signal.aborted)return;t.payload=o,t.status="ready",t.chip?.setStatus("ready",o),t.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;t.status="error",t.chip?.setStatus("error"),t.reportStatus?.("error"),(this.#e.announceError??this.#e.announce)(`Couldn't attach ${t.ref.label} to context`),this.#e.mentionConfig.onMentionResolveError?.(t.item,o),this.#e.emit?.("resolve-error",{sourceId:t.source.id,itemId:t.item.id})}}remove(t){let n=this.mentions.findIndex(r=>r.key===t);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.#s(),this.#e.announce(`Removed ${o.ref.label} from context`)}getRefs(){return this.mentions.map(t=>t.ref)}removeLast(){let t=this.mentions[this.mentions.length-1];return t?(this.remove(t.key),!0):!1}clear(){for(let t of this.mentions)t.abort?.abort(),t.chip?.el.remove();this.mentions.length=0,this.#s()}collectForSubmit(){let t=[...this.mentions],n=t.map(s=>s.ref),o=this.#e.getComposerText();for(let s of t)s.chip?.el.remove();return this.mentions.length=0,this.#s(),{refs:n,finalize:async()=>{let s=await Promise.all(t.map(async p=>{try{return p.source.resolveOn==="submit"?await p.source.resolve(p.item,this.#a(new AbortController().signal,p.args,o)):(p.resolvePromise&&await p.resolvePromise,p.payload??null)}catch(f){try{this.#e.mentionConfig.onMentionResolveError?.(p.item,f)}catch(m){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",m)}return this.#e.emit?.("resolve-error",{sourceId:p.source.id,itemId:p.item.id}),null}})),i=[],l=[],c={},d=new Set;for(let p=0;p<t.length;p++){let f=t[p],m=s[p];if(!m)continue;let g=Lx(f.source.id,f.item.id);if(!d.has(g)){if(d.add(g),m.llmAppend&&m.llmAppend.trim())try{i.push(kx({label:f.ref.label,text:m.llmAppend,ref:f.ref,item:f.item},i.length,this.#e.mentionConfig.llmFormat))}catch(h){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",h)}m.contentParts?.length&&l.push(...m.contentParts),m.context&&((c[f.source.id]??={})[f.item.id]=m.context)}}return{blocks:i,contentParts:l,context:c}}}}#s(){Ha(this.#e.contextRow)}}});function Px(e){let t=e.getRootNode?.();return t&&Ix(t)||t&&Gp(t)?t:e.ownerDocument??document}function Kp(e,t,n){let o=Gp(e)?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(Gp(e)?e:e.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",t),i.textContent=n,o.appendChild(i)}function Yp(e,t,n){if(Gp(e)||Ix(e)){Kp(e,t,n);return}let o=e;if(o.isConnected){Kp(Px(o),t,n);return}let r=o.ownerDocument??document;Kp(r,t,n),queueMicrotask(()=>{let s=Px(o);s!==r&&Kp(s,t,n)})}function uI(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Bs(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:d,onDismiss:p}=e,f=e.container??uI(t),m=!1,g=null,h=()=>{if(!m)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let S=n.getBoundingClientRect(),E=l?.()??null,k=E!=null?A.top+E:A.top,D=o==="top-start"||o==="top-end"?k-r-S.height:A.bottom+r,Y=o==="bottom-end"||o==="top-end"?A.right-S.width:A.left,T=i?.()??null;if(T!=null){let W=Math.max(A.left,A.right-S.width);Y=Math.min(Math.max(A.left+T,A.left),W)}n.style.top=`${D}px`,n.style.left=`${Y}px`},b=()=>{m&&(m=!1,g&&(g(),g=null),n.remove())},C=()=>{if(m)return;m=!0,c!=null&&(n.style.zIndex=String(c)),f.appendChild(n),h();let A=(t.ownerDocument??document).defaultView??window,S=t.ownerDocument??document,E=()=>{if(!t.isConnected){b(),p?.("anchor-removed");return}h()},k=z=>{let Y=typeof z.composedPath=="function"?z.composedPath():[];Y.includes(n)||Y.includes(t)||(b(),p?.("outside"))},D=A.setTimeout(()=>{S.addEventListener("pointerdown",k,!0)},0);A.addEventListener("scroll",E,!0),A.addEventListener("resize",E),g=()=>{A.clearTimeout(D),S.removeEventListener("pointerdown",k,!0),A.removeEventListener("scroll",E,!0),A.removeEventListener("resize",E)},d?.()};return{get isOpen(){return m},open:C,close:b,toggle:()=>m?b():C(),reposition:h,destroy:b}}function Hx(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Gp,Ix,Ra=ie(()=>{"use strict";Gp=e=>e.nodeType===Node.DOCUMENT_NODE,Ix=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host!==void 0});var Rx,Wx=ie(()=>{"use strict";Rx=`
23
23
  .persona-mention-menu {
24
24
  box-sizing: border-box;
25
25
  display: flex;
@@ -177,31 +177,31 @@ ${t}
177
177
  min-height: 36px;
178
178
  }
179
179
  }
180
- `});function Xp(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()}}var Wx=ie(()=>{"use strict"});function _x(e){let{config:t,listboxId:n}=e,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),i=Je(Dx.Search,15,"currentColor",2);i&&s.appendChild(i);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":t.searchPlaceholder??"Search context",placeholder:t.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>e.onSearchInput?.(l.value)),l.addEventListener("keydown",L=>e.onSearchKeydown?.(L));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let d=[],p=[],f=-1,m=new Map,g=(L,w)=>`${L}\0${w}`,h=L=>`${n}-opt-${L}`,b=L=>`${n}-grp-${L}`,C=(L,w)=>{let x=d[L];x&&(w?x.setAttribute("data-active","true"):x.removeAttribute("data-active"),x.setAttribute("aria-selected",w?"true":"false"),p[L]?.(w))},A=(L,w=!0)=>{f>=0&&f!==L&&C(f,!1),f=L;let x=d[L];x?(C(L,!0),w&&x.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",x.id),l.setAttribute("aria-activedescendant",x.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},S=(L,w)=>{let x=b(w),P=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":x}});return P.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:x},text:L})),P},E=()=>{let L=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),w=v("span","persona-mention-option-icon");L.appendChild(w);let x="",P=v("span","persona-mention-option-text"),I=v("span","persona-mention-option-labelline"),J=v("span","persona-mention-option-label");I.appendChild(J),P.appendChild(I),L.appendChild(P);let _=null,j=null,te={el:L,index:0,update:(K,X,oe)=>{te.index=X,L.id=h(X),L.setAttribute("aria-setsize",String(oe)),L.setAttribute("aria-posinset",String(X+1)),L.removeAttribute("data-active"),L.setAttribute("aria-selected","false");let de=K.iconName??t.chipIconName??"at-sign";if(de!==x){x=de;let Te=uI(de,15,2);w.replaceChildren(...Te?[Te]:[])}J.textContent!==K.label&&(J.textContent=K.label);let xe=K.commandArgsPlaceholder?`\u2039${K.commandArgsPlaceholder}\u203A`:null;xe?(_||(_=v("span","persona-mention-option-arghint"),I.appendChild(_)),_.textContent!==xe&&(_.textContent=xe)):_&&(_.remove(),_=null),K.description?(j||(j=v("span","persona-mention-option-desc"),P.appendChild(j)),j.textContent!==K.description&&(j.textContent=K.description)):j&&(j.remove(),j=null)}};return L.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),e.onSelectIndex(te.index))}),L.addEventListener("mouseenter",()=>e.onHoverIndex(te.index)),te},k=(L,w,x,P,I)=>{let J=F("div",{className:"persona-mention-option",attrs:{role:"option",id:h(P),"aria-selected":"false","aria-setsize":String(I),"aria-posinset":String(P+1)}}),_=j=>{J.replaceChildren(t.renderMentionItem({item:L,source:w,query:x,active:j,index:P}))};return _(!1),J.addEventListener("mousedown",j=>{j.button===0&&(j.preventDefault(),e.onSelectIndex(P))}),J.addEventListener("mouseenter",()=>e.onHoverIndex(P)),{el:J,paint:_}},D=L=>{let w=F("div",{className:"persona-mention-status persona-mention-error"});if(w.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${L.label}`})),e.onRetry){let x=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});x.addEventListener("mousedown",P=>P.preventDefault()),x.addEventListener("click",P=>{P.preventDefault(),e.onRetry(L.id)}),w.appendChild(x)}return w};return{el:o,render:L=>{c.replaceChildren(),d=[],p=[],f=-1;let w=new Set,x=0,P=0,I=0,J=0,_=0,j=L.groups.reduce((te,K)=>K.status==="ready"?te+K.items.length:te,0);for(let te of L.groups)if(te.status==="loading"){I++;let K=S(te.source.label,_++);K.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(K)}else if(te.status==="error"){J++;let K=S(te.source.label,_++);K.appendChild(D(te.source)),c.appendChild(K)}else if(te.status==="ready"&&te.items.length>0){let K=new Map;for(let oe of te.items){let de=oe.group??te.source.label,xe=K.get(de);xe?xe.push(oe):K.set(de,[oe])}let X=Array.from(K.entries());X.forEach(([oe,de],xe)=>{let Te=S(oe,_++);for(let re of de){let N=x++,ke;if(t.renderMentionItem){let ve=k(re,te.source,L.query,N,j);ke=ve.el,p.push(ve.paint)}else{let ve=g(te.source.id,re.id),tt=w.has(ve)?void 0:m.get(ve);tt||(tt=E(),w.has(ve)||m.set(ve,tt)),w.add(ve),tt.update(re,N,j),ke=tt.el,p.push(null)}d.push(ke),Te.appendChild(ke),P++}te.truncated&&xe===X.length-1&&Te.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Te)})}for(let te of m.keys())w.has(te)||m.delete(te);P===0&&I===0&&J===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),d.length>0?A(Math.min(Math.max(0,L.activeIndex),d.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:A,destroy:()=>{c.replaceChildren(),d=[],m.clear(),o.remove()},showSearch:(L,w)=>{l.value=L,w&&(l.placeholder=w),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var Dx,Bx,uI,Ox=ie(()=>{"use strict";Ge();Dx=require("lucide");ao();Up();Bx=new Map,uI=(e,t,n)=>{let o=`${e}|${t}|${n}`,r=Bx.get(o);return r===void 0&&(r=$p(e,t,"currentColor",n),Bx.set(o,r)),r?r.cloneNode(!0):null}});var fI,mI,Qp,Nx=ie(()=>{"use strict";Ra();Rx();Ep();bg();Wx();Ox();Hg();fI=e=>!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function",mI=0,Qp=class{#e;#t;#n;#o;#a;#r;#s;#g=null;#c=null;#f=!1;#p="";#l=null;#i=0;#T=null;#b=!1;#S=null;#y=[];#d=[];#u=0;#m=null;#h=null;#A=new Set;#w=new Set;#C=-1;#v=null;#I=null;constructor(t){this.#e=t;let n=t.mentionConfig,o=kp(n),r=o.filter(i=>i.sources.length>0);this.#t=r.length>0?r:[o[0]],this.#n=this.#t[0],this.#o=n.maxItemsPerGroup??6,this.#a=n.searchDebounceMs??150,this.#s=`persona-mention-listbox-${++mI}`,this.#r=t.mentionConfig.renderMentionMenu?this.#L():_x({config:t.mentionConfig,listboxId:this.#s,onSelectIndex:i=>this.#D(i),onHoverIndex:i=>this.#_(i,!1),onRetry:i=>this.#re(i),onSearchInput:i=>this.#$(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=t.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.#s)}get input(){return this.#e.composerInput}#L(){let t=document.createElement("div");t.setAttribute("data-persona-mention-menu",""),t.setAttribute("role","listbox"),t.id=this.#s;let n=()=>{let o=this.#e.mentionConfig.renderMentionMenu({query:this.#p,groups:this.#y.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.#y.map(r=>[r.source.id,r.status])),activeIndex:this.#i,select:r=>{let s=this.#y.find(i=>i.items.includes(r));s&&this.#te(s.source,r)},close:()=>this.close()});t.replaceChildren(o)};return{el:t,render:n,setActiveIndex:n,destroy:()=>t.remove()}}isOpen(){return this.#f}openFromButton(t){let n=t&&this.#t.find(i=>i.trigger===t)||this.#t[0],o=this.input.getSelection().start,r=ql(this.input.getLogicalText(),o,[n]);if(r){this.#b=!1,this.#l=r.match,this.#f?(this.#x(n),this.#$(r.match.query)):this.#R(r.match.query,n),this.input.focus();return}let s=this.#S;this.#b=!0,this.#S=n.trigger,this.#l=null,this.#f?(s&&s!==n.trigger&&this.#e.onPickerOpenChange?.(!1,s,this.#s),this.#x(n),this.#$("")):this.#R("",n),this.#r.showSearch?this.#r.showSearch("",n.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,n.trigger,this.#s)}onInput(){let t=this.input.getSelection().start,n=ql(this.input.getLogicalText(),t,this.#t);if(!n){this.#f&&this.close();return}if(this.#N(n.channel,n.match.query)){this.#l=null,this.#f&&this.close(!1);return}this.#l=n.match,this.#f?(this.#x(n.channel),this.#I!==n.match.triggerIndex&&this.#E(),this.#$(n.match.query)):this.#R(n.match.query,n.channel)}#x(t){t!==this.#n&&(this.#n=t,this.#y=[],this.#i=0)}#R(t,n){if(this.#f=!0,this.#n=n,this.#y=[],this.#i=0,this.#C=-1,!this.#g){let o=this.#Y();if(this.#g=Bs({anchor:this.#e.anchor,content:this.#r.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.#e.popoverContainer,horizontalOffset:o?()=>this.#v?.x??null:void 0,verticalOffset:o?()=>this.#v?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.#e.anchor.getBoundingClientRect().width;this.#r.el.style.minWidth=`${Math.min(220,r)}px`}}this.#E(),this.#g.open(),Yp(this.#r.el,"persona-mention-menu",Hx),this.#J(),this.#e.emit?.("opened",{trigger:n.trigger}),this.#$(t)}#J(){typeof ResizeObserver>"u"||this.#c||(this.#c=new ResizeObserver(()=>{this.#f&&(this.#E(),this.#g?.reposition())}),this.#c.observe(this.#e.anchor))}#G(){this.#c?.disconnect(),this.#c=null}#Y(){return this.#X()&&!!this.input.getLogicalRangeRect}#E(){let t=this.#l,n=this.input.getLogicalRangeRect;if(this.#I=t?.triggerIndex??null,this.#v=null,!t||!n)return;let o=n(t.triggerIndex,t.triggerIndex+1);if(!o)return;let r=this.#e.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.#v={x:l?null:o.left-r.left,y:s}}close(t=!0){this.#f&&(this.#f=!1,this.#G(),this.#h&&clearTimeout(this.#h),this.#m?.abort(),this.#u++,this.#g?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.#b&&(this.#b=!1,this.#r.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#S??this.#n.trigger,this.#s),this.#S=null,t&&this.input.focus()))}#$(t){this.#p=t,this.#i=0,this.#T=null;let n=++this.#u;this.#w.clear(),this.#m?.abort(),this.#m=new AbortController;for(let o of this.#n.sources)this.#A.has(o.id)?this.#U(o.id,"loading"):(this.#w.add(o.id),this.#W(o,n));this.#j(),this.#h&&clearTimeout(this.#h),this.#h=setTimeout(()=>{if(n===this.#u)for(let o of this.#n.sources)this.#A.has(o.id)&&!this.#w.has(o.id)&&this.#W(o,n)},this.#a)}#W(t,n){let o={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#m.signal},r;try{r=t.search(this.#p,o)}catch{this.#U(t.id,"error"),this.#j();return}fI(r)?(this.#A.add(t.id),this.#U(t.id,"loading"),r.then(s=>{n===this.#u&&(this.#ee(t.id,s),this.#j())}).catch(()=>{n===this.#u&&(this.#U(t.id,"error"),this.#j())})):this.#ee(t.id,r)}#B(t){let n=this.#y.find(o=>o.source.id===t.id);if(!n){n={source:t,items:[],status:"loading",truncated:!1};let o=this.#n.sources;this.#y.push(n),this.#y.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}#U(t,n){let o=this.#n.sources.find(r=>r.id===t);o&&(this.#B(o).status=n)}#ee(t,n){let o=this.#n.sources.find(s=>s.id===t);if(!o)return;let r=this.#B(o);r.truncated=n.length>this.#o,r.items=n.slice(0,this.#o),r.status=r.items.length===0?"empty":"ready"}#k(t){return JSON.stringify([t.source.id,t.item.id])}#z(){this.#d=[];for(let t of this.#y)if(t.status==="ready")for(let n of t.items)this.#d.push({source:t.source,item:n});if(this.#T){let t=this.#d.findIndex(n=>this.#k(n)===this.#T);this.#i=t>=0?t:Math.min(this.#i,Math.max(0,this.#d.length-1))}else this.#i>=this.#d.length&&(this.#i=Math.max(0,this.#d.length-1))}#q(){return{query:this.#p,groups:this.#y,activeIndex:this.#i}}#j(){this.#z(),this.#r.render(this.#q()),this.#O(),this.#g?.reposition();let t=this.#y.some(n=>n.status==="loading");this.#d.length===0&&t||this.#d.length!==this.#C&&(this.#C=this.#d.length,this.#e.announce(this.#d.length===0?"No matches":this.#d.length===1?"1 result":`${this.#d.length} results`),this.#e.emit?.("searched",{query:this.#p,results:this.#d.length}))}#_(t,n=!0){t<0||t>=this.#d.length||(this.#i=t,this.#T=this.#k(this.#d[t]),this.#r.setActiveIndex(t,n),this.#O())}#O(){this.#f&&!this.#b&&this.#i>=0&&this.#i<this.#d.length?this.input.element.setAttribute("aria-activedescendant",`${this.#s}-opt-${this.#i}`):this.input.element.removeAttribute("aria-activedescendant")}#re(t){let n=this.#n.sources.find(o=>o.id===t);!n||!this.#m||(this.#U(t,"loading"),this.#j(),this.#W(n,this.#u),this.#j())}handleKeydown(t){if(!this.#f)return!1;switch(t.key){case"ArrowDown":return this.#d.length===0||(t.preventDefault(),this.#_((this.#i+1)%this.#d.length)),!0;case"ArrowUp":return this.#d.length===0||(t.preventDefault(),this.#_((this.#i-1+this.#d.length)%this.#d.length)),!0;case"Home":return this.#d.length===0||(t.preventDefault(),this.#_(0)),!0;case"End":return this.#d.length===0||(t.preventDefault(),this.#_(this.#d.length-1)),!0;case"Enter":case"Tab":return this.#d.length===0?(this.close(),!1):(t.preventDefault(),this.#D(this.#i),!0);case"Escape":return t.preventDefault(),this.close(),!0;case"Backspace":return this.#p.length===0&&this.close(),!1;default:return!1}}#D(t){let n=this.#d[t];n&&this.#te(n.source,n.item)}#ce(t){return Xp(t).args}#se(t){return t.command==="server"||t.commandArgsPlaceholder!=null}#te(t,n){let o=n.command;if(this.#se(n)){this.#K(t,n);return}if(o==="action"){let s=this.#ce(this.#p);this.#ie(),this.close(),this.#V(n,s),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.#ce(this.#p),i=this.#ne();this.close(),this.#Ce(t,n,s,i),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"prompt",args:s});return}if(this.#X()){this.#de(t,n);return}this.#e.onSelect(t,n,"")&&(this.#ie(),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}#X(){return this.#e.mentionConfig.display==="inline"&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#de(t,n){if(this.#e.admitMention&&!this.#e.admitMention(t,n)){this.close(),this.input.focus();return}let o=qp(t,n),r=this.#l?this.input.insertMentionAtTrigger(o,this.#l):this.input.insertMentionAtSelection?.(o)??null;r?(this.#e.onInsertMention(r,t,n,""),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})):(this.#e.mentionConfig.onMentionRejected?.(n,"stale"),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:"stale"})),this.#l=null,this.close(),this.input.focus()}#K(t,n){let o=`${this.#n.trigger}${n.label} `,r=this.input.getSelection().start,s=this.#l?this.#l.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.#l=null,this.close(),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}#N(t,n){let{name:o}=Xp(n);return!o||n.length<=o.length?!1:t.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.#se(s)})}#F(t){for(let n of this.#t){if(!n.trigger)continue;let o=n.position==="anywhere"?[t]:n.position==="line-start"?t.split(`
180
+ `});function Xp(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()}}var Bx=ie(()=>{"use strict"});function Ox(e){let{config:t,listboxId:n}=e,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),i=Je(_x.Search,15,"currentColor",2);i&&s.appendChild(i);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":t.searchPlaceholder??"Search context",placeholder:t.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>e.onSearchInput?.(l.value)),l.addEventListener("keydown",L=>e.onSearchKeydown?.(L));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let d=[],p=[],f=-1,m=new Map,g=(L,w)=>`${L}\0${w}`,h=L=>`${n}-opt-${L}`,b=L=>`${n}-grp-${L}`,C=(L,w)=>{let x=d[L];x&&(w?x.setAttribute("data-active","true"):x.removeAttribute("data-active"),x.setAttribute("aria-selected",w?"true":"false"),p[L]?.(w))},A=(L,w=!0)=>{f>=0&&f!==L&&C(f,!1),f=L;let x=d[L];x?(C(L,!0),w&&x.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",x.id),l.setAttribute("aria-activedescendant",x.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},S=(L,w)=>{let x=b(w),P=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":x}});return P.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:x},text:L})),P},E=()=>{let L=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),w=v("span","persona-mention-option-icon");L.appendChild(w);let x="",P=v("span","persona-mention-option-text"),I=v("span","persona-mention-option-labelline"),J=v("span","persona-mention-option-label");I.appendChild(J),P.appendChild(I),L.appendChild(P);let _=null,j=null,te={el:L,index:0,update:(K,X,oe)=>{te.index=X,L.id=h(X),L.setAttribute("aria-setsize",String(oe)),L.setAttribute("aria-posinset",String(X+1)),L.removeAttribute("data-active"),L.setAttribute("aria-selected","false");let de=K.iconName??t.chipIconName??"at-sign";if(de!==x){x=de;let Te=fI(de,15,2);w.replaceChildren(...Te?[Te]:[])}J.textContent!==K.label&&(J.textContent=K.label);let xe=K.commandArgsPlaceholder?`\u2039${K.commandArgsPlaceholder}\u203A`:null;xe?(_||(_=v("span","persona-mention-option-arghint"),I.appendChild(_)),_.textContent!==xe&&(_.textContent=xe)):_&&(_.remove(),_=null),K.description?(j||(j=v("span","persona-mention-option-desc"),P.appendChild(j)),j.textContent!==K.description&&(j.textContent=K.description)):j&&(j.remove(),j=null)}};return L.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),e.onSelectIndex(te.index))}),L.addEventListener("mouseenter",()=>e.onHoverIndex(te.index)),te},k=(L,w,x,P,I)=>{let J=F("div",{className:"persona-mention-option",attrs:{role:"option",id:h(P),"aria-selected":"false","aria-setsize":String(I),"aria-posinset":String(P+1)}}),_=j=>{J.replaceChildren(t.renderMentionItem({item:L,source:w,query:x,active:j,index:P}))};return _(!1),J.addEventListener("mousedown",j=>{j.button===0&&(j.preventDefault(),e.onSelectIndex(P))}),J.addEventListener("mouseenter",()=>e.onHoverIndex(P)),{el:J,paint:_}},D=L=>{let w=F("div",{className:"persona-mention-status persona-mention-error"});if(w.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${L.label}`})),e.onRetry){let x=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});x.addEventListener("mousedown",P=>P.preventDefault()),x.addEventListener("click",P=>{P.preventDefault(),e.onRetry(L.id)}),w.appendChild(x)}return w};return{el:o,render:L=>{c.replaceChildren(),d=[],p=[],f=-1;let w=new Set,x=0,P=0,I=0,J=0,_=0,j=L.groups.reduce((te,K)=>K.status==="ready"?te+K.items.length:te,0);for(let te of L.groups)if(te.status==="loading"){I++;let K=S(te.source.label,_++);K.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(K)}else if(te.status==="error"){J++;let K=S(te.source.label,_++);K.appendChild(D(te.source)),c.appendChild(K)}else if(te.status==="ready"&&te.items.length>0){let K=new Map;for(let oe of te.items){let de=oe.group??te.source.label,xe=K.get(de);xe?xe.push(oe):K.set(de,[oe])}let X=Array.from(K.entries());X.forEach(([oe,de],xe)=>{let Te=S(oe,_++);for(let re of de){let N=x++,ke;if(t.renderMentionItem){let ve=k(re,te.source,L.query,N,j);ke=ve.el,p.push(ve.paint)}else{let ve=g(te.source.id,re.id),tt=w.has(ve)?void 0:m.get(ve);tt||(tt=E(),w.has(ve)||m.set(ve,tt)),w.add(ve),tt.update(re,N,j),ke=tt.el,p.push(null)}d.push(ke),Te.appendChild(ke),P++}te.truncated&&xe===X.length-1&&Te.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Te)})}for(let te of m.keys())w.has(te)||m.delete(te);P===0&&I===0&&J===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),d.length>0?A(Math.min(Math.max(0,L.activeIndex),d.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:A,destroy:()=>{c.replaceChildren(),d=[],m.clear(),o.remove()},showSearch:(L,w)=>{l.value=L,w&&(l.placeholder=w),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var _x,Dx,fI,Nx=ie(()=>{"use strict";Ge();_x=require("lucide");ao();Up();Dx=new Map,fI=(e,t,n)=>{let o=`${e}|${t}|${n}`,r=Dx.get(o);return r===void 0&&(r=$p(e,t,"currentColor",n),Dx.set(o,r)),r?r.cloneNode(!0):null}});var mI,gI,Qp,Fx=ie(()=>{"use strict";Ra();Wx();Ep();bg();Bx();Nx();Hg();mI=e=>!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function",gI=0,Qp=class{#e;#t;#n;#o;#a;#r;#s;#g=null;#c=null;#f=!1;#p="";#l=null;#i=0;#T=null;#b=!1;#S=null;#y=[];#d=[];#u=0;#m=null;#h=null;#A=new Set;#w=new Set;#C=-1;#v=null;#I=null;constructor(t){this.#e=t;let n=t.mentionConfig,o=kp(n),r=o.filter(i=>i.sources.length>0);this.#t=r.length>0?r:[o[0]],this.#n=this.#t[0],this.#o=n.maxItemsPerGroup??6,this.#a=n.searchDebounceMs??150,this.#s=`persona-mention-listbox-${++gI}`,this.#r=t.mentionConfig.renderMentionMenu?this.#L():Ox({config:t.mentionConfig,listboxId:this.#s,onSelectIndex:i=>this.#D(i),onHoverIndex:i=>this.#_(i,!1),onRetry:i=>this.#re(i),onSearchInput:i=>this.#$(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=t.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.#s)}get input(){return this.#e.composerInput}#L(){let t=document.createElement("div");t.setAttribute("data-persona-mention-menu",""),t.setAttribute("role","listbox"),t.id=this.#s;let n=()=>{let o=this.#e.mentionConfig.renderMentionMenu({query:this.#p,groups:this.#y.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.#y.map(r=>[r.source.id,r.status])),activeIndex:this.#i,select:r=>{let s=this.#y.find(i=>i.items.includes(r));s&&this.#te(s.source,r)},close:()=>this.close()});t.replaceChildren(o)};return{el:t,render:n,setActiveIndex:n,destroy:()=>t.remove()}}isOpen(){return this.#f}openFromButton(t){let n=t&&this.#t.find(i=>i.trigger===t)||this.#t[0],o=this.input.getSelection().start,r=ql(this.input.getLogicalText(),o,[n]);if(r){this.#b=!1,this.#l=r.match,this.#f?(this.#x(n),this.#$(r.match.query)):this.#R(r.match.query,n),this.input.focus();return}let s=this.#S;this.#b=!0,this.#S=n.trigger,this.#l=null,this.#f?(s&&s!==n.trigger&&this.#e.onPickerOpenChange?.(!1,s,this.#s),this.#x(n),this.#$("")):this.#R("",n),this.#r.showSearch?this.#r.showSearch("",n.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,n.trigger,this.#s)}onInput(){let t=this.input.getSelection().start,n=ql(this.input.getLogicalText(),t,this.#t);if(!n){this.#f&&this.close();return}if(this.#N(n.channel,n.match.query)){this.#l=null,this.#f&&this.close(!1);return}this.#l=n.match,this.#f?(this.#x(n.channel),this.#I!==n.match.triggerIndex&&this.#E(),this.#$(n.match.query)):this.#R(n.match.query,n.channel)}#x(t){t!==this.#n&&(this.#n=t,this.#y=[],this.#i=0)}#R(t,n){if(this.#f=!0,this.#n=n,this.#y=[],this.#i=0,this.#C=-1,!this.#g){let o=this.#Y();if(this.#g=Bs({anchor:this.#e.anchor,content:this.#r.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.#e.popoverContainer,horizontalOffset:o?()=>this.#v?.x??null:void 0,verticalOffset:o?()=>this.#v?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.#e.anchor.getBoundingClientRect().width;this.#r.el.style.minWidth=`${Math.min(220,r)}px`}}this.#E(),this.#g.open(),Yp(this.#r.el,"persona-mention-menu",Rx),this.#J(),this.#e.emit?.("opened",{trigger:n.trigger}),this.#$(t)}#J(){typeof ResizeObserver>"u"||this.#c||(this.#c=new ResizeObserver(()=>{this.#f&&(this.#E(),this.#g?.reposition())}),this.#c.observe(this.#e.anchor))}#G(){this.#c?.disconnect(),this.#c=null}#Y(){return this.#X()&&!!this.input.getLogicalRangeRect}#E(){let t=this.#l,n=this.input.getLogicalRangeRect;if(this.#I=t?.triggerIndex??null,this.#v=null,!t||!n)return;let o=n(t.triggerIndex,t.triggerIndex+1);if(!o)return;let r=this.#e.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.#v={x:l?null:o.left-r.left,y:s}}close(t=!0){this.#f&&(this.#f=!1,this.#G(),this.#h&&clearTimeout(this.#h),this.#m?.abort(),this.#u++,this.#g?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.#b&&(this.#b=!1,this.#r.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#S??this.#n.trigger,this.#s),this.#S=null,t&&this.input.focus()))}#$(t){this.#p=t,this.#i=0,this.#T=null;let n=++this.#u;this.#w.clear(),this.#m?.abort(),this.#m=new AbortController;for(let o of this.#n.sources)this.#A.has(o.id)?this.#U(o.id,"loading"):(this.#w.add(o.id),this.#W(o,n));this.#j(),this.#h&&clearTimeout(this.#h),this.#h=setTimeout(()=>{if(n===this.#u)for(let o of this.#n.sources)this.#A.has(o.id)&&!this.#w.has(o.id)&&this.#W(o,n)},this.#a)}#W(t,n){let o={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#m.signal},r;try{r=t.search(this.#p,o)}catch{this.#U(t.id,"error"),this.#j();return}mI(r)?(this.#A.add(t.id),this.#U(t.id,"loading"),r.then(s=>{n===this.#u&&(this.#ee(t.id,s),this.#j())}).catch(()=>{n===this.#u&&(this.#U(t.id,"error"),this.#j())})):this.#ee(t.id,r)}#B(t){let n=this.#y.find(o=>o.source.id===t.id);if(!n){n={source:t,items:[],status:"loading",truncated:!1};let o=this.#n.sources;this.#y.push(n),this.#y.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}#U(t,n){let o=this.#n.sources.find(r=>r.id===t);o&&(this.#B(o).status=n)}#ee(t,n){let o=this.#n.sources.find(s=>s.id===t);if(!o)return;let r=this.#B(o);r.truncated=n.length>this.#o,r.items=n.slice(0,this.#o),r.status=r.items.length===0?"empty":"ready"}#k(t){return JSON.stringify([t.source.id,t.item.id])}#z(){this.#d=[];for(let t of this.#y)if(t.status==="ready")for(let n of t.items)this.#d.push({source:t.source,item:n});if(this.#T){let t=this.#d.findIndex(n=>this.#k(n)===this.#T);this.#i=t>=0?t:Math.min(this.#i,Math.max(0,this.#d.length-1))}else this.#i>=this.#d.length&&(this.#i=Math.max(0,this.#d.length-1))}#q(){return{query:this.#p,groups:this.#y,activeIndex:this.#i}}#j(){this.#z(),this.#r.render(this.#q()),this.#O(),this.#g?.reposition();let t=this.#y.some(n=>n.status==="loading");this.#d.length===0&&t||this.#d.length!==this.#C&&(this.#C=this.#d.length,this.#e.announce(this.#d.length===0?"No matches":this.#d.length===1?"1 result":`${this.#d.length} results`),this.#e.emit?.("searched",{query:this.#p,results:this.#d.length}))}#_(t,n=!0){t<0||t>=this.#d.length||(this.#i=t,this.#T=this.#k(this.#d[t]),this.#r.setActiveIndex(t,n),this.#O())}#O(){this.#f&&!this.#b&&this.#i>=0&&this.#i<this.#d.length?this.input.element.setAttribute("aria-activedescendant",`${this.#s}-opt-${this.#i}`):this.input.element.removeAttribute("aria-activedescendant")}#re(t){let n=this.#n.sources.find(o=>o.id===t);!n||!this.#m||(this.#U(t,"loading"),this.#j(),this.#W(n,this.#u),this.#j())}handleKeydown(t){if(!this.#f)return!1;switch(t.key){case"ArrowDown":return this.#d.length===0||(t.preventDefault(),this.#_((this.#i+1)%this.#d.length)),!0;case"ArrowUp":return this.#d.length===0||(t.preventDefault(),this.#_((this.#i-1+this.#d.length)%this.#d.length)),!0;case"Home":return this.#d.length===0||(t.preventDefault(),this.#_(0)),!0;case"End":return this.#d.length===0||(t.preventDefault(),this.#_(this.#d.length-1)),!0;case"Enter":case"Tab":return this.#d.length===0?(this.close(),!1):(t.preventDefault(),this.#D(this.#i),!0);case"Escape":return t.preventDefault(),this.close(),!0;case"Backspace":return this.#p.length===0&&this.close(),!1;default:return!1}}#D(t){let n=this.#d[t];n&&this.#te(n.source,n.item)}#ce(t){return Xp(t).args}#se(t){return t.command==="server"||t.commandArgsPlaceholder!=null}#te(t,n){let o=n.command;if(this.#se(n)){this.#K(t,n);return}if(o==="action"){let s=this.#ce(this.#p);this.#ie(),this.close(),this.#V(n,s),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.#ce(this.#p),i=this.#ne();this.close(),this.#Ce(t,n,s,i),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"prompt",args:s});return}if(this.#X()){this.#de(t,n);return}this.#e.onSelect(t,n,"")&&(this.#ie(),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}#X(){return this.#e.mentionConfig.display==="inline"&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#de(t,n){if(this.#e.admitMention&&!this.#e.admitMention(t,n)){this.close(),this.input.focus();return}let o=qp(t,n),r=this.#l?this.input.insertMentionAtTrigger(o,this.#l):this.input.insertMentionAtSelection?.(o)??null;r?(this.#e.onInsertMention(r,t,n,""),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})):(this.#e.mentionConfig.onMentionRejected?.(n,"stale"),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:"stale"})),this.#l=null,this.close(),this.input.focus()}#K(t,n){let o=`${this.#n.trigger}${n.label} `,r=this.input.getSelection().start,s=this.#l?this.#l.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.#l=null,this.close(),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}#N(t,n){let{name:o}=Xp(n);return!o||n.length<=o.length?!1:t.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.#se(s)})}#F(t){for(let n of this.#t){if(!n.trigger)continue;let o=n.position==="anywhere"?[t]:n.position==="line-start"?t.split(`
181
181
  `):[t.split(`
182
- `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Xp(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.#se(c))return{source:l,item:c,args:i}}}}return null}async dispatchInlineCommand(t){let n=this.#F(t);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.#e.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.#V(r,s),{kind:"action"};if(i==="prompt"){let c;try{c=await o.resolve(r,this.#P(s,t))}catch(d){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",d),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??t}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.#P(s,t)),d={};return c.context&&(d[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:d}}}}}#P(t,n){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:n,args:t,signal:new AbortController().signal}}#V(t,n){if(t.action)try{Promise.resolve(t.action({args:n,config:this.#e.getConfig(),messages:this.#e.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}#ne(){return this.#l?{value:this.input.getValue(),start:this.#l.triggerIndex,end:this.input.getSelection().start}:null}async#Ce(t,n,o,r){let s=this.input,i;try{i=await t.resolve(n,{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}#ie(){if(!this.#l)return;let t=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.#l.triggerIndex,t,"");else{let n=fx(this.input.getValue(),this.#l,t);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.#l=null}destroy(){this.#G(),this.#h&&clearTimeout(this.#h),this.#m?.abort(),this.#g?.destroy(),this.#r.destroy();let t=this.input.element;t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-controls"),t.removeAttribute("aria-activedescendant")}}});function Gl(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Fx(e){let t=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:e,getValue:()=>e.value,getLogicalText:()=>e.value,getSelection:()=>({start:e.selectionStart??0,end:e.selectionEnd??0}),setSelection:(n,o=n)=>{e.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{e.value=n,e.setSelectionRange(o,o)},setValue:n=>{e.value=n,e.setSelectionRange(n.length,n.length),t(),e.focus()},submit:()=>Gl(e.form),dispatchInput:t,focus:()=>e.focus()}}var Jp=ie(()=>{"use strict"});function Rg(e,t){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",e),n.setAttribute("aria-atomic","true"),n.setAttribute("role",e==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=t.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,gI),document.body.appendChild(n)):t.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var gI,Vx=ie(()=>{"use strict";gI={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"}});function $x(e){let t=e.composerInput??Fx(e.textarea),n=Rg("polite",e.liveRegionHost),o=Rg("assertive",e.liveRegionHost),r=d=>n.announce(d),s=d=>o.announce(d),i=new jp({mentionConfig:e.mentionConfig,contextRow:e.contextRow,getMessages:e.getMessages,getConfig:e.getConfig,getComposerText:()=>t.getValue(),announce:r,announceError:s,emit:e.emit}),l=()=>new Qp({mentionConfig:e.mentionConfig,composerInput:t,anchor:e.anchor,getMessages:e.getMessages,getConfig:e.getConfig,onSelect:(d,p,f)=>i.add(d,p,f),onInsertMention:(d,p,f,m)=>i.track(d,p,f,m,g=>t.setMentionStatus?.(d,g)),admitMention:(d,p)=>i.admit(d,p),announce:r,popoverContainer:e.popoverContainer,onPickerOpenChange:e.onPickerOpenChange,emit:e.emit}),c=l();return{openMenu:d=>c.openFromButton(d),isMenuOpen:()=>c.isOpen(),handleInput:()=>c.onInput(),handleKeydown:d=>c.handleKeydown(d),hasMentions:()=>i.hasMentions(),getMentionRefs:()=>i.getRefs(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:d=>c.dispatchInlineCommand(d),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:d=>i.remove(d),rebindComposer:d=>{d!==t&&(c.destroy(),t=d,c=l())},clear:()=>i.clear(),destroy:()=>{c.destroy(),i.clear(),n.destroy(),o.destroy()}}}var Ux=ie(()=>{"use strict";Hg();Nx();Jp();Vx();Up()});var zx={};En(zx,{mountContextMentions:()=>$x,setMentionIconRenderer:()=>kg});var qx=ie(()=>{"use strict";Ux()});var YN,hI,Zp,Wg=ie(()=>{"use strict";Bn();({setLoader:YN,load:hI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(qx(),zx))})),Zp=hI});function Dg(e){return e.kind==="text"?e.value.length:1}function _g(e){let t=[],n=r=>{let s=t[t.length-1];s&&s.kind==="text"?s.value+=r:t.push({kind:"text",value:r})};(e.length===0||e[0].kind!=="text")&&t.push({kind:"text",value:""});for(let r of e){if(r.kind==="text"){n(r.value);continue}let s=t[t.length-1];(!s||s.kind!=="text")&&t.push({kind:"text",value:""}),t.push({kind:"mention",id:r.id,ref:r.ref}),t.push({kind:"text",value:""})}let o=t[t.length-1];return(!o||o.kind!=="text")&&t.push({kind:"text",value:""}),t}function jx(){return{blocks:[{kind:"text",value:""}]}}function Og(e){return{blocks:[{kind:"text",value:e}]}}function Ng(e){return e.blocks.map(t=>t.kind==="text"?t.value:`${yI}${t.ref.label}`).join("")}function tu(e){return e.blocks.map(t=>t.kind==="text"?t.value:"\uFFFC").join("")}function nu(e){return e.blocks.reduce((t,n)=>t+Dg(n),0)}function bI(e){let t=[];for(let n of e.blocks)n.kind==="mention"&&t.push({id:n.id,ref:n.ref});return t}function eu(e,t){let n=[],o=[],r=0;for(let s of e){let i=Dg(s),l=r+i;if(l<=t)n.push(s);else if(r>=t)o.push(s);else if(s.kind==="text"){let c=t-r;c>0&&n.push({kind:"text",value:s.value.slice(0,c)}),c<i&&o.push({kind:"text",value:s.value.slice(c)})}else o.push(s);r=l}return{left:n,right:o}}function Fg(e,t,n,o){let r=eu(e.blocks,t.start).left,s=eu(e.blocks,t.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",c=l!==" "&&l!==" "&&l!==`
182
+ `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Xp(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.#se(c))return{source:l,item:c,args:i}}}}return null}async dispatchInlineCommand(t){let n=this.#F(t);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.#e.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.#V(r,s),{kind:"action"};if(i==="prompt"){let c;try{c=await o.resolve(r,this.#P(s,t))}catch(d){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",d),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??t}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.#P(s,t)),d={};return c.context&&(d[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:d}}}}}#P(t,n){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:n,args:t,signal:new AbortController().signal}}#V(t,n){if(t.action)try{Promise.resolve(t.action({args:n,config:this.#e.getConfig(),messages:this.#e.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}#ne(){return this.#l?{value:this.input.getValue(),start:this.#l.triggerIndex,end:this.input.getSelection().start}:null}async#Ce(t,n,o,r){let s=this.input,i;try{i=await t.resolve(n,{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}#ie(){if(!this.#l)return;let t=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.#l.triggerIndex,t,"");else{let n=mx(this.input.getValue(),this.#l,t);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.#l=null}destroy(){this.#G(),this.#h&&clearTimeout(this.#h),this.#m?.abort(),this.#g?.destroy(),this.#r.destroy();let t=this.input.element;t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-controls"),t.removeAttribute("aria-activedescendant")}}});function Gl(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Vx(e){let t=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:e,getValue:()=>e.value,getLogicalText:()=>e.value,getSelection:()=>({start:e.selectionStart??0,end:e.selectionEnd??0}),setSelection:(n,o=n)=>{e.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{e.value=n,e.setSelectionRange(o,o)},setValue:n=>{e.value=n,e.setSelectionRange(n.length,n.length),t(),e.focus()},submit:()=>Gl(e.form),dispatchInput:t,focus:()=>e.focus()}}var Jp=ie(()=>{"use strict"});function Rg(e,t){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",e),n.setAttribute("aria-atomic","true"),n.setAttribute("role",e==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=t.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,hI),document.body.appendChild(n)):t.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var hI,$x=ie(()=>{"use strict";hI={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"}});function Ux(e){let t=e.composerInput??Vx(e.textarea),n=Rg("polite",e.liveRegionHost),o=Rg("assertive",e.liveRegionHost),r=d=>n.announce(d),s=d=>o.announce(d),i=new jp({mentionConfig:e.mentionConfig,contextRow:e.contextRow,getMessages:e.getMessages,getConfig:e.getConfig,getComposerText:()=>t.getValue(),announce:r,announceError:s,emit:e.emit}),l=()=>new Qp({mentionConfig:e.mentionConfig,composerInput:t,anchor:e.anchor,getMessages:e.getMessages,getConfig:e.getConfig,onSelect:(d,p,f)=>i.add(d,p,f),onInsertMention:(d,p,f,m)=>i.track(d,p,f,m,g=>t.setMentionStatus?.(d,g)),admitMention:(d,p)=>i.admit(d,p),announce:r,popoverContainer:e.popoverContainer,onPickerOpenChange:e.onPickerOpenChange,emit:e.emit}),c=l();return{openMenu:d=>c.openFromButton(d),isMenuOpen:()=>c.isOpen(),handleInput:()=>c.onInput(),handleKeydown:d=>c.handleKeydown(d),hasMentions:()=>i.hasMentions(),getMentionRefs:()=>i.getRefs(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:d=>c.dispatchInlineCommand(d),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:d=>i.remove(d),rebindComposer:d=>{d!==t&&(c.destroy(),t=d,c=l())},clear:()=>i.clear(),destroy:()=>{c.destroy(),i.clear(),n.destroy(),o.destroy()}}}var zx=ie(()=>{"use strict";Hg();Fx();Jp();$x();Up()});var qx={};En(qx,{mountContextMentions:()=>Ux,setMentionIconRenderer:()=>kg});var jx=ie(()=>{"use strict";zx()});var XN,yI,Zp,Wg=ie(()=>{"use strict";Bn();({setLoader:XN,load:yI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(jx(),qx))})),Zp=yI});function Dg(e){return e.kind==="text"?e.value.length:1}function _g(e){let t=[],n=r=>{let s=t[t.length-1];s&&s.kind==="text"?s.value+=r:t.push({kind:"text",value:r})};(e.length===0||e[0].kind!=="text")&&t.push({kind:"text",value:""});for(let r of e){if(r.kind==="text"){n(r.value);continue}let s=t[t.length-1];(!s||s.kind!=="text")&&t.push({kind:"text",value:""}),t.push({kind:"mention",id:r.id,ref:r.ref}),t.push({kind:"text",value:""})}let o=t[t.length-1];return(!o||o.kind!=="text")&&t.push({kind:"text",value:""}),t}function Kx(){return{blocks:[{kind:"text",value:""}]}}function Og(e){return{blocks:[{kind:"text",value:e}]}}function Ng(e){return e.blocks.map(t=>t.kind==="text"?t.value:`${bI}${t.ref.label}`).join("")}function tu(e){return e.blocks.map(t=>t.kind==="text"?t.value:"\uFFFC").join("")}function nu(e){return e.blocks.reduce((t,n)=>t+Dg(n),0)}function vI(e){let t=[];for(let n of e.blocks)n.kind==="mention"&&t.push({id:n.id,ref:n.ref});return t}function eu(e,t){let n=[],o=[],r=0;for(let s of e){let i=Dg(s),l=r+i;if(l<=t)n.push(s);else if(r>=t)o.push(s);else if(s.kind==="text"){let c=t-r;c>0&&n.push({kind:"text",value:s.value.slice(0,c)}),c<i&&o.push({kind:"text",value:s.value.slice(c)})}else o.push(s);r=l}return{left:n,right:o}}function Fg(e,t,n,o){let r=eu(e.blocks,t.start).left,s=eu(e.blocks,t.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",c=l!==" "&&l!==" "&&l!==`
183
183
  `,d=_g([...r,{kind:"mention",id:o,ref:n},...c?[{kind:"text",value:" "}]:[],...s]),p=t.start+1+(l===`
184
- `?0:1);return{doc:{blocks:d},caret:p}}function Kx(e,t){let n=0,o=0,r=!1;for(let i of e.blocks)i.kind==="mention"&&i.id===t&&(n=o,r=!0),o+=Dg(i);return r?{doc:{blocks:_g(e.blocks.filter(i=>!(i.kind==="mention"&&i.id===t)))},caret:n}:{doc:e,caret:o}}function ou(e,t,n,o){let r=nu(e),s=Math.max(0,Math.min(t,n,r)),i=Math.min(r,Math.max(t,n,0)),l=eu(e.blocks,s).left,c=eu(e.blocks,i).right;return{doc:{blocks:_g([...l,{kind:"text",value:o},...c])},caret:s+o.length}}function Gx(e){let t=[];for(let n of e.blocks)n.kind==="text"?n.value.length>0&&t.push({kind:"text",text:n.value}):t.push({kind:"mention",ref:n.ref});return{content:Ng(e),contextMentions:bI(e).map(n=>n.ref),contentSegments:t}}var yI,Vg=ie(()=>{"use strict";Ep();yI="@"});function Jl(e){return e.nodeType===1&&e.hasAttribute(Ql)}function Qx(e){return e.nodeType===1&&e.tagName==="BR"}function ru(e){return e.nodeType===3?e.data.length:Jl(e)||Qx(e)?1:e.textContent?.length??0}function Yx(e,t,n){let o=0;for(let r of Array.from(e.childNodes)){if(r===t)return r.nodeType===3?o+n:o+(n>0?ru(r):0);if(r.contains(t))return Jl(r)?o+1:o+CI(r,t,n);o+=ru(r)}if(t===e){let r=0,s=Array.from(e.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=ru(s[i]);return r}return o}function CI(e,t,n){let o=0,r=s=>{if(s===t)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let i of Array.from(s.childNodes))if(r(i))return!0;return!1};return r(e),o}function Xl(e,t){let n=0,o=Array.from(e.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=ru(s);if(t<=n+i)return s.nodeType===3?{node:s,offset:t-n}:{node:e,offset:t<=n?r:r+1};n+=i}return{node:e,offset:o.length}}function wI(e,t){let n=[];for(let o of Array.from(e.childNodes))if(Jl(o)){let r=o.getAttribute(Ql),s=t.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(Qx(o))n.push({kind:"text",value:Xx});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function Jx(e){let t=e.renderToken,n=new Map,o=e.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),e.placeholder!=null&&o.setAttribute("data-placeholder",e.placeholder);let r=!1,s=0,i=()=>wI(o,n),l=T=>{o.replaceChildren();for(let W of T.blocks)if(W.kind==="text")W.value.length>0&&o.appendChild(document.createTextNode(W.value));else{n.set(W.id,W.ref);let L=t(W.ref);L.setAttribute("contenteditable","false"),L.setAttribute(Ql,W.id),o.appendChild(L)}},c=()=>{let W=o.getRootNode().activeElement;return W===o||W!=null&&o.contains(W)},d=(T,W)=>{if(s=T,!W?.focus&&!c())return;let L=typeof window<"u"?window.getSelection():null;if(!L)return;let w=Xl(o,T);try{let x=document.createRange();x.setStart(w.node,w.offset),x.collapse(!0),L.removeAllRanges(),L.addRange(x)}catch{}},p=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},f=()=>{let T={start:s,end:s},W=typeof window<"u"?window.getSelection():null;if(!W||W.rangeCount===0)return T;let L=W.getRangeAt(0);if(!o.contains(L.startContainer))return T;let w=Yx(o,L.startContainer,L.startOffset),x=L.collapsed?w:Yx(o,L.endContainer,L.endOffset);return{start:Math.min(w,x),end:Math.max(w,x)}},m=()=>{let T=new Set;for(let W of Array.from(o.childNodes))Jl(W)&&T.add(W.getAttribute(Ql));for(let W of Array.from(n.keys()))T.has(W)||(n.delete(W),e.onMentionRemoved?.(W))},g=()=>{r||n.size!==0&&m()},h=()=>{r=!0},b=()=>{r=!1,m()},C=T=>{T.preventDefault();let W=T.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,W);else{let{start:L,end:w}=f(),x=ou(i(),L,w,W);l(x.doc),d(x.caret,{focus:!0}),m()}p()},A=T=>{if(r)return;let W=T.inputType;if(W==="insertParagraph"){T.preventDefault();let{start:te,end:K}=f(),X=ou(i(),te,K,Xx);l(X.doc),d(X.caret,{focus:!0}),n.size>0&&m(),p();return}if(W!=="deleteContentBackward"&&W!=="deleteContentForward"||n.size===0)return;let{start:L,end:w}=f();if(L!==w)return;let x=i(),P=tu(x),I=W==="deleteContentBackward"?L-1:L;if(I<0||I>=P.length||P[I]!=="\uFFFC")return;let J=0,_=null;for(let te of x.blocks){let K=te.kind==="text"?te.value.length:1;if(te.kind==="mention"&&I>=J&&I<J+K){_=te.id;break}J+=K}if(!_)return;T.preventDefault();let j=Kx(x,_);l(j.doc),d(j.caret,{focus:!0}),m(),p()},S=(T,W)=>{l(Og(T)),d(W)},E=(T,W)=>{if(!Number.isFinite(T)||!Number.isFinite(W)||W<=T)return null;try{let L=Xl(o,T),w=Xl(o,W),x=document.createRange();x.setStart(L.node,L.offset),x.setEnd(w.node,w.offset);let P=x.getBoundingClientRect();return P.width===0&&P.height===0?null:P}catch{return null}},k=(T,W,L)=>{let w=ou(i(),T,W,L);l(w.doc),d(w.caret,{focus:!0})},D=(T,W)=>{let L=i(),w=tu(L),x=W.triggerIndex,P=W.triggerIndex+1+W.query.length;if(x<0||P>w.length||w.slice(x+1,P)!==W.query)return null;let I=e.generateId(),J=Fg(L,{start:x,end:P},T,I);return l(J.doc),d(J.caret,{focus:!0}),e.onMentionInserted?.(I,T),p(),I},z=T=>{let W=i(),L=f(),x=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:L.start,end:L.end}:{start:nu(W),end:nu(W)},P=e.generateId(),I=Fg(W,x,T,P);return l(I.doc),d(I.caret,{focus:!0}),e.onMentionInserted?.(P,T),p(),P},Y=(T,W)=>{for(let L of Array.from(o.childNodes))if(Jl(L)&&L.getAttribute(Ql)===T){let w=W==="error";if(L.classList.toggle(vI,w),w){L.hasAttribute(Yl)||(L.setAttribute(Yl,L.getAttribute("aria-label")??""),L.setAttribute($g,L.getAttribute("title")??""));let x=n.get(T)?.label??"";L.setAttribute("title",`${x}: failed to attach context`),L.setAttribute("aria-label",`${x}, failed to attach context`)}else if(L.hasAttribute(Yl)){let x=L.getAttribute(Yl),P=L.getAttribute($g);x?L.setAttribute("aria-label",x):L.removeAttribute("aria-label"),P?L.setAttribute("title",P):L.removeAttribute("title"),L.removeAttribute(Yl),L.removeAttribute($g)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",h),o.addEventListener("compositionend",b),o.addEventListener("paste",C),o.addEventListener("beforeinput",A),l(jx()),{element:o,getValue:()=>Ng(i()),getLogicalText:()=>tu(i()),getDocument:i,getSelection:f,setSelection:(T,W=T)=>{let L=typeof window<"u"?window.getSelection():null;if(L)try{let w=Xl(o,T),x=Xl(o,W),P=document.createRange();P.setStart(w.node,w.offset),P.setEnd(x.node,x.offset),L.removeAllRanges(),L.addRange(P)}catch{}},setValueWithCaret:S,getLogicalRangeRect:E,setValue:T=>{l(Og(T)),o.focus(),d(T.length,{focus:!0}),p()},replaceLogicalRange:k,insertMentionAtTrigger:D,insertMentionAtSelection:z,setMentionStatus:Y,submit:()=>Gl(o.closest("form")),dispatchInput:p,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",h),o.removeEventListener("compositionend",b),o.removeEventListener("paste",C),o.removeEventListener("beforeinput",A)}}}var vI,Ql,Yl,$g,Xx,Zx=ie(()=>{"use strict";Vg();Jp();vI="persona-mention-token-error",Ql="data-mention-id",Yl="data-mention-prev-label",$g="data-mention-prev-title",Xx=`
185
- `});function AI(e,t){t.className=`${e.className} persona-composer-contenteditable`.trim();for(let r=0;r<e.style.length;r++){let s=e.style.item(r);s!=="height"&&t.style.setProperty(s,e.style.getPropertyValue(s),e.style.getPropertyPriority(s))}let n=e.getAttribute("placeholder");n&&(t.setAttribute("data-placeholder",n),t.setAttribute("aria-placeholder",n));let o=e.getAttribute("aria-label")??n;o&&t.setAttribute("aria-label",o)}function MI(e,t,n){Object.defineProperty(e,"value",{configurable:!0,get:()=>t.getValue(),set:o=>{t.setValueWithCaret(o,o.length),t.dispatchInput()}}),Object.defineProperty(e,"placeholder",{configurable:!0,get:()=>e.getAttribute("data-placeholder")??"",set:o=>{o?(e.setAttribute("data-placeholder",o),e.setAttribute("aria-placeholder",o),n||e.setAttribute("aria-label",o)):(e.removeAttribute("data-placeholder"),e.removeAttribute("aria-placeholder"),n||e.removeAttribute("aria-label"))}}),Object.defineProperty(e,"selectionStart",{configurable:!0,get:()=>t.getSelection().start}),Object.defineProperty(e,"selectionEnd",{configurable:!0,get:()=>t.getSelection().end}),e.setSelectionRange=(o,r)=>t.setSelection(o??0,r??o??0)}function eS(e){let{textarea:t}=e,n={generateId:SI,renderToken:e.renderToken,onMentionRemoved:e.onMentionRemoved,placeholder:t.getAttribute("placeholder")??void 0},o=Jx(n),r=o.element,s=t.getAttribute("aria-label")!=null;AI(t,r),MI(r,o,s),r.getInlineMessageFields=()=>Gx(o.getDocument?.()??{blocks:[]});let i=t.selectionStart??t.value.length;return o.setValueWithCaret(t.value,i),{input:o,element:r,destroy:o.destroy}}var xI,SI,tS=ie(()=>{"use strict";Zx();Vg();xI=0,SI=()=>`pmention-${++xI}`});var nS={};En(nS,{mountInlineComposer:()=>eS});var oS=ie(()=>{"use strict";tS()});var aF,TI,su,Ug=ie(()=>{"use strict";Bn();({setLoader:aF,load:TI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(oS(),nS)),resetOnSetLoader:!0})),su=TI});function Zl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=F("span",{className:Jt("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=We(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(F("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var zg=ie(()=>{"use strict";Ge();ln()});function rS(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??EI,s=e.config.contextMentions;if(!s?.enabled)return null;let i=kp(s).filter(T=>T.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(T=>T.sources.some(W=>typeof W.matchCommand=="function")),c=T=>l.some(W=>W.trigger?W.position==="line-start"?T.split(`
184
+ `?0:1);return{doc:{blocks:d},caret:p}}function Gx(e,t){let n=0,o=0,r=!1;for(let i of e.blocks)i.kind==="mention"&&i.id===t&&(n=o,r=!0),o+=Dg(i);return r?{doc:{blocks:_g(e.blocks.filter(i=>!(i.kind==="mention"&&i.id===t)))},caret:n}:{doc:e,caret:o}}function ou(e,t,n,o){let r=nu(e),s=Math.max(0,Math.min(t,n,r)),i=Math.min(r,Math.max(t,n,0)),l=eu(e.blocks,s).left,c=eu(e.blocks,i).right;return{doc:{blocks:_g([...l,{kind:"text",value:o},...c])},caret:s+o.length}}function Yx(e){let t=[];for(let n of e.blocks)n.kind==="text"?n.value.length>0&&t.push({kind:"text",text:n.value}):t.push({kind:"mention",ref:n.ref});return{content:Ng(e),contextMentions:vI(e).map(n=>n.ref),contentSegments:t}}var bI,Vg=ie(()=>{"use strict";Ep();bI="@"});function Jl(e){return e.nodeType===1&&e.hasAttribute(Ql)}function Jx(e){return e.nodeType===1&&e.tagName==="BR"}function ru(e){return e.nodeType===3?e.data.length:Jl(e)||Jx(e)?1:e.textContent?.length??0}function Xx(e,t,n){let o=0;for(let r of Array.from(e.childNodes)){if(r===t)return r.nodeType===3?o+n:o+(n>0?ru(r):0);if(r.contains(t))return Jl(r)?o+1:o+wI(r,t,n);o+=ru(r)}if(t===e){let r=0,s=Array.from(e.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=ru(s[i]);return r}return o}function wI(e,t,n){let o=0,r=s=>{if(s===t)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let i of Array.from(s.childNodes))if(r(i))return!0;return!1};return r(e),o}function Xl(e,t){let n=0,o=Array.from(e.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=ru(s);if(t<=n+i)return s.nodeType===3?{node:s,offset:t-n}:{node:e,offset:t<=n?r:r+1};n+=i}return{node:e,offset:o.length}}function xI(e,t){let n=[];for(let o of Array.from(e.childNodes))if(Jl(o)){let r=o.getAttribute(Ql),s=t.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(Jx(o))n.push({kind:"text",value:Qx});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function Zx(e){let t=e.renderToken,n=new Map,o=e.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),e.placeholder!=null&&o.setAttribute("data-placeholder",e.placeholder);let r=!1,s=0,i=()=>xI(o,n),l=T=>{o.replaceChildren();for(let W of T.blocks)if(W.kind==="text")W.value.length>0&&o.appendChild(document.createTextNode(W.value));else{n.set(W.id,W.ref);let L=t(W.ref);L.setAttribute("contenteditable","false"),L.setAttribute(Ql,W.id),o.appendChild(L)}},c=()=>{let W=o.getRootNode().activeElement;return W===o||W!=null&&o.contains(W)},d=(T,W)=>{if(s=T,!W?.focus&&!c())return;let L=typeof window<"u"?window.getSelection():null;if(!L)return;let w=Xl(o,T);try{let x=document.createRange();x.setStart(w.node,w.offset),x.collapse(!0),L.removeAllRanges(),L.addRange(x)}catch{}},p=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},f=()=>{let T={start:s,end:s},W=typeof window<"u"?window.getSelection():null;if(!W||W.rangeCount===0)return T;let L=W.getRangeAt(0);if(!o.contains(L.startContainer))return T;let w=Xx(o,L.startContainer,L.startOffset),x=L.collapsed?w:Xx(o,L.endContainer,L.endOffset);return{start:Math.min(w,x),end:Math.max(w,x)}},m=()=>{let T=new Set;for(let W of Array.from(o.childNodes))Jl(W)&&T.add(W.getAttribute(Ql));for(let W of Array.from(n.keys()))T.has(W)||(n.delete(W),e.onMentionRemoved?.(W))},g=()=>{r||n.size!==0&&m()},h=()=>{r=!0},b=()=>{r=!1,m()},C=T=>{T.preventDefault();let W=T.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,W);else{let{start:L,end:w}=f(),x=ou(i(),L,w,W);l(x.doc),d(x.caret,{focus:!0}),m()}p()},A=T=>{if(r)return;let W=T.inputType;if(W==="insertParagraph"){T.preventDefault();let{start:te,end:K}=f(),X=ou(i(),te,K,Qx);l(X.doc),d(X.caret,{focus:!0}),n.size>0&&m(),p();return}if(W!=="deleteContentBackward"&&W!=="deleteContentForward"||n.size===0)return;let{start:L,end:w}=f();if(L!==w)return;let x=i(),P=tu(x),I=W==="deleteContentBackward"?L-1:L;if(I<0||I>=P.length||P[I]!=="\uFFFC")return;let J=0,_=null;for(let te of x.blocks){let K=te.kind==="text"?te.value.length:1;if(te.kind==="mention"&&I>=J&&I<J+K){_=te.id;break}J+=K}if(!_)return;T.preventDefault();let j=Gx(x,_);l(j.doc),d(j.caret,{focus:!0}),m(),p()},S=(T,W)=>{l(Og(T)),d(W)},E=(T,W)=>{if(!Number.isFinite(T)||!Number.isFinite(W)||W<=T)return null;try{let L=Xl(o,T),w=Xl(o,W),x=document.createRange();x.setStart(L.node,L.offset),x.setEnd(w.node,w.offset);let P=x.getBoundingClientRect();return P.width===0&&P.height===0?null:P}catch{return null}},k=(T,W,L)=>{let w=ou(i(),T,W,L);l(w.doc),d(w.caret,{focus:!0})},D=(T,W)=>{let L=i(),w=tu(L),x=W.triggerIndex,P=W.triggerIndex+1+W.query.length;if(x<0||P>w.length||w.slice(x+1,P)!==W.query)return null;let I=e.generateId(),J=Fg(L,{start:x,end:P},T,I);return l(J.doc),d(J.caret,{focus:!0}),e.onMentionInserted?.(I,T),p(),I},z=T=>{let W=i(),L=f(),x=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:L.start,end:L.end}:{start:nu(W),end:nu(W)},P=e.generateId(),I=Fg(W,x,T,P);return l(I.doc),d(I.caret,{focus:!0}),e.onMentionInserted?.(P,T),p(),P},Y=(T,W)=>{for(let L of Array.from(o.childNodes))if(Jl(L)&&L.getAttribute(Ql)===T){let w=W==="error";if(L.classList.toggle(CI,w),w){L.hasAttribute(Yl)||(L.setAttribute(Yl,L.getAttribute("aria-label")??""),L.setAttribute($g,L.getAttribute("title")??""));let x=n.get(T)?.label??"";L.setAttribute("title",`${x}: failed to attach context`),L.setAttribute("aria-label",`${x}, failed to attach context`)}else if(L.hasAttribute(Yl)){let x=L.getAttribute(Yl),P=L.getAttribute($g);x?L.setAttribute("aria-label",x):L.removeAttribute("aria-label"),P?L.setAttribute("title",P):L.removeAttribute("title"),L.removeAttribute(Yl),L.removeAttribute($g)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",h),o.addEventListener("compositionend",b),o.addEventListener("paste",C),o.addEventListener("beforeinput",A),l(Kx()),{element:o,getValue:()=>Ng(i()),getLogicalText:()=>tu(i()),getDocument:i,getSelection:f,setSelection:(T,W=T)=>{let L=typeof window<"u"?window.getSelection():null;if(L)try{let w=Xl(o,T),x=Xl(o,W),P=document.createRange();P.setStart(w.node,w.offset),P.setEnd(x.node,x.offset),L.removeAllRanges(),L.addRange(P)}catch{}},setValueWithCaret:S,getLogicalRangeRect:E,setValue:T=>{l(Og(T)),o.focus(),d(T.length,{focus:!0}),p()},replaceLogicalRange:k,insertMentionAtTrigger:D,insertMentionAtSelection:z,setMentionStatus:Y,submit:()=>Gl(o.closest("form")),dispatchInput:p,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",h),o.removeEventListener("compositionend",b),o.removeEventListener("paste",C),o.removeEventListener("beforeinput",A)}}}var CI,Ql,Yl,$g,Qx,eS=ie(()=>{"use strict";Vg();Jp();CI="persona-mention-token-error",Ql="data-mention-id",Yl="data-mention-prev-label",$g="data-mention-prev-title",Qx=`
185
+ `});function MI(e,t){t.className=`${e.className} persona-composer-contenteditable`.trim();for(let r=0;r<e.style.length;r++){let s=e.style.item(r);s!=="height"&&t.style.setProperty(s,e.style.getPropertyValue(s),e.style.getPropertyPriority(s))}let n=e.getAttribute("placeholder");n&&(t.setAttribute("data-placeholder",n),t.setAttribute("aria-placeholder",n));let o=e.getAttribute("aria-label")??n;o&&t.setAttribute("aria-label",o)}function TI(e,t,n){Object.defineProperty(e,"value",{configurable:!0,get:()=>t.getValue(),set:o=>{t.setValueWithCaret(o,o.length),t.dispatchInput()}}),Object.defineProperty(e,"placeholder",{configurable:!0,get:()=>e.getAttribute("data-placeholder")??"",set:o=>{o?(e.setAttribute("data-placeholder",o),e.setAttribute("aria-placeholder",o),n||e.setAttribute("aria-label",o)):(e.removeAttribute("data-placeholder"),e.removeAttribute("aria-placeholder"),n||e.removeAttribute("aria-label"))}}),Object.defineProperty(e,"selectionStart",{configurable:!0,get:()=>t.getSelection().start}),Object.defineProperty(e,"selectionEnd",{configurable:!0,get:()=>t.getSelection().end}),e.setSelectionRange=(o,r)=>t.setSelection(o??0,r??o??0)}function tS(e){let{textarea:t}=e,n={generateId:AI,renderToken:e.renderToken,onMentionRemoved:e.onMentionRemoved,placeholder:t.getAttribute("placeholder")??void 0},o=Zx(n),r=o.element,s=t.getAttribute("aria-label")!=null;MI(t,r),TI(r,o,s),r.getInlineMessageFields=()=>Yx(o.getDocument?.()??{blocks:[]});let i=t.selectionStart??t.value.length;return o.setValueWithCaret(t.value,i),{input:o,element:r,destroy:o.destroy}}var SI,AI,nS=ie(()=>{"use strict";eS();Vg();SI=0,AI=()=>`pmention-${++SI}`});var oS={};En(oS,{mountInlineComposer:()=>tS});var rS=ie(()=>{"use strict";nS()});var lF,EI,su,Ug=ie(()=>{"use strict";Bn();({setLoader:lF,load:EI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(rS(),oS)),resetOnSetLoader:!0})),su=EI});function Zl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=F("span",{className:Jt("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=We(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(F("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var zg=ie(()=>{"use strict";Ge();ln()});function sS(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??kI,s=e.config.contextMentions;if(!s?.enabled)return null;let i=kp(s).filter(T=>T.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(T=>T.sources.some(W=>typeof W.matchCommand=="function")),c=T=>l.some(W=>W.trigger?W.position==="line-start"?T.split(`
186
186
  `).some(w=>w.startsWith(W.trigger)):(W.position==="anywhere"?T:T.split(`
187
- `)[0]).startsWith(W.trigger):!1),d=(T,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:W}))}catch{}},p=!e.chipRow,f=e.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),m=null,g=null,h=e.textarea,b=null,C=null,A=null,S=null,E=()=>{if(m)return Promise.resolve(m);if(g)return g;let T=t().then(W=>(W.setMentionIconRenderer(o),m=W.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:b??void 0,anchor:e.anchor,contextRow:f,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:Y,emit:d}),m)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),g===T&&(g=null),null));return g=T,T},k=()=>{n().then(T=>{let W=T.mountInlineComposer({textarea:e.textarea,renderToken:w=>Zl(w,{render:s.renderMentionToken}),onMentionRemoved:w=>m?.untrackMention(w)});b=W.input,C=W.destroy;let L=h;L.replaceWith(W.element),h=W.element,S={next:W.element,prev:L},A?.(W.element,L),m?m.rebindComposer(W.input):g&&g.then(w=>w?.rebindComposer(W.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};s.display==="inline"&&k();let D=[],z=new Map;for(let T of i){if(!T.showButton)continue;let W=r({config:{...s,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{E().then(L=>L?.openMenu(T.trigger))}});D.push(W),z.set(T.trigger,W.button)}let Y=(T,W,L)=>{let w=z.get(W);w&&(w.setAttribute("aria-expanded",T?"true":"false"),T?w.setAttribute("aria-controls",L):w.removeAttribute("aria-controls"))};return{affordanceButtons:D.map(T=>T.wrapper),contextRow:f,handleInput:T=>{if(m){m.handleInput();return}if(!ux(T))return;let W=h,L=W.selectionStart??0;ql(W.value,L,i)&&E().then(w=>w?.handleInput())},handleKeydown:T=>{if(m?.isMenuOpen())return m.handleKeydown(T);if(T.key==="Backspace"&&m?.hasMentions()&&!S){let W=h,L=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||L)&&m.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>m?.isMenuOpen()??!1,hasMentions:()=>m?.hasMentions()??!1,getMentionRefs:()=>m?.getMentionRefs()??[],collectForSubmit:()=>m?.collectForSubmit()??null,takeInlineCommand:async T=>c(T)?(m??await E())?.dispatchInlineCommand(T)??null:null,clear:()=>m?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:T=>{A=T,S&&T(S.next,S.prev)},destroy:()=>{m?.destroy(),C?.();for(let T of D)T.wrapper.remove();p&&f.remove()}}}var EI,sS=ie(()=>{"use strict";Ge();Ep();bg();Eg();Wg();ln();Ug();zg();EI={loadContextMentions:()=>Zp(),loadContextMentionsInline:()=>su(),renderLucideIcon:(...e)=>We(...e),createMentionButton:(...e)=>Vp(...e)}});var iS={};En(iS,{createAskUserSheetHandlers:()=>cx,createContextMentionOrchestrator:()=>rS});var aS=ie(()=>{"use strict";dx();sS()});var dS={};En(dS,{resolveApproval:()=>II,resolveAskUserQuestion:()=>HI,resolveWebMcpToolCall:()=>BI,resolveWebMcpToolCallBatch:()=>cS});async function II(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(m=>m.id===r),d={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(d),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let p=e.s.config.approval,f=p&&typeof p=="object"?p.onDecision:void 0;try{let m;if(f?m=await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):m=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),m){let g=null;if(m instanceof Response){if(!m.ok){let h=await m.json().catch(()=>null),b=h?.message??h?.error??`Approval request failed: ${m.status}`,C=h?.code==="APPROVAL_ALREADY_RESOLVED"||m.status===404&&/no paused execution/i.test(String(h?.error)),A=e.s.messages.find(S=>S.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...d,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(b)}g=m.body}else m instanceof ReadableStream&&(g=m);e.s.approvalTokens.get(r)===i&&e.s.messages.some(h=>h.id===s)&&(e.s.messages=e.s.messages.filter(h=>h.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),g?await e.s.connectStream(g,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(m){let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function HI(e,t,n){if(e.s.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let p=t.toolCall?.args,f=Array.isArray(p?.questions)?p.questions:[];if(f.length===1){let m=typeof f[0]?.question=="string"?f[0].question:"";m&&(i={[m]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,d=Array.isArray(c?.questions)?c.questions:[];if(d.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let p=i??{};d.forEach((f,m)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let h=p[g],b=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";e.appendMessage({id:`ask-user-q-${l}-${m}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${m}`,role:"user",content:b||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let p=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!p.ok){let f=await p.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${p.status}`)}p.body?await e.s.connectStream(p.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(p){let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,f||e.s.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}function RI(e,t){let o=[e.s.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()}function lS(e,t){return t.toolCall?.name!==Yr?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function WI(e,t){let n=RI(e,t);return e.s.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}function au(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.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 function cS(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let d=c.toolCall?.name,p=c.toolCall?.id;if(!d||!p)return null;let f=`${t}:${p}`;if(e.s.webMcpInflightKeys.has(f)||e.s.webMcpResolvedKeys.has(f)||lS(e,c))return null;e.s.webMcpInflightKeys.add(f),o.push(f);let m=WI(e,c),g=c.agentMetadata?.webMcpToolCallId??d;if(d===Yr)return{dedupeKey:f,resumeKey:g,output:ww(),toolMessage:c,startedAt:m,completedAt:Date.now()};let h=e.s.client.executeWebMcpToolCall(d,c.toolCall?.args,r.signal),b;if(!h)b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{b=await h}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),au(e,c,jg(A?"Aborted by cancel()":PI(C)),m),e.s.webMcpInflightKeys.delete(f),null}return r.signal.aborted?(au(e,c,jg("Aborted by cancel()"),m),e.s.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:b,toolMessage:c,startedAt:m,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(f=>f!==null),l.length===0)return;let c={};for(let f of l)c[f.resumeKey]=f.output;let d=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!d.ok){let f=await d.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${d.status}`)}let p=l[0].dedupeKey;for(let f of l){e.s.webMcpResolvedKeys.add(f.dedupeKey);let m=f.toolMessage.toolCall?.name,g=f.toolMessage.agentMetadata?.webMcpToolCallId;au(e,f.toolMessage,f.output,f.startedAt,f.completedAt,{...m===Yr?{suggestRepliesResolved:!0}:{},...m&&g?{clientToolAnswer:{toolCallId:g,toolName:m,args:f.toolMessage.toolCall?.args,result:f.output,batch:p}}:{}})}d.body&&await e.s.connectStream(d.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of l)au(e,p.toolMessage,jg("Aborted by cancel()"),p.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function BI(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await DI(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||lS(e,t)))return cS(e,n,[t])}async function DI(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var jg,PI,pS=ie(()=>{"use strict";Nl();jg=e=>({isError:!0,content:[{type:"text",text:e}]}),PI=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});var Wa,Qg=ie(()=>{"use strict";Wa=class{#e=null;#t=0;#n=[];#o=[];#a=[];#r=!1;#s=!1;#g=0;#c=!1;#f=!1;#p;#l=[];#i=0;#T=!1;#b;#S;#y;#d=null;constructor(t=24e3,n={}){this.#S=t;let o=Math.max(0,n.prebufferMs??0);this.#y=Math.round(t*o/1e3),this.#p=this.#y>0}#u(){if(!this.#e){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.#e=new o({sampleRate:this.#S})}let t=this.#e;return t.state==="suspended"&&!this.#f&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#d){let r=new Uint8Array(this.#d.length+t.length);r.set(this.#d),r.set(t,this.#d.length),n=r,this.#d=null}if(n.length%2!==0&&(this.#d=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#w(n);o.length!==0&&(this.#p?(this.#l.push(o),this.#i+=o.length,clearTimeout(this.#b),this.#i>=this.#y?this.#m():this.#T&&(this.#b=setTimeout(()=>this.#m(),this.#y/this.#S*1e3))):this.#h(o))}markStreamEnd(){this.#l.length>0&&this.#m(),this.#s=!0,this.#A()}flush(){for(let t of this.#n){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#n=[],this.#g=0,this.#t=0,this.#r=!1,this.#s=!1,this.#o=[],this.#a=[],this.#d=null,this.#l=[],this.#i=0,this.#p=this.#y>0,this.#c=!1,clearTimeout(this.#b)}setContinuousMode(t){this.#T=t}isPlaying(){return this.#r}onFinished(t){this.#o.push(t)}onStarted(t){this.#a.push(t)}pause(){this.#f=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#f=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#m(){this.#p=!1;let t=this.#l;this.#l=[],this.#i=0;for(let n of t)this.#h(n)}#h(t){if(t.length===0)return;let n=this.#u(),o=n.createBuffer(1,t.length,this.#S);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#t===0?this.#t=s:this.#t<s&&(this.#t=s,this.#y>0&&(this.#p=!0)),r.start(this.#t),this.#t+=o.duration,this.#n.push(r),this.#g++,this.#r=!0,!this.#c){this.#c=!0;let i=this.#a.slice();this.#a=[];for(let l of i)l()}r.onended=()=>{let i=this.#n.indexOf(r);i!==-1&&(this.#n.splice(i,1),this.#g--,this.#A())}}#A(){if(this.#s&&this.#g<=0&&this.#l.length===0){this.#r=!1,this.#s=!1;let t=this.#o.slice();this.#o=[];for(let n of t)n()}}#w(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 i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function cH(e,t){let n="Conversation so far:",o=t.slice(0,aH).trim(),r=iH-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-lH).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>yS&&(c=`${c.slice(0,yS-1)}\u2026`);let d=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(d.length+1>r)break;r-=d.length+1,s.unshift(d)}let i=s.length>0?[`${n}
187
+ `)[0]).startsWith(W.trigger):!1),d=(T,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:W}))}catch{}},p=!e.chipRow,f=e.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),m=null,g=null,h=e.textarea,b=null,C=null,A=null,S=null,E=()=>{if(m)return Promise.resolve(m);if(g)return g;let T=t().then(W=>(W.setMentionIconRenderer(o),m=W.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:b??void 0,anchor:e.anchor,contextRow:f,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:Y,emit:d}),m)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),g===T&&(g=null),null));return g=T,T},k=()=>{n().then(T=>{let W=T.mountInlineComposer({textarea:e.textarea,renderToken:w=>Zl(w,{render:s.renderMentionToken}),onMentionRemoved:w=>m?.untrackMention(w)});b=W.input,C=W.destroy;let L=h;L.replaceWith(W.element),h=W.element,S={next:W.element,prev:L},A?.(W.element,L),m?m.rebindComposer(W.input):g&&g.then(w=>w?.rebindComposer(W.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};s.display==="inline"&&k();let D=[],z=new Map;for(let T of i){if(!T.showButton)continue;let W=r({config:{...s,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{E().then(L=>L?.openMenu(T.trigger))}});D.push(W),z.set(T.trigger,W.button)}let Y=(T,W,L)=>{let w=z.get(W);w&&(w.setAttribute("aria-expanded",T?"true":"false"),T?w.setAttribute("aria-controls",L):w.removeAttribute("aria-controls"))};return{affordanceButtons:D.map(T=>T.wrapper),contextRow:f,handleInput:T=>{if(m){m.handleInput();return}if(!fx(T))return;let W=h,L=W.selectionStart??0;ql(W.value,L,i)&&E().then(w=>w?.handleInput())},handleKeydown:T=>{if(m?.isMenuOpen())return m.handleKeydown(T);if(T.key==="Backspace"&&m?.hasMentions()&&!S){let W=h,L=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||L)&&m.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>m?.isMenuOpen()??!1,hasMentions:()=>m?.hasMentions()??!1,getMentionRefs:()=>m?.getMentionRefs()??[],collectForSubmit:()=>m?.collectForSubmit()??null,takeInlineCommand:async T=>c(T)?(m??await E())?.dispatchInlineCommand(T)??null:null,clear:()=>m?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:T=>{A=T,S&&T(S.next,S.prev)},destroy:()=>{m?.destroy(),C?.();for(let T of D)T.wrapper.remove();p&&f.remove()}}}var kI,iS=ie(()=>{"use strict";Ge();Ep();bg();Eg();Wg();ln();Ug();zg();kI={loadContextMentions:()=>Zp(),loadContextMentionsInline:()=>su(),renderLucideIcon:(...e)=>We(...e),createMentionButton:(...e)=>Vp(...e)}});var aS={};En(aS,{createAskUserSheetHandlers:()=>dx,createContextMentionOrchestrator:()=>sS});var lS=ie(()=>{"use strict";px();iS()});var pS={};En(pS,{resolveApproval:()=>HI,resolveAskUserQuestion:()=>RI,resolveWebMcpToolCall:()=>DI,resolveWebMcpToolCallBatch:()=>dS});async function HI(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(m=>m.id===r),d={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(d),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let p=e.s.config.approval,f=p&&typeof p=="object"?p.onDecision:void 0;try{let m;if(f?m=await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):m=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),m){let g=null;if(m instanceof Response){if(!m.ok){let h=await m.json().catch(()=>null),b=h?.message??h?.error??`Approval request failed: ${m.status}`,C=h?.code==="APPROVAL_ALREADY_RESOLVED"||m.status===404&&/no paused execution/i.test(String(h?.error)),A=e.s.messages.find(S=>S.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...d,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(b)}g=m.body}else m instanceof ReadableStream&&(g=m);e.s.approvalTokens.get(r)===i&&e.s.messages.some(h=>h.id===s)&&(e.s.messages=e.s.messages.filter(h=>h.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),g?await e.s.connectStream(g,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(m){let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function RI(e,t,n){if(e.s.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let p=t.toolCall?.args,f=Array.isArray(p?.questions)?p.questions:[];if(f.length===1){let m=typeof f[0]?.question=="string"?f[0].question:"";m&&(i={[m]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,d=Array.isArray(c?.questions)?c.questions:[];if(d.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let p=i??{};d.forEach((f,m)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let h=p[g],b=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";e.appendMessage({id:`ask-user-q-${l}-${m}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${m}`,role:"user",content:b||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let p=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!p.ok){let f=await p.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${p.status}`)}p.body?await e.s.connectStream(p.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(p){let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,f||e.s.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}function WI(e,t){let o=[e.s.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()}function cS(e,t){return t.toolCall?.name!==Yr?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function BI(e,t){let n=WI(e,t);return e.s.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}function au(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.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 function dS(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let d=c.toolCall?.name,p=c.toolCall?.id;if(!d||!p)return null;let f=`${t}:${p}`;if(e.s.webMcpInflightKeys.has(f)||e.s.webMcpResolvedKeys.has(f)||cS(e,c))return null;e.s.webMcpInflightKeys.add(f),o.push(f);let m=BI(e,c),g=c.agentMetadata?.webMcpToolCallId??d;if(d===Yr)return{dedupeKey:f,resumeKey:g,output:ww(),toolMessage:c,startedAt:m,completedAt:Date.now()};let h=e.s.client.executeWebMcpToolCall(d,c.toolCall?.args,r.signal),b;if(!h)b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{b=await h}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),au(e,c,jg(A?"Aborted by cancel()":II(C)),m),e.s.webMcpInflightKeys.delete(f),null}return r.signal.aborted?(au(e,c,jg("Aborted by cancel()"),m),e.s.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:b,toolMessage:c,startedAt:m,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(f=>f!==null),l.length===0)return;let c={};for(let f of l)c[f.resumeKey]=f.output;let d=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!d.ok){let f=await d.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${d.status}`)}let p=l[0].dedupeKey;for(let f of l){e.s.webMcpResolvedKeys.add(f.dedupeKey);let m=f.toolMessage.toolCall?.name,g=f.toolMessage.agentMetadata?.webMcpToolCallId;au(e,f.toolMessage,f.output,f.startedAt,f.completedAt,{...m===Yr?{suggestRepliesResolved:!0}:{},...m&&g?{clientToolAnswer:{toolCallId:g,toolName:m,args:f.toolMessage.toolCall?.args,result:f.output,batch:p}}:{}})}d.body&&await e.s.connectStream(d.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of l)au(e,p.toolMessage,jg("Aborted by cancel()"),p.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function DI(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await _I(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||cS(e,t)))return dS(e,n,[t])}async function _I(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var jg,II,uS=ie(()=>{"use strict";Nl();jg=e=>({isError:!0,content:[{type:"text",text:e}]}),II=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});var Wa,Qg=ie(()=>{"use strict";Wa=class{#e=null;#t=0;#n=[];#o=[];#a=[];#r=!1;#s=!1;#g=0;#c=!1;#f=!1;#p;#l=[];#i=0;#T=!1;#b;#S;#y;#d=null;constructor(t=24e3,n={}){this.#S=t;let o=Math.max(0,n.prebufferMs??0);this.#y=Math.round(t*o/1e3),this.#p=this.#y>0}#u(){if(!this.#e){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.#e=new o({sampleRate:this.#S})}let t=this.#e;return t.state==="suspended"&&!this.#f&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#d){let r=new Uint8Array(this.#d.length+t.length);r.set(this.#d),r.set(t,this.#d.length),n=r,this.#d=null}if(n.length%2!==0&&(this.#d=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#w(n);o.length!==0&&(this.#p?(this.#l.push(o),this.#i+=o.length,clearTimeout(this.#b),this.#i>=this.#y?this.#m():this.#T&&(this.#b=setTimeout(()=>this.#m(),this.#y/this.#S*1e3))):this.#h(o))}markStreamEnd(){this.#l.length>0&&this.#m(),this.#s=!0,this.#A()}flush(){for(let t of this.#n){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#n=[],this.#g=0,this.#t=0,this.#r=!1,this.#s=!1,this.#o=[],this.#a=[],this.#d=null,this.#l=[],this.#i=0,this.#p=this.#y>0,this.#c=!1,clearTimeout(this.#b)}setContinuousMode(t){this.#T=t}isPlaying(){return this.#r}onFinished(t){this.#o.push(t)}onStarted(t){this.#a.push(t)}pause(){this.#f=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#f=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#m(){this.#p=!1;let t=this.#l;this.#l=[],this.#i=0;for(let n of t)this.#h(n)}#h(t){if(t.length===0)return;let n=this.#u(),o=n.createBuffer(1,t.length,this.#S);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#t===0?this.#t=s:this.#t<s&&(this.#t=s,this.#y>0&&(this.#p=!0)),r.start(this.#t),this.#t+=o.duration,this.#n.push(r),this.#g++,this.#r=!0,!this.#c){this.#c=!0;let i=this.#a.slice();this.#a=[];for(let l of i)l()}r.onended=()=>{let i=this.#n.indexOf(r);i!==-1&&(this.#n.splice(i,1),this.#g--,this.#A())}}#A(){if(this.#s&&this.#g<=0&&this.#l.length===0){this.#r=!1,this.#s=!1;let t=this.#o.slice();this.#o=[];for(let n of t)n()}}#w(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 i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function dH(e,t){let n="Conversation so far:",o=t.slice(0,lH).trim(),r=aH-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-cH).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>bS&&(c=`${c.slice(0,bS-1)}\u2026`);let d=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(d.length+1>r)break;r-=d.length+1,s.unshift(d)}let i=s.length>0?[`${n}
188
188
  ${s.join(`
189
189
  `)}`]:[];return o&&i.push(o),i.join(`
190
190
 
191
- `)}function dH(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===qI?new Uint8Array(e,44):new Uint8Array(e)}function bS(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 pH(e){return bS(e).replace(/^ws/i,"http")}function uH(e){return typeof e!="number"||!Number.isFinite(e)?YI:Math.min(QI,Math.max(XI,Math.round(e)))}var Jg,VI,$I,UI,zI,qI,jI,KI,GI,YI,XI,QI,JI,ZI,eH,tH,nH,oH,rH,sH,hS,du,iH,aH,lH,yS,Ba,Zg=ie(()=>{"use strict";Qg();wp();Jg=16e3,VI=24e3,$I=4096,UI=Jg*2*8,zI=4,qI=1380533830,jI=3e4,KI=1e3,GI=5e3,YI=3e4,XI=3e4,QI=6e5,JI="full-duplex-v1",ZI=300,eH=2e3,tH=2e3,nH="runtype-browser-v1",oH=54e4,rH="You're talking to an AI assistant. Voice is processed by OpenAI.",sH=new Map([["idle_timeout","Voice call ended after a quiet period."],["max_duration","This voice call reached its time limit."],["provider_ended","The voice session ended."],["quota","Voice is unavailable right now."],["auth_expired","Voice session expired. Tap the mic to reconnect."]]),hS=["provider_error","server_restart"],du="Voice connection lost.",iH=8e3,aH=4e3,lH=12,yS=2e3;Ba=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#t=null;this.#n=[];this.#o=null;this.#a=null;this.#r=null;this.#s=[];this.#g=0;this.#c=null;this.#f=!1;this.#p=!1;this.#l=0;this.#i=!1;this.#T=Number.NEGATIVE_INFINITY;this.#b=null;this.#S=!1;this.#y=!1;this.#d=0;this.#u=0;this.#h=!1;this.bridge=null;this.#A=!1;this.#w=new Set;this.#C=new Map;this.#v=new Set;this.#L=null;this.#x=null;this.#J=!1;this.#G=!1;this.#Y=!1;this.#E=null;this.#$=null;this.#W=Promise.resolve();this.#B=new Set;this.#U=new Set;this.#ee=null;this.#k=!1;this.#z=new Set;this.#q=new Set;this.#j=[];this.#_=[];this.#O=[];this.#re=[];this.#D=[]}#e;#t;#n;#o;#a;#r;#s;#g;#c;#f;#p;#l;#i;#T;#b;#S;#y;#d;#u;#m;#h;#A;#w;#C;#v;#I;#L;#x;#R;#J;#G;#Y;#E;#$;#W;#B;#U;#ee;#k;#z;#q;#j;#_;#O;#re;#D;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#f||this.#b)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.#T<jI)){this.#T=r;try{this.config?.prewarmMode==="attach"?this.#se(o,t,n):this.#ce(o,t,n)}catch{}}}#ce(t,n,o){if(typeof fetch!="function")return;let r=`${pH(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#se(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=uH(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#K(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},d=new Promise(f=>{c=f}),p={ws:l,state:"connecting",ready:d,settle:c,openedAt:0,idleTimer:void 0};this.#b=p,l.onopen=()=>{this.#b===p&&(p.state=l.protocol==="runtype.attach"?"attached":"live",p.openedAt=Date.now(),this.#te(p,i),p.state==="attached"&&l.send('{"type":"ping"}'),p.settle())},l.onmessage=f=>{if(this.#b!==p||typeof f.data!="string")return;let m;try{m=JSON.parse(f.data)}catch{return}m.type==="attached"&&typeof m.idleMs=="number"&&this.#te(p,m.idleMs-(Date.now()-p.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#b===p&&this.#X()}}#te(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#b===t&&this.#X()},Math.max(0,n))}#X(){let t=this.#b;if(!t)return;this.#b=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#de(){let t=this.#b;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,GI)})]),clearTimeout(n)}return this.#b!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#X(),null):(this.#b=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#K(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back","delegation_stream"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:nH,clientVersion:`persona/${br}`,voiceCapabilities:JI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${bS(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#f)return;let t=this.#G;t||(this.#J=!1,this.#x=null),this.#G=!1;let n=this.config?.agentId,o=this.config?.clientToken,r=this.config?.host;if(!n)throw new Error("Runtype voice requires an agentId");if(!o)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.#l;this.#i=!1,this.#f=!0;try{let i=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Jg,channelCount:1,echoCancellation:!0}});if(s!==this.#l){i.getTracks().forEach(m=>m.stop());return}this.#o=i;let l=window.AudioContext||window.webkitAudioContext,c=new l({sampleRate:Jg});if(this.#t=c,c.state==="suspended"){if(await Promise.race([c.resume().catch(()=>{}),new Promise(m=>setTimeout(m,t?500:KI))]),s!==this.#l)return;if(c.state!=="running")throw t?new Error(this.#x=`${du} Tap the mic to reconnect.`):new Error("Audio blocked until a tap")}let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Wa(VI);if(s!==this.#l){d.destroy(),i.getTracks().forEach(m=>m.stop()),c.close().catch(()=>{});return}this.#c=d,this.#oe(),this.#P(c,i,s);let p=await this.#de();if(s!==this.#l){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:m}=p;this.#e=m,this.#N(m,s),p.live||m.send('{"type":"start"}'),this.#V(m),this.#M("listening");return}let f=new WebSocket(this.#K(r,n),["runtype.bearer",o]);f.binaryType="arraybuffer",this.#e=f,f.onopen=()=>{s===this.#l&&(this.#V(f),this.#M("listening"))},this.#N(f,s)}catch(i){throw this.#ae(),this.#ue(i),this.#M("error"),i}}#N(t,n){t.onmessage=o=>this.#ne(o,n),t.onerror=()=>{n!==this.#l||this.#L||(this.#ue(new Error("Voice connection failed")),this.#M("error"),this.#ae())},t.onclose=o=>{if(this.#i){this.#i=!1;return}if(n!==this.#l)return;let r=this.#L??(o.code===4408?{reason:"idle_timeout"}:null);if(!r){if(o.code!==1e3){let s=o.code?` (code ${o.code})`:"";this.#ue(new Error(`Voice connection closed${s}`)),this.#M("error")}else this.#M("idle");this.#ae();return}this.#F(r.reason,r.message)}}#F(t,n){let o=hS.includes(t)&&!this.#J;if(this.#ae(),o){this.#J=!0,this.#f=!0,this.#x=t==="provider_error"?`${du} Reconnecting\u2026`:"Reconnecting\u2026",this.#R=setTimeout(()=>{this.#f=!1,this.#G=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#M("idle");return}if(hS.includes(t))return this.#x=du,this.#ue(new Error(du)),this.#M("error");if(t==="error")return this.#M("error");this.#x=t==="quota"&&n||sH.get(t)||null,this.#M("idle")}takeNotice(){let t=this.#x;return this.#x=null,t}getDisclosure(){let t=this.config?.disclosureText;return this.#f&&this.#S&&t!==!1?t||rH:null}async stopListening(){this.#ae(),this.#M("idle")}async disconnect(){this.#ae(),this.#M("disconnected"),this.#j=[],this.#_=[],this.#O=[],this.#re=[],this.#D=[]}stopPlayback(){this.#ke();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#S&&(this.#d=Date.now()+eH,t.send('{"type":"cancel"}')),this.#M("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#f}onLevel(t){this.#n.push(t)}async deactivateBargeIn(){this.#ae(),this.#M("idle")}#P(t,n,o){let r=t.createMediaStreamSource(n);this.#a=r;let s=t.createScriptProcessor($I,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#l)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let d=i.inputBuffer.getChannelData(0),p=new Int16Array(d.length),f=0;for(let m=0;m<d.length;m++){let g=Math.max(-1,Math.min(1,d[m]));f+=g*g,p[m]=g<0?g*32768:g*32767}if(l&&c)this.#V(l),l.send(p.buffer);else for(this.#s.push(p.buffer),this.#g+=p.byteLength;this.#g>UI;)this.#g-=this.#s.shift().byteLength;if(this.#n.length>0){let m=Math.sqrt(f/d.length),g=Math.max(0,Math.min(1,m*zI));for(let h of this.#n)h(g)}},r.connect(s),s.connect(t.destination)}#V(t){for(let n of this.#s)t.send(n);this.#s=[],this.#g=0}#ne(t,n){if(n!==this.#l)return;if(t.data instanceof ArrayBuffer){this.#Se(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#S=o.speechMode==="speech_to_speech",this.#c?.setContinuousMode?.(this.#S)),Array.isArray(o.capabilities)&&(this.#w=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#I=o.callId),this.#A=this.#S&&this.#w.has("client_delegation")&&!!this.bridge,this.#S&&!this.#p&&this.#M("listening"),this.#w.has("context")&&!this.#Y&&(this.#Y=!0,this.#E=this.#Ce());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#he())break;let i=String(s);if(r==="user")o.final===!0&&this.#ie(n),this.#k=!1;else{if(this.#w.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#B.has(l)&&!this.#z.has(i)?(this.#q.add(i),this.#k=!1):this.#k&&!this.#z.has(i)&&(this.#q.add(i),this.#k=!1)}else this.#k&&!this.#z.has(i)&&(this.#q.add(i),this.#k=!1);if(this.#z.add(i),this.#q.has(i))break}this.#fe(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#A&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#ie(n);let s=o.input;this.#A&&s&&this.#Ee(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#B.has(r)&&!this.#U.delete(r)&&!this.#w.has("delegation_read_back")&&this.#xe(r);this.#y=o.type==="delegation_started",!this.#p&&!this.#he()&&this.#M(this.#y?"processing":"listening");break}case"delegation_progress":{let r=String(o.delegationId);this.#B.has(r)&&!this.#U.has(r)&&!this.#v.has(r)&&(this.#U.add(r),this.#xe(r));break}case"delegation_cancelled":this.#Te(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#I??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#Te(String(o.delegationId));break;case"audio_clear":this.#ke(),this.#d=0,this.#M("listening");break;case"transcript_interim":this.#M("listening"),this.#fe("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#M(r==="user"?"processing":"speaking"),this.#fe(r,o.text??"",!0);break}case"audio_end":this.#c?this.#c.markStreamEnd():(this.#p=!1,this.#M("listening"));break;case"metrics":this.#pe({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#ue(new Error(o.error||"Voice error")),this.#M("error");break;case"session_end":this.#L={reason:String(o.reason),...typeof o.message=="string"&&{message:o.message}};break}}async#Ce(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return cH(t,n)}#ie(t){let n=this.#E;if(!n)return;this.#E=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#l||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#$={done:r,drop:()=>o=!0}}async#we(){let t=this.#$;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),tH)})]);clearTimeout(n),o&&t.drop()}#xe(t){this.#k=!0,this.#ee=t}#Te(t,n=!1){this.#v.add(t),this.#ee===t&&(this.#k=!1),this.#U.delete(t),this.bridge?.dropDelegation?.(t,n),this.#C.get(t)?.abort()}#Ee(t,n,o){let r=this.bridge,s=({type:l,...c})=>{let d=this.#e;return o!==this.#l||d?.readyState!==WebSocket.OPEN||this.#v.has(t)?!1:(d.send(JSON.stringify({type:l,delegationId:t,...c})),!0)},i=(l,c,d,p=0)=>s({type:l,status:c,text:d,...p>0&&{streamedChars:p}});this.#W=this.#W.then(async()=>{if(o!==this.#l||this.#v.has(t))return;let l=null,c=this.#w.has("delegation_stream")&&this.#w.has("delegation_read_back"),d=C=>{l=(l??this.#we()).then(()=>{s({type:"delegation_delta",text:C})&&this.#B.add(t)})},p=await r.runDelegatedTurn(c?{...n,stream:d}:n).catch(()=>({status:"failed",text:""}));await this.#we(),await l;let f=c?p.streamedChars??0:0,m=!!p.followUp,g=m&&this.#w.has("delegation_update");if(!i(g?"delegation_update":"delegation_result",m&&!g?"completed":p.status,p.text,f)||(p.status!=="failed"&&p.inChat!==!1&&this.#B.add(t),!p.followUp))return;let b=new AbortController;this.#C.set(t,b),p.followUp({signal:b.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,oH),readBack:g,onUpdate:C=>i("delegation_update","pending_approval",C)}).then(C=>{this.#C.delete(t),g&&C&&!b.signal.aborted&&i("delegation_result",C.status,C.text)})})}#Se(t,n){if(n!==this.#l||!this.#c||this.#he())return;let o=dH(t);o.length!==0&&(this.#p||(this.#p=!0,this.#M("speaking")),this.#oe(),this.#c.enqueue(o),this.#S&&this.#Ie(o.length))}#he(){return Date.now()<this.#d}#oe(){if(this.#h||!this.#c)return;this.#h=!0;let t=this.#l;this.#c.onFinished(()=>{t===this.#l&&(this.#h=!1,this.#Ae())})}#Ie(t){let n=Date.now();this.#u=Math.max(n,this.#u)+t/48,clearTimeout(this.#m),this.#m=setTimeout(()=>this.#Ae(),this.#u-n+ZI)}#Ae(){this.#p=!1,this.#u=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#M(this.#y?"processing":"listening")}#ke(){this.#c?.flush(),this.#h=!1,this.#oe(),this.#p=!1,this.#u=0,clearTimeout(this.#m)}#ae(){this.#l+=1,this.#f=!1,this.#p=!1,this.#X(),this.#S=!1,this.#y=!1,this.#A=!1,this.#w=new Set;for(let t of this.#C.values())t.abort();if(this.#C.clear(),this.#v.clear(),this.#I=void 0,this.#L=null,clearTimeout(this.#R),this.#Y=!1,this.#E=null,this.#$=null,this.#W=Promise.resolve(),this.#B.clear(),this.#U.clear(),this.#ee=null,this.#k=!1,this.#z.clear(),this.#q.clear(),this.#h=!1,this.#d=0,this.#u=0,clearTimeout(this.#m),this.#s=[],this.#g=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#a&&(this.#a.disconnect(),this.#a=null),this.#o&&(this.#o.getTracks().forEach(t=>t.stop()),this.#o=null),this.#t&&(this.#t.close().catch(()=>{}),this.#t=null),this.#c&&(this.#c.destroy(),this.#c=null),this.#e){this.#i=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#j.push(t)}onError(t){this.#_.push(t)}onStatusChange(t){this.#O.push(t)}onTranscript(t){this.#re.push(t)}onMetrics(t){this.#D.push(t)}#M(t){this.#O.forEach(n=>n(t))}#ue(t){this.#_.forEach(n=>n(t))}#fe(t,n,o,r){this.#re.forEach(s=>s(t,n,o,r))}#pe(t){this.#D.forEach(n=>n(t))}}});var Ds,eh=ie(()=>{"use strict";Ds=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#t=[];this.#n=[];this.#o=[];this.#a=!1;this.#r=typeof window<"u"?window:void 0}#e;#t;#n;#o;#a;#r;async connect(){this.#o.forEach(t=>t("connected"))}async startListening(){try{if(this.#a)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.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.#t.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#n.forEach(o=>o(new Error(n.error))),this.#o.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#a=!0,this.#o.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#a=!1,this.#o.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#n.forEach(n=>n(t)),this.#o.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#a=!1,this.#o.forEach(t=>t("idle"))}onResult(t){this.#t.push(t)}onError(t){this.#n.push(t)}onStatusChange(t){this.#o.push(t)}async disconnect(){await this.stopListening(),this.#o.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ba(e.runtype);case"browser":if(!Ds.isSupported())throw new Error("Browser speech recognition not supported");return new Ds(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 th(e){if(e?.type==="custom"&&e.custom)return nc({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return nc({type:"runtype",runtype:e.runtype});if(Ds.isSupported())return nc({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function vS(e){try{return th(e),!0}catch{return!1}}var CS=ie(()=>{"use strict";Zg();eh()});var wS,pu,xS=ie(()=>{"use strict";wS=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),pu=class{constructor(t){this.host=t;this.turns=new Map;this.latestId=null;this.cancelled=new Set}apply(t,n,o,r,s,i){let l=this.host;n=n.trim();let c=this.turns.get(r);if(c||(c={},this.turns.set(r,c),this.latestId=r),t==="user"){c.userFinal=o;let d=c.userId?l.find(c.userId):void 0;if(d){let p=c.userStartMs===void 0&&s!==void 0;p&&(c.userStartMs=s),l.upsert({...d,content:n,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else{c.userStartMs=s;let p=c.assistantId?l.find(c.assistantId):void 0;c.userId=l.inject({role:"user",content:n,streaming:!1,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s)??p)}).id}}else if(!this.cancelled.has(r)){c.assistantFinal=o;let d=c.assistantId?l.find(c.assistantId):void 0;if(d){let p=c.assistantStartMs===void 0&&s!==void 0;p&&(c.assistantStartMs=s),l.upsert({...d,content:n,streaming:!o,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else n&&(c.assistantStartMs=s,c.assistantId=l.inject({role:"assistant",content:n,streaming:!o,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s))}).id);o&&c.assistantId&&l.markSpoken(c.assistantId)}this.sync()}claimUserTurn(t,n=[]){let o=n[n.length-1];for(let s of n)s!==o&&(this.turns.has(s)||this.turns.set(s,{}),this.turns.get(s).claimed=!0);let r;if(o){if(r=this.turns.get(o),r||(r={},this.turns.set(o,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:"user",content:t.trim()}).id)}else{let s=wS(t),i=[...this.turns.values()].reverse().flatMap(l=>{let c=l.userId&&!l.claimed?this.host.find(l.userId):void 0;return c?[{turn:l,text:wS(c.content)}]:[]}).filter(({text:l})=>l&&s);r=(i.find(({text:l})=>l===s)??i.find(({text:l})=>l.startsWith(s)||s.startsWith(l)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let t=this.inFlight();if(t.length===0){let n=this.awaiting();if(!n)return;t=[n]}for(let n of t)this.cancelled.add(n);this.closeReplies(t),this.sync()}fail(t){let n=this.awaiting(),o=this.inFlight();if(!n&&o.length===0)return;for(let i of o)this.turns.get(i).assistantFinal=!0;this.closeReplies(o);let r=this.host.inject({role:"assistant",content:t,streaming:!1,voiceProcessing:!1}),s=n?this.turns.get(n):void 0;s&&(s.assistantId=r.id,s.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let t=this.pending(),n=new Set;for(let o of this.turns.values())o.userId&&n.add(o.userId),o.assistantId&&(n.add(o.assistantId),this.host.markSpoken(o.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(n),t&&this.host.setStreaming(!1)}startedAfter(t){if(t===void 0)return;let n;for(let o of this.turns.values())for(let[r,s]of[[o.userId,o.userStartMs],[o.assistantId,o.assistantStartMs]])r&&s!==void 0&&s>t&&(!n||s<n.start)&&(n={start:s,id:r});return n&&this.host.find(n.id)}placeBefore(t){if(!t)return;let n=t.sequence??0,o=n-1;for(let r of this.turns.values())for(let s of[r.userId,r.assistantId]){let i=s?this.host.find(s):void 0,l=i?.sequence;i?.createdAt===t.createdAt&&l!==void 0&&l>o&&l<n&&(o=l)}return{createdAt:t.createdAt,sequence:(o+n)/2}}closeReplies(t){let n=new Set;for(let o of t){let r=this.turns.get(o)?.assistantId;r&&(n.add(r),this.host.markSpoken(r))}n.size>0&&this.host.settle(n)}inFlight(){let t=[];for(let[n,o]of this.turns)o.assistantId&&!o.assistantFinal&&!this.cancelled.has(n)&&t.push(n);return t}awaiting(){let t=this.latestId;if(!t)return null;let n=this.turns.get(t);return n?.userFinal&&!n.assistantId&&!n.claimed&&!this.cancelled.has(t)?t:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}});function gH(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,"").toLowerCase();if(fH.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let o=e.length-t.length;return o===0||/\n\s*$/.test(e.slice(0,o))}return!1}function*SS(e,t){let n=new RegExp(mH.source,"g");for(let o=n.exec(e);o;o=n.exec(e)){let r=o[1];if(!e.slice(0,o.index+(r?.length??0)).trim()||r!==void 0&&(/^[,;:]$/.test(r)&&!t||r==="."&&gH(e.slice(0,o.index))))continue;let s=o.index+o[0].length;s<e.length&&(yield s)}}function AS(e,t){let n=e.slice(0,t),o=0;for(let r of n.matchAll(/\s+/g))n.slice(0,r.index).trim()&&(o=r.index+r[0].length);return o}function nh(e){let t=0;for(let r of SS(e.slice(0,220),!0))t=r;if(t)return t;let n=AS(e,220);if(n)return n;let o=e.charCodeAt(219);return o>=55296&&o<=56319?219:220}var fH,mH,uu,MS=ie(()=>{"use strict";fH=new Set(["mr","mrs","ms","dr","prof","sr","jr","st","mt","vs","etc","approx","inc","ltd","co","corp","no","nos","fig","ft","dept","est","min","max","e.g","i.e","a.m","p.m","u.s","u.k"]),mH=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;uu=class{#e="";#t=!0;push(t){return this.#e+=t,this.#n()}flush(){let t=this.#n(),n=this.#e;if(this.#e="",n.trim()){for(let o=0;o<n.length;){let r=n.slice(o),s=r.length>220?nh(r):r.length;t.push(r.slice(0,s)),o+=s}this.#t=!1}return t}idle(){let t=this.#e;if(!t.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(t))return[];this.#e="",this.#t=!1;let n=[];for(let o=0;o<t.length;){let r=t.slice(o),s=r.length>220?nh(r):r.length;n.push(r.slice(0,s)),o+=s}return n}#n(){let t=[];for(let n=this.#o();n>0;n=this.#o())t.push(this.#e.slice(0,n)),this.#e=this.#e.slice(n),this.#t=!1;return t}#o(){let t=this.#e;if(!t.trim())return 0;let n=SS(t,this.#t).next().value??0;if(n&&n<=220)return n;let o=/[.!?]["'”’)\]*_]*$/.test(t);if(this.#t&&!o){let r=t.match(/\S+\s+/g)?.length??0;if(t.trim().length>=30||r>=6){let s=AS(t,220);if(s)return s}}return t.length>220?nh(t):0}}});function rh(e,t=0){if(e==null||e==="")return"";if(typeof e!="object")return String(e);if(t>2)return"";if(Array.isArray(e))return e.map(s=>rh(s,t+1)).filter(Boolean).join(", ");let n=e,o=n.quantity??n.qty??n.count,r=n.name??n.item??n.product??n.title;return o!=null&&r!=null&&typeof r!="object"?`${o} ${r}`:Object.entries(n).filter(([s])=>!s.startsWith("_")).map(([s,i])=>{let l=rh(i,t+1);return l&&(t?`${Da(s)} ${l}`:`${Da(s)}: ${l}`)}).filter(Boolean).join(t?", ":"; ")}function LS(e){let t=e.length>1?"These actions need the user's approval in the chat before they happen:":"This action needs the user's approval in the chat before it happens:",n=CH-t.length-ES.length-2,o=e.map(r=>{let s=[Da(r.toolName)];r.description&&s.push(`(${oh(r.description.trim(),160)})`);let i=rh(r.parameters);return i&&s.push(`with ${i}`),r.reason&&s.push(`because: ${oh(r.reason.trim(),160)}`),oh(`- ${s.join(" ")}`,Math.floor(n/e.length)-1)});return`${t}
191
+ `)}function pH(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===jI?new Uint8Array(e,44):new Uint8Array(e)}function vS(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 uH(e){return vS(e).replace(/^ws/i,"http")}function fH(e){return typeof e!="number"||!Number.isFinite(e)?XI:Math.min(JI,Math.max(QI,Math.round(e)))}var Jg,$I,UI,zI,qI,jI,KI,GI,YI,XI,QI,JI,ZI,eH,tH,nH,oH,rH,sH,iH,yS,du,aH,lH,cH,bS,Ba,Zg=ie(()=>{"use strict";Qg();wp();Jg=16e3,$I=24e3,UI=4096,zI=Jg*2*8,qI=4,jI=1380533830,KI=3e4,GI=1e3,YI=5e3,XI=3e4,QI=3e4,JI=6e5,ZI="full-duplex-v1",eH=300,tH=2e3,nH=2e3,oH="runtype-browser-v1",rH=54e4,sH="You're talking to an AI assistant. Voice is processed by OpenAI.",iH=new Map([["idle_timeout","Voice call ended after a quiet period."],["max_duration","This voice call reached its time limit."],["provider_ended","The voice session ended."],["quota","Voice is unavailable right now."],["auth_expired","Voice session expired. Tap the mic to reconnect."]]),yS=["provider_error","server_restart"],du="Voice connection lost.",aH=8e3,lH=4e3,cH=12,bS=2e3;Ba=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#t=null;this.#n=[];this.#o=null;this.#a=null;this.#r=null;this.#s=[];this.#g=0;this.#c=null;this.#f=!1;this.#p=!1;this.#l=0;this.#i=!1;this.#T=Number.NEGATIVE_INFINITY;this.#b=null;this.#S=!1;this.#y=!1;this.#d=0;this.#u=0;this.#h=!1;this.bridge=null;this.#A=!1;this.#w=new Set;this.#C=new Map;this.#v=new Set;this.#L=null;this.#x=null;this.#J=!1;this.#G=!1;this.#Y=!1;this.#E=null;this.#$=null;this.#W=Promise.resolve();this.#B=new Set;this.#U=new Set;this.#ee=null;this.#k=!1;this.#z=new Set;this.#q=new Set;this.#j=[];this.#_=[];this.#O=[];this.#re=[];this.#D=[]}#e;#t;#n;#o;#a;#r;#s;#g;#c;#f;#p;#l;#i;#T;#b;#S;#y;#d;#u;#m;#h;#A;#w;#C;#v;#I;#L;#x;#R;#J;#G;#Y;#E;#$;#W;#B;#U;#ee;#k;#z;#q;#j;#_;#O;#re;#D;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#f||this.#b)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.#T<KI)){this.#T=r;try{this.config?.prewarmMode==="attach"?this.#se(o,t,n):this.#ce(o,t,n)}catch{}}}#ce(t,n,o){if(typeof fetch!="function")return;let r=`${uH(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#se(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=fH(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#K(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},d=new Promise(f=>{c=f}),p={ws:l,state:"connecting",ready:d,settle:c,openedAt:0,idleTimer:void 0};this.#b=p,l.onopen=()=>{this.#b===p&&(p.state=l.protocol==="runtype.attach"?"attached":"live",p.openedAt=Date.now(),this.#te(p,i),p.state==="attached"&&l.send('{"type":"ping"}'),p.settle())},l.onmessage=f=>{if(this.#b!==p||typeof f.data!="string")return;let m;try{m=JSON.parse(f.data)}catch{return}m.type==="attached"&&typeof m.idleMs=="number"&&this.#te(p,m.idleMs-(Date.now()-p.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#b===p&&this.#X()}}#te(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#b===t&&this.#X()},Math.max(0,n))}#X(){let t=this.#b;if(!t)return;this.#b=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#de(){let t=this.#b;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,YI)})]),clearTimeout(n)}return this.#b!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#X(),null):(this.#b=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#K(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back","delegation_stream"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:oH,clientVersion:`persona/${br}`,voiceCapabilities:ZI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${vS(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#f)return;let t=this.#G;t||(this.#J=!1,this.#x=null),this.#G=!1;let n=this.config?.agentId,o=this.config?.clientToken,r=this.config?.host;if(!n)throw new Error("Runtype voice requires an agentId");if(!o)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.#l;this.#i=!1,this.#f=!0;try{let i=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Jg,channelCount:1,echoCancellation:!0}});if(s!==this.#l){i.getTracks().forEach(m=>m.stop());return}this.#o=i;let l=window.AudioContext||window.webkitAudioContext,c=new l({sampleRate:Jg});if(this.#t=c,c.state==="suspended"){if(await Promise.race([c.resume().catch(()=>{}),new Promise(m=>setTimeout(m,t?500:GI))]),s!==this.#l)return;if(c.state!=="running")throw t?new Error(this.#x=`${du} Tap the mic to reconnect.`):new Error("Audio blocked until a tap")}let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Wa($I);if(s!==this.#l){d.destroy(),i.getTracks().forEach(m=>m.stop()),c.close().catch(()=>{});return}this.#c=d,this.#oe(),this.#P(c,i,s);let p=await this.#de();if(s!==this.#l){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:m}=p;this.#e=m,this.#N(m,s),p.live||m.send('{"type":"start"}'),this.#V(m),this.#M("listening");return}let f=new WebSocket(this.#K(r,n),["runtype.bearer",o]);f.binaryType="arraybuffer",this.#e=f,f.onopen=()=>{s===this.#l&&(this.#V(f),this.#M("listening"))},this.#N(f,s)}catch(i){throw this.#ae(),this.#ue(i),this.#M("error"),i}}#N(t,n){t.onmessage=o=>this.#ne(o,n),t.onerror=()=>{n!==this.#l||this.#L||(this.#ue(new Error("Voice connection failed")),this.#M("error"),this.#ae())},t.onclose=o=>{if(this.#i){this.#i=!1;return}if(n!==this.#l)return;let r=this.#L??(o.code===4408?{reason:"idle_timeout"}:null);if(!r){if(o.code!==1e3){let s=o.code?` (code ${o.code})`:"";this.#ue(new Error(`Voice connection closed${s}`)),this.#M("error")}else this.#M("idle");this.#ae();return}this.#F(r.reason,r.message)}}#F(t,n){let o=yS.includes(t)&&!this.#J;if(this.#ae(),o){this.#J=!0,this.#f=!0,this.#x=t==="provider_error"?`${du} Reconnecting\u2026`:"Reconnecting\u2026",this.#R=setTimeout(()=>{this.#f=!1,this.#G=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#M("idle");return}if(yS.includes(t))return this.#x=du,this.#ue(new Error(du)),this.#M("error");if(t==="error")return this.#M("error");this.#x=t==="quota"&&n||iH.get(t)||null,this.#M("idle")}takeNotice(){let t=this.#x;return this.#x=null,t}getDisclosure(){let t=this.config?.disclosureText;return this.#f&&this.#S&&t!==!1?t||sH:null}async stopListening(){this.#ae(),this.#M("idle")}async disconnect(){this.#ae(),this.#M("disconnected"),this.#j=[],this.#_=[],this.#O=[],this.#re=[],this.#D=[]}stopPlayback(){this.#ke();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#S&&(this.#d=Date.now()+tH,t.send('{"type":"cancel"}')),this.#M("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#f}onLevel(t){this.#n.push(t)}async deactivateBargeIn(){this.#ae(),this.#M("idle")}#P(t,n,o){let r=t.createMediaStreamSource(n);this.#a=r;let s=t.createScriptProcessor(UI,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#l)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let d=i.inputBuffer.getChannelData(0),p=new Int16Array(d.length),f=0;for(let m=0;m<d.length;m++){let g=Math.max(-1,Math.min(1,d[m]));f+=g*g,p[m]=g<0?g*32768:g*32767}if(l&&c)this.#V(l),l.send(p.buffer);else for(this.#s.push(p.buffer),this.#g+=p.byteLength;this.#g>zI;)this.#g-=this.#s.shift().byteLength;if(this.#n.length>0){let m=Math.sqrt(f/d.length),g=Math.max(0,Math.min(1,m*qI));for(let h of this.#n)h(g)}},r.connect(s),s.connect(t.destination)}#V(t){for(let n of this.#s)t.send(n);this.#s=[],this.#g=0}#ne(t,n){if(n!==this.#l)return;if(t.data instanceof ArrayBuffer){this.#Se(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#S=o.speechMode==="speech_to_speech",this.#c?.setContinuousMode?.(this.#S)),Array.isArray(o.capabilities)&&(this.#w=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#I=o.callId),this.#A=this.#S&&this.#w.has("client_delegation")&&!!this.bridge,this.#S&&!this.#p&&this.#M("listening"),this.#w.has("context")&&!this.#Y&&(this.#Y=!0,this.#E=this.#Ce());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#he())break;let i=String(s);if(r==="user")o.final===!0&&this.#ie(n),this.#k=!1;else{if(this.#w.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#B.has(l)&&!this.#z.has(i)?(this.#q.add(i),this.#k=!1):this.#k&&!this.#z.has(i)&&(this.#q.add(i),this.#k=!1)}else this.#k&&!this.#z.has(i)&&(this.#q.add(i),this.#k=!1);if(this.#z.add(i),this.#q.has(i))break}this.#fe(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#A&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#ie(n);let s=o.input;this.#A&&s&&this.#Ee(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#B.has(r)&&!this.#U.delete(r)&&!this.#w.has("delegation_read_back")&&this.#xe(r);this.#y=o.type==="delegation_started",!this.#p&&!this.#he()&&this.#M(this.#y?"processing":"listening");break}case"delegation_progress":{let r=String(o.delegationId);this.#B.has(r)&&!this.#U.has(r)&&!this.#v.has(r)&&(this.#U.add(r),this.#xe(r));break}case"delegation_cancelled":this.#Te(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#I??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#Te(String(o.delegationId));break;case"audio_clear":this.#ke(),this.#d=0,this.#M("listening");break;case"transcript_interim":this.#M("listening"),this.#fe("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#M(r==="user"?"processing":"speaking"),this.#fe(r,o.text??"",!0);break}case"audio_end":this.#c?this.#c.markStreamEnd():(this.#p=!1,this.#M("listening"));break;case"metrics":this.#pe({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#ue(new Error(o.error||"Voice error")),this.#M("error");break;case"session_end":this.#L={reason:String(o.reason),...typeof o.message=="string"&&{message:o.message}};break}}async#Ce(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return dH(t,n)}#ie(t){let n=this.#E;if(!n)return;this.#E=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#l||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#$={done:r,drop:()=>o=!0}}async#we(){let t=this.#$;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),nH)})]);clearTimeout(n),o&&t.drop()}#xe(t){this.#k=!0,this.#ee=t}#Te(t,n=!1){this.#v.add(t),this.#ee===t&&(this.#k=!1),this.#U.delete(t),this.bridge?.dropDelegation?.(t,n),this.#C.get(t)?.abort()}#Ee(t,n,o){let r=this.bridge,s=({type:l,...c})=>{let d=this.#e;return o!==this.#l||d?.readyState!==WebSocket.OPEN||this.#v.has(t)?!1:(d.send(JSON.stringify({type:l,delegationId:t,...c})),!0)},i=(l,c,d,p=0)=>s({type:l,status:c,text:d,...p>0&&{streamedChars:p}});this.#W=this.#W.then(async()=>{if(o!==this.#l||this.#v.has(t))return;let l=null,c=this.#w.has("delegation_stream")&&this.#w.has("delegation_read_back"),d=C=>{l=(l??this.#we()).then(()=>{s({type:"delegation_delta",text:C})&&this.#B.add(t)})},p=await r.runDelegatedTurn(c?{...n,stream:d}:n).catch(()=>({status:"failed",text:""}));await this.#we(),await l;let f=c?p.streamedChars??0:0,m=!!p.followUp,g=m&&this.#w.has("delegation_update");if(!i(g?"delegation_update":"delegation_result",m&&!g?"completed":p.status,p.text,f)||(p.status!=="failed"&&p.inChat!==!1&&this.#B.add(t),!p.followUp))return;let b=new AbortController;this.#C.set(t,b),p.followUp({signal:b.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,rH),readBack:g,onUpdate:C=>i("delegation_update","pending_approval",C)}).then(C=>{this.#C.delete(t),g&&C&&!b.signal.aborted&&i("delegation_result",C.status,C.text)})})}#Se(t,n){if(n!==this.#l||!this.#c||this.#he())return;let o=pH(t);o.length!==0&&(this.#p||(this.#p=!0,this.#M("speaking")),this.#oe(),this.#c.enqueue(o),this.#S&&this.#Ie(o.length))}#he(){return Date.now()<this.#d}#oe(){if(this.#h||!this.#c)return;this.#h=!0;let t=this.#l;this.#c.onFinished(()=>{t===this.#l&&(this.#h=!1,this.#Ae())})}#Ie(t){let n=Date.now();this.#u=Math.max(n,this.#u)+t/48,clearTimeout(this.#m),this.#m=setTimeout(()=>this.#Ae(),this.#u-n+eH)}#Ae(){this.#p=!1,this.#u=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#M(this.#y?"processing":"listening")}#ke(){this.#c?.flush(),this.#h=!1,this.#oe(),this.#p=!1,this.#u=0,clearTimeout(this.#m)}#ae(){this.#l+=1,this.#f=!1,this.#p=!1,this.#X(),this.#S=!1,this.#y=!1,this.#A=!1,this.#w=new Set;for(let t of this.#C.values())t.abort();if(this.#C.clear(),this.#v.clear(),this.#I=void 0,this.#L=null,clearTimeout(this.#R),this.#Y=!1,this.#E=null,this.#$=null,this.#W=Promise.resolve(),this.#B.clear(),this.#U.clear(),this.#ee=null,this.#k=!1,this.#z.clear(),this.#q.clear(),this.#h=!1,this.#d=0,this.#u=0,clearTimeout(this.#m),this.#s=[],this.#g=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#a&&(this.#a.disconnect(),this.#a=null),this.#o&&(this.#o.getTracks().forEach(t=>t.stop()),this.#o=null),this.#t&&(this.#t.close().catch(()=>{}),this.#t=null),this.#c&&(this.#c.destroy(),this.#c=null),this.#e){this.#i=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#j.push(t)}onError(t){this.#_.push(t)}onStatusChange(t){this.#O.push(t)}onTranscript(t){this.#re.push(t)}onMetrics(t){this.#D.push(t)}#M(t){this.#O.forEach(n=>n(t))}#ue(t){this.#_.forEach(n=>n(t))}#fe(t,n,o,r){this.#re.forEach(s=>s(t,n,o,r))}#pe(t){this.#D.forEach(n=>n(t))}}});var Ds,eh=ie(()=>{"use strict";Ds=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#t=[];this.#n=[];this.#o=[];this.#a=!1;this.#r=typeof window<"u"?window:void 0}#e;#t;#n;#o;#a;#r;async connect(){this.#o.forEach(t=>t("connected"))}async startListening(){try{if(this.#a)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.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.#t.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#n.forEach(o=>o(new Error(n.error))),this.#o.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#a=!0,this.#o.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#a=!1,this.#o.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#n.forEach(n=>n(t)),this.#o.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#a=!1,this.#o.forEach(t=>t("idle"))}onResult(t){this.#t.push(t)}onError(t){this.#n.push(t)}onStatusChange(t){this.#o.push(t)}async disconnect(){await this.stopListening(),this.#o.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ba(e.runtype);case"browser":if(!Ds.isSupported())throw new Error("Browser speech recognition not supported");return new Ds(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 th(e){if(e?.type==="custom"&&e.custom)return nc({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return nc({type:"runtype",runtype:e.runtype});if(Ds.isSupported())return nc({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function CS(e){try{return th(e),!0}catch{return!1}}var wS=ie(()=>{"use strict";Zg();eh()});var xS,pu,SS=ie(()=>{"use strict";xS=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),pu=class{constructor(t){this.host=t;this.turns=new Map;this.latestId=null;this.cancelled=new Set}apply(t,n,o,r,s,i){let l=this.host;n=n.trim();let c=this.turns.get(r);if(c||(c={},this.turns.set(r,c),this.latestId=r),t==="user"){c.userFinal=o;let d=c.userId?l.find(c.userId):void 0;if(d){let p=c.userStartMs===void 0&&s!==void 0;p&&(c.userStartMs=s),l.upsert({...d,content:n,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else{c.userStartMs=s;let p=c.assistantId?l.find(c.assistantId):void 0;c.userId=l.inject({role:"user",content:n,streaming:!1,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s)??p)}).id}}else if(!this.cancelled.has(r)){c.assistantFinal=o;let d=c.assistantId?l.find(c.assistantId):void 0;if(d){let p=c.assistantStartMs===void 0&&s!==void 0;p&&(c.assistantStartMs=s),l.upsert({...d,content:n,streaming:!o,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else n&&(c.assistantStartMs=s,c.assistantId=l.inject({role:"assistant",content:n,streaming:!o,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s))}).id);o&&c.assistantId&&l.markSpoken(c.assistantId)}this.sync()}claimUserTurn(t,n=[]){let o=n[n.length-1];for(let s of n)s!==o&&(this.turns.has(s)||this.turns.set(s,{}),this.turns.get(s).claimed=!0);let r;if(o){if(r=this.turns.get(o),r||(r={},this.turns.set(o,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:"user",content:t.trim()}).id)}else{let s=xS(t),i=[...this.turns.values()].reverse().flatMap(l=>{let c=l.userId&&!l.claimed?this.host.find(l.userId):void 0;return c?[{turn:l,text:xS(c.content)}]:[]}).filter(({text:l})=>l&&s);r=(i.find(({text:l})=>l===s)??i.find(({text:l})=>l.startsWith(s)||s.startsWith(l)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let t=this.inFlight();if(t.length===0){let n=this.awaiting();if(!n)return;t=[n]}for(let n of t)this.cancelled.add(n);this.closeReplies(t),this.sync()}fail(t){let n=this.awaiting(),o=this.inFlight();if(!n&&o.length===0)return;for(let i of o)this.turns.get(i).assistantFinal=!0;this.closeReplies(o);let r=this.host.inject({role:"assistant",content:t,streaming:!1,voiceProcessing:!1}),s=n?this.turns.get(n):void 0;s&&(s.assistantId=r.id,s.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let t=this.pending(),n=new Set;for(let o of this.turns.values())o.userId&&n.add(o.userId),o.assistantId&&(n.add(o.assistantId),this.host.markSpoken(o.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(n),t&&this.host.setStreaming(!1)}startedAfter(t){if(t===void 0)return;let n;for(let o of this.turns.values())for(let[r,s]of[[o.userId,o.userStartMs],[o.assistantId,o.assistantStartMs]])r&&s!==void 0&&s>t&&(!n||s<n.start)&&(n={start:s,id:r});return n&&this.host.find(n.id)}placeBefore(t){if(!t)return;let n=t.sequence??0,o=n-1;for(let r of this.turns.values())for(let s of[r.userId,r.assistantId]){let i=s?this.host.find(s):void 0,l=i?.sequence;i?.createdAt===t.createdAt&&l!==void 0&&l>o&&l<n&&(o=l)}return{createdAt:t.createdAt,sequence:(o+n)/2}}closeReplies(t){let n=new Set;for(let o of t){let r=this.turns.get(o)?.assistantId;r&&(n.add(r),this.host.markSpoken(r))}n.size>0&&this.host.settle(n)}inFlight(){let t=[];for(let[n,o]of this.turns)o.assistantId&&!o.assistantFinal&&!this.cancelled.has(n)&&t.push(n);return t}awaiting(){let t=this.latestId;if(!t)return null;let n=this.turns.get(t);return n?.userFinal&&!n.assistantId&&!n.claimed&&!this.cancelled.has(t)?t:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}});function hH(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,"").toLowerCase();if(mH.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let o=e.length-t.length;return o===0||/\n\s*$/.test(e.slice(0,o))}return!1}function*AS(e,t){let n=new RegExp(gH.source,"g");for(let o=n.exec(e);o;o=n.exec(e)){let r=o[1];if(!e.slice(0,o.index+(r?.length??0)).trim()||r!==void 0&&(/^[,;:]$/.test(r)&&!t||r==="."&&hH(e.slice(0,o.index))))continue;let s=o.index+o[0].length;s<e.length&&(yield s)}}function MS(e,t){let n=e.slice(0,t),o=0;for(let r of n.matchAll(/\s+/g))n.slice(0,r.index).trim()&&(o=r.index+r[0].length);return o}function nh(e){let t=0;for(let r of AS(e.slice(0,220),!0))t=r;if(t)return t;let n=MS(e,220);if(n)return n;let o=e.charCodeAt(219);return o>=55296&&o<=56319?219:220}var mH,gH,uu,TS=ie(()=>{"use strict";mH=new Set(["mr","mrs","ms","dr","prof","sr","jr","st","mt","vs","etc","approx","inc","ltd","co","corp","no","nos","fig","ft","dept","est","min","max","e.g","i.e","a.m","p.m","u.s","u.k"]),gH=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;uu=class{#e="";#t=!0;push(t){return this.#e+=t,this.#n()}flush(){let t=this.#n(),n=this.#e;if(this.#e="",n.trim()){for(let o=0;o<n.length;){let r=n.slice(o),s=r.length>220?nh(r):r.length;t.push(r.slice(0,s)),o+=s}this.#t=!1}return t}idle(){let t=this.#e;if(!t.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(t))return[];this.#e="",this.#t=!1;let n=[];for(let o=0;o<t.length;){let r=t.slice(o),s=r.length>220?nh(r):r.length;n.push(r.slice(0,s)),o+=s}return n}#n(){let t=[];for(let n=this.#o();n>0;n=this.#o())t.push(this.#e.slice(0,n)),this.#e=this.#e.slice(n),this.#t=!1;return t}#o(){let t=this.#e;if(!t.trim())return 0;let n=AS(t,this.#t).next().value??0;if(n&&n<=220)return n;let o=/[.!?]["'”’)\]*_]*$/.test(t);if(this.#t&&!o){let r=t.match(/\S+\s+/g)?.length??0;if(t.trim().length>=30||r>=6){let s=MS(t,220);if(s)return s}}return t.length>220?nh(t):0}}});function rh(e,t=0){if(e==null||e==="")return"";if(typeof e!="object")return String(e);if(t>2)return"";if(Array.isArray(e))return e.map(s=>rh(s,t+1)).filter(Boolean).join(", ");let n=e,o=n.quantity??n.qty??n.count,r=n.name??n.item??n.product??n.title;return o!=null&&r!=null&&typeof r!="object"?`${o} ${r}`:Object.entries(n).filter(([s])=>!s.startsWith("_")).map(([s,i])=>{let l=rh(i,t+1);return l&&(t?`${Da(s)} ${l}`:`${Da(s)}: ${l}`)}).filter(Boolean).join(t?", ":"; ")}function PS(e){let t=e.length>1?"These actions need the user's approval in the chat before they happen:":"This action needs the user's approval in the chat before it happens:",n=wH-t.length-kS.length-2,o=e.map(r=>{let s=[Da(r.toolName)];r.description&&s.push(`(${oh(r.description.trim(),160)})`);let i=rh(r.parameters);return i&&s.push(`with ${i}`),r.reason&&s.push(`because: ${oh(r.reason.trim(),160)}`),oh(`- ${s.join(" ")}`,Math.floor(n/e.length)-1)});return`${t}
192
192
  ${o.join(`
193
193
  `)}
194
194
 
195
- ${ES}`}function PS(e){let t=null,n=null,o=()=>e.track(t??n),r=[],s=new Map,i=new Map,l=(h,b)=>{s.set(h,[...s.get(h)??[],b]),s.size>32&&s.delete(s.keys().next().value)},c=h=>e.messages().find(b=>b.id===h),d=h=>h.approvals.filter(b=>c(b)?.approval?.status==="pending"),p=h=>Da(c(h)?.approval?.toolName??""),f=(h,b,C)=>{h.outcome={status:b,text:C};for(let A of d(h))e.decide(A)},m=h=>h.flatMap(b=>e.messages().find(C=>C.id===b)??[]).filter(b=>!b.variant&&b.content.trim()).map(b=>b.content.trim()).join(`
195
+ ${kS}`}function IS(e){let t=null,n=null,o=()=>e.track(t??n),r=[],s=new Map,i=new Map,l=(h,b)=>{s.set(h,[...s.get(h)??[],b]),s.size>32&&s.delete(s.keys().next().value)},c=h=>e.messages().find(b=>b.id===h),d=h=>h.approvals.filter(b=>c(b)?.approval?.status==="pending"),p=h=>Da(c(h)?.approval?.toolName??""),f=(h,b,C)=>{h.outcome={status:b,text:C};for(let A of d(h))e.decide(A)},m=h=>h.flatMap(b=>e.messages().find(C=>C.id===b)??[]).filter(b=>!b.variant&&b.content.trim()).map(b=>b.content.trim()).join(`
196
196
 
197
- `),g=async h=>{do await kS();while(e.busy()&&!(h&&(e.parked()||h.failed)))};return{getHistory:()=>{let h=e.messages().filter(A=>(A.role==="user"||A.role==="assistant")&&!A.variant&&!A.voiceProcessing&&!A.streaming&&A.content),b=!1,C=[];for(let A=h.length-1;A>=0;A-=1){let S=h[A];if(S.role==="user")b=!1;else if(!S.voiceCaption)b=!0;else if(b)continue;C.unshift({role:S.role,content:S.content})}return C},dropDelegation(h,b){i.set(h,!!b),i.size>32&&i.delete(i.keys().next().value);let C=b&&r.find(A=>A.delegationId===h);C&&!C.outcome&&f(C,"timeout","");for(let A of s.get(h)??[])A.stopStream?.(),A.dropped=!0,A.ids.length&&e.unspoken(A.ids)},async runDelegatedTurn({delegationId:h,userText:b,userUtteranceIds:C,stream:A}){let S=r.filter(K=>d(K).length),E=S.flatMap(d);if(E.length===1&&SH(b)){let K=p(E[0]);return f(S[0],"denied",""),{status:"denied",text:`Okay, I cancelled the ${K} request. Nothing was done.`,inChat:!1}}let k=e.parked()&&e.messages().every(K=>!fu(K)||E.includes(K.id));e.busy()&&!k&&await g();let D=new Set(e.messages().map(K=>K.id)),z=()=>e.messages().filter(K=>!D.has(K.id)&&K.variant==="approval"),Y={ids:[],failed:!1},T=A?new uu:null,W="",L="",w=!1,x=K=>{for(let X of K)L+=X,A(X)},P;T&&(Y.onUpdate=()=>{if(w)return;let K=m(Y.ids);if(!K.startsWith(W)){w=!0,clearTimeout(P);return}if(K.length===W.length)return;let X=K.slice(W.length);W=K,x(T.push(X)),clearTimeout(P),P=setTimeout(()=>{w||x(T.idle())},hH)},Y.stopStream=()=>{clearTimeout(P),w=!0,Y.onUpdate=void 0}),l(h,Y),t=Y,o();try{await e.send(b,e.claim(b,C)??void 0),await g(Y)}catch{Y.failed=!0}finally{t=null,o()}T&&(Y.onUpdate?.(),clearTimeout(P),w||x(T.flush()),Y.onUpdate=void 0,Y.stopStream=void 0);let I=K=>{let X=yH(L,K);return X>0?{streamedChars:X}:{}},J=Y.ids.flatMap(K=>e.messages().find(X=>X.id===K)??[]),_=m(Y.ids),j=Y.failed?[]:z().filter(fu),te=new Set(j.map(K=>Da(K.approval.toolName)));for(let K of S){if(K.outcome)continue;for(let oe of d(K).filter(de=>te.has(p(de))))K.replaced.add(oe),e.decide(oe);let X=p(K.approvals[0]);K.approvals.every(oe=>K.replaced.has(oe))?K.outcome={status:"cancelled",text:`The earlier ${X} request was replaced by the new one; it was not done.`}:k&&K.approvals.every(oe=>c(oe)?.approval?.status==="denied")&&(K.outcome={status:"cancelled",text:`The earlier ${X} request was replaced by the new one; it was not done.`})}if(j.length){let K=new Set(j.map(oe=>oe.id)),X={delegationId:h,approvals:[...K],at:Date.now(),replaced:new Set};return r.push(X),i.get(h)&&f(X,"timeout",""),_=`${_}
197
+ `),g=async h=>{do await LS();while(e.busy()&&!(h&&(e.parked()||h.failed)))};return{getHistory:()=>{let h=e.messages().filter(A=>(A.role==="user"||A.role==="assistant")&&!A.variant&&!A.voiceProcessing&&!A.streaming&&A.content),b=!1,C=[];for(let A=h.length-1;A>=0;A-=1){let S=h[A];if(S.role==="user")b=!1;else if(!S.voiceCaption)b=!0;else if(b)continue;C.unshift({role:S.role,content:S.content})}return C},dropDelegation(h,b){i.set(h,!!b),i.size>32&&i.delete(i.keys().next().value);let C=b&&r.find(A=>A.delegationId===h);C&&!C.outcome&&f(C,"timeout","");for(let A of s.get(h)??[])A.stopStream?.(),A.dropped=!0,A.ids.length&&e.unspoken(A.ids)},async runDelegatedTurn({delegationId:h,userText:b,userUtteranceIds:C,stream:A}){let S=r.filter(K=>d(K).length),E=S.flatMap(d);if(E.length===1&&AH(b)){let K=p(E[0]);return f(S[0],"denied",""),{status:"denied",text:`Okay, I cancelled the ${K} request. Nothing was done.`,inChat:!1}}let k=e.parked()&&e.messages().every(K=>!fu(K)||E.includes(K.id));e.busy()&&!k&&await g();let D=new Set(e.messages().map(K=>K.id)),z=()=>e.messages().filter(K=>!D.has(K.id)&&K.variant==="approval"),Y={ids:[],failed:!1},T=A?new uu:null,W="",L="",w=!1,x=K=>{for(let X of K)L+=X,A(X)},P;T&&(Y.onUpdate=()=>{if(w)return;let K=m(Y.ids);if(!K.startsWith(W)){w=!0,clearTimeout(P);return}if(K.length===W.length)return;let X=K.slice(W.length);W=K,x(T.push(X)),clearTimeout(P),P=setTimeout(()=>{w||x(T.idle())},yH)},Y.stopStream=()=>{clearTimeout(P),w=!0,Y.onUpdate=void 0}),l(h,Y),t=Y,o();try{await e.send(b,e.claim(b,C)??void 0),await g(Y)}catch{Y.failed=!0}finally{t=null,o()}T&&(Y.onUpdate?.(),clearTimeout(P),w||x(T.flush()),Y.onUpdate=void 0,Y.stopStream=void 0);let I=K=>{let X=bH(L,K);return X>0?{streamedChars:X}:{}},J=Y.ids.flatMap(K=>e.messages().find(X=>X.id===K)??[]),_=m(Y.ids),j=Y.failed?[]:z().filter(fu),te=new Set(j.map(K=>Da(K.approval.toolName)));for(let K of S){if(K.outcome)continue;for(let oe of d(K).filter(de=>te.has(p(de))))K.replaced.add(oe),e.decide(oe);let X=p(K.approvals[0]);K.approvals.every(oe=>K.replaced.has(oe))?K.outcome={status:"cancelled",text:`The earlier ${X} request was replaced by the new one; it was not done.`}:k&&K.approvals.every(oe=>c(oe)?.approval?.status==="denied")&&(K.outcome={status:"cancelled",text:`The earlier ${X} request was replaced by the new one; it was not done.`})}if(j.length){let K=new Set(j.map(oe=>oe.id)),X={delegationId:h,approvals:[...K],at:Date.now(),replaced:new Set};return r.push(X),i.get(h)&&f(X,"timeout",""),_=`${_}
198
198
 
199
- ${LS(j.map(oe=>oe.approval))}`.trim(),{status:"pending_approval",text:_,...I(_),followUp:async({signal:oe,approvalTimeoutMs:de=wH,readBack:xe=!0,onUpdate:Te})=>{let re={ids:[],failed:!1};s.delete(h),l(h,re);let N=()=>z().filter(Se=>K.has(Se.id)||re.ids.includes(Se.id)),ke=()=>z().filter(Se=>fu(Se)&&!K.has(Se.id)&&!r.some(U=>U.approvals.includes(Se.id))&&(re.ids.includes(Se.id)||Se.approval?.toolType==="webmcp"&&n===re)),ve=()=>{n=re,o()};xe&&ve();try{for(;!oe.aborted&&!X.outcome&&(t||e.busy()||N().some(fu));){xe&&n!==re&&!d(X).length&&ve();let Se=ke();if(Se.length){for(let U of Se)K.add(U.id),X.approvals.push(U.id);X.at=Date.now(),Te?.(LS(Se.map(U=>U.approval)))}if(Date.now()-X.at>=de&&d(X).length&&(!e.busy()||e.parked())){f(X,"timeout",`That ${p(X.approvals[0])} request expired, so nothing was done.`);break}await kS()}}finally{n===re&&(n=null,o()),r.splice(r.indexOf(X),1)}if(oe.aborted)return null;if(X.outcome)return X.outcome;if(re.failed)return{status:"failed",text:`The ${p(X.approvals[0])} request didn't complete.`};let tt=N(),xt=Se=>tt.filter(Se).map(U=>Da(U.approval.toolName)).join(", "),ht=tt.some(Se=>Se.approval?.status==="approved"),lt=xt(Se=>Se.approval?.status==="denied"&&!X.replaced.has(Se.id)),Ye=xt(Se=>X.replaced.has(Se.id)),dt=xt(Se=>Se.approval?.status==="timeout"),Pe=[ht?m(re.ids):"",lt&&`The user declined the ${lt} request in the chat, so ${ht?"that part was not done":"nothing was done"}.`,Ye&&`The earlier ${Ye} request was replaced by the new one; it was not done.`,dt&&`The ${dt} request timed out, so it was not done.`].filter(Boolean).join(`
199
+ ${PS(j.map(oe=>oe.approval))}`.trim(),{status:"pending_approval",text:_,...I(_),followUp:async({signal:oe,approvalTimeoutMs:de=xH,readBack:xe=!0,onUpdate:Te})=>{let re={ids:[],failed:!1};s.delete(h),l(h,re);let N=()=>z().filter(Se=>K.has(Se.id)||re.ids.includes(Se.id)),ke=()=>z().filter(Se=>fu(Se)&&!K.has(Se.id)&&!r.some(U=>U.approvals.includes(Se.id))&&(re.ids.includes(Se.id)||Se.approval?.toolType==="webmcp"&&n===re)),ve=()=>{n=re,o()};xe&&ve();try{for(;!oe.aborted&&!X.outcome&&(t||e.busy()||N().some(fu));){xe&&n!==re&&!d(X).length&&ve();let Se=ke();if(Se.length){for(let U of Se)K.add(U.id),X.approvals.push(U.id);X.at=Date.now(),Te?.(PS(Se.map(U=>U.approval)))}if(Date.now()-X.at>=de&&d(X).length&&(!e.busy()||e.parked())){f(X,"timeout",`That ${p(X.approvals[0])} request expired, so nothing was done.`);break}await LS()}}finally{n===re&&(n=null,o()),r.splice(r.indexOf(X),1)}if(oe.aborted)return null;if(X.outcome)return X.outcome;if(re.failed)return{status:"failed",text:`The ${p(X.approvals[0])} request didn't complete.`};let tt=N(),xt=Se=>tt.filter(Se).map(U=>Da(U.approval.toolName)).join(", "),ht=tt.some(Se=>Se.approval?.status==="approved"),lt=xt(Se=>Se.approval?.status==="denied"&&!X.replaced.has(Se.id)),Ye=xt(Se=>X.replaced.has(Se.id)),dt=xt(Se=>Se.approval?.status==="timeout"),Pe=[ht?m(re.ids):"",lt&&`The user declined the ${lt} request in the chat, so ${ht?"that part was not done":"nothing was done"}.`,Ye&&`The earlier ${Ye} request was replaced by the new one; it was not done.`,dt&&`The ${dt} request timed out, so it was not done.`].filter(Boolean).join(`
200
200
 
201
201
  `);return{status:ht?"completed":lt?"denied":Ye?"cancelled":dt?"timeout":"completed",text:Pe}}}}return!Y.failed&&e.parked()||J.some(K=>K.agentMetadata?.awaitingLocalTool&&!K.agentMetadata.askUserQuestionAnswered&&!K.toolCall?.name?.startsWith("webmcp:"))?(_=`${_}
202
202
 
203
- ${vH}`.trim(),{status:Y.failed?"failed":"completed",text:_,...I(_)}):{status:!Y.failed&&_?"completed":"failed",text:_,...I(_)}}}}var hH,yH,bH,vH,CH,wH,TS,xH,SH,ES,kS,oh,Da,fu,IS=ie(()=>{"use strict";MS();hH=200,yH=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},bH=50,vH="I need your answer in the chat before I can continue.",CH=1e3,wH=5*6e4,TS="no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)",xH=new RegExp(`^(?:${TS})(?: (?:${TS}))?(?: thanks| thank you)?$`),SH=e=>xH.test(e.toLowerCase().replace(/[^a-z' ]+/g," ").replace(/\s+/g," ").trim()),ES="Briefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.",kS=()=>new Promise(e=>setTimeout(e,bH)),oh=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e,Da=e=>e.replace(/^webmcp:/,"").replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().toLowerCase();fu=e=>e.variant==="approval"&&e.approval?.status==="pending"});var HS,RS=ie(()=>{"use strict";HS=(e,t,n,o)=>{let r=e.session;try{e.keyed=n?new n({find:d=>r.messages.find(p=>p.id===d),inject:d=>r.injectMessage(d),upsert:d=>r.upsertMessage(d),settle:d=>{r.messages=r.messages.map(p=>d.has(p.id)?{...p,streaming:!1,voiceProcessing:!1}:p),r.callbacks.onMessagesChanged([...r.messages])},setStreaming:d=>{(d||!e.busy())&&e.setStreaming(d)},markSpoken:d=>{r.ttsSpokenMessageIds.add(d)}}):null,o&&t.setSessionBridge&&t.setSessionBridge(o({messages:()=>r.messages,busy:()=>e.busy(),parked:()=>r.webMcpApprovalResolvers.size>0,claim:(d,p)=>e.keyed?.claimUserTurn(d,p)??null,send:(d,p)=>r.sendMessage(d,{viaVoice:!0,voiceTurn:{userMessageId:p}}),track:d=>{e.setDelegation(d)},unspoken:d=>{for(let p of d)r.ttsSpokenMessageIds.delete(p);r.streaming||r.speakLatestAssistantMessage(d)},decide:d=>{if(r.webMcpApprovalResolvers.has(d))return r.resolveWebMcpApproval(d,"denied");let p=r.messages.find(f=>f.id===d)?.approval;p?.status==="pending"&&r.resolveApproval(p,"denied")}}));let s=e.generation(),i=()=>e.provider()===t&&s===e.generation(),c=(r.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";t.onResult(d=>{i()&&d.provider!=="runtype"&&d.text&&d.text.trim()&&r.sendMessage(d.text,{viaVoice:!0})}),t.onTranscript&&t.onTranscript((d,p,f,m)=>{if(i()){if(m?.turnId){e.keyed?.apply(d,p,f,m.turnId,m.startMs,m.caption);return}if(d==="user"){if(e.pendingUser)r.upsertMessage({id:e.pendingUser,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!f});else{let g=r.injectMessage({role:"user",content:p,streaming:!1,voiceProcessing:!f});e.pendingUser=g.id}if(f){e.turns().start(m?.turnId),e.pendingUser=null;let g=r.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});e.pendingAssistant=g.id,e.setStreaming(!0)}}else{if(!e.turns().accepts(m?.turnId))return;if(e.pendingAssistant)r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!f,voiceProcessing:!f});else{let g=r.injectMessage({role:"assistant",content:p,streaming:!f,voiceProcessing:!f});e.pendingAssistant=g.id}f&&(e.pendingAssistant&&r.ttsSpokenMessageIds.add(e.pendingAssistant),e.setStreaming(!1),e.pendingAssistant=null)}}}),t.onLevel&&t.onLevel(d=>{i()&&e.setLevel(Number.isFinite(d)?Math.max(0,Math.min(1,d)):0)}),t.onMetrics&&t.onMetrics(d=>{i()&&r.config.voiceRecognition?.onMetrics?.(d)}),t.onError(d=>{i()&&(console.error("Voice error:",d),e.pendingAssistant&&(r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),e.setStreaming(!1),e.pendingUser=null,e.pendingAssistant=null),e.keyed?.fail(c))}),t.onStatusChange(d=>{i()&&(e.setStatus(d),(d==="listening"||d==="idle"||d==="disconnected")&&e.settlePending(d!=="listening"),(d==="idle"||d==="disconnected")&&e.keyed?.settle(),r.callbacks.onVoiceStatusChanged?.(d))}),t.connect()}catch(s){console.error("Failed to setup voice:",s)}}});var WS,BS=ie(()=>{"use strict";WS=e=>{let t=c=>{if(e.original)return;let d=e.config().voiceRecognition??{};e.original={backgroundColor:c.style.backgroundColor,color:c.style.color,borderColor:c.style.borderColor,iconName:d.iconName??"mic",iconSize:parseFloat(d.iconSize??"")||e.iconFallbackPx}},n=(c,d,p)=>{let f=c.querySelector("svg");f&&f.remove();let m=e.original?.iconSize??(parseFloat(e.config().voiceRecognition?.iconSize??"")||e.iconFallbackPx),g=e.renderIcon(d,m,p,1.5);g&&c.appendChild(g)},o=c=>{c.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")};return{recording:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=d.recordingBackgroundColor,f=d.recordingIconColor,m=d.recordingBorderColor;if(o(c),c.classList.add("persona-voice-recording"),e.setMicState("recording"),c.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",c.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let g=c.querySelector("svg");g&&g.setAttribute("stroke",f)}m&&(c.style.borderColor=m),c.setAttribute("aria-label","Stop voice recognition")},processing:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=d.processingIconName??"loader",g=d.processingIconColor??f?.color??"",h=d.processingBackgroundColor??f?.backgroundColor??"",b=d.processingBorderColor??f?.borderColor??"";o(c),c.classList.add("persona-voice-processing"),e.setMicState("processing"),c.style.backgroundColor=h,c.style.borderColor=b;let C=g||"currentColor";c.style.color=C,n(c,m,C),c.setAttribute("aria-label","Processing voice input"),p==="none"&&(c.style.cursor="default")},speaking:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",g=d.speakingIconName??m,h=d.speakingIconColor??(p==="barge-in"?d.recordingIconColor??f?.color??"":f?.color??""),b=d.speakingBackgroundColor??(p==="barge-in"?d.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":f?.backgroundColor??""),C=d.speakingBorderColor??(p==="barge-in"?d.recordingBorderColor??"":f?.borderColor??"");o(c),c.classList.add("persona-voice-speaking"),e.setMicState("speaking"),c.style.backgroundColor=b,c.style.borderColor=C;let A=h||"currentColor";c.style.color=A,n(c,g,A);let S=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";c.setAttribute("aria-label",S),p==="none"&&(c.style.cursor="default"),p==="barge-in"&&c.classList.add("persona-voice-recording")},reset:()=>{let c=e.mic();if(!c)return;o(c),e.setMicState("idle");let d=e.original;d&&(c.style.backgroundColor=d.backgroundColor??"",c.style.color=d.color??"",c.style.borderColor=d.borderColor??"",n(c,d.iconName,d.color||"currentColor"),e.original=null),c.style.cursor="",c.setAttribute("aria-label","Start voice recognition")}}}});var DS={};En(DS,{BrowserVoiceProvider:()=>Ds,KeyedVoiceTranscript:()=>pu,RuntypeVoiceProvider:()=>Ba,createBestAvailableVoiceProvider:()=>th,createMicStateStyles:()=>WS,createVoiceProvider:()=>nc,createVoiceSessionBridge:()=>PS,isVoiceSupported:()=>vS,wireSessionVoice:()=>HS});var _S=ie(()=>{"use strict";CS();Zg();eh();xS();IS();RS();BS()});function EH(e){return e.replace(/\/+$/,"")}async function kH(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 mu,FS=ie(()=>{"use strict";Qg();mu=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#t=null;this.#n=0;this.#o=t}#e;#t;#n;#o;#a(){return this.#t??=Promise.resolve(this.#o.createPlaybackEngine?this.#o.createPlaybackEngine():new Wa(24e3,{prebufferMs:this.#o.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#n;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#a();if(t!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#n&&o.onStart?.()}),r.onFinished(()=>{t===this.#n&&o.onEnd?.()});let s=`${EH(this.#o.host)}/v1/agents/${encodeURIComponent(this.#o.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#o.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#o.voice,format:"pcm"})});if(t!==this.#n)return;if(!i.ok||!i.body)throw new Error(await kH(i));let l=i.body.getReader();for(;;){let{done:c,value:d}=await l.read();if(t!==this.#n){await l.cancel().catch(()=>{});return}if(c)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.#n)return;let s=r instanceof Error?r:new Error(String(r));this.#o.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}});var gu,VS=ie(()=>{"use strict";gu=class{constructor(t,n,o={}){this.id="fallback";this.#t=t,this.#n=n,this.#o=o,this.#e=t}#e;#t;#n;#o;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#t;let o=!1;this.#t.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#o.onFallback?.(r),this.#e=this.#n,this.#n.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}});var $S={};En($S,{FallbackSpeechEngine:()=>gu,RuntypeSpeechEngine:()=>mu});var US=ie(()=>{"use strict";FS();VS()});var qS={};En(qS,{createReconnectController:()=>PH});function PH(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},i=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},c=()=>{i()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},f=h=>new Promise(b=>{n=b,o=setTimeout(()=>{o=null,n=null,b()},h)}),m=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let b=!1;for(let A of e.getMessages())A.streaming&&(A.streaming=!1,b=!0);let C=e.buildErrorContent("Connection lost and the response could not be resumed.");C?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):b&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let h=e.config.reconnect?.backoffMs??LH,b=e.config.reconnect?.maxAttempts??h.length,C=e.config.reconnectStream;if(!C){e.setReconnecting(!1);return}for(;e.getResumable()&&t<b;){t+=1,e.setStatus("resuming");let A=e.getResumable(),S=A.lastEventId,E=new AbortController;e.setAbortController(E),e.emitReconnect({phase:"resuming",handle:A,attempt:t});let k=null;try{let D=await C({executionId:A.executionId,after:A.lastEventId,signal:E.signal});D&&D.ok&&D.body&&(k=D.body)}catch{k=null}if(E.signal.aborted)return;if(k){let D=e.getMessages().find(Y=>Y.id===A.assistantMessageId)?.content,z=typeof D=="string"?D:"";try{await e.resumeConnect(k,A.assistantMessageId,z)}catch{}if(E.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:A});return}e.getResumable().lastEventId!==S&&(t=0)}if(e.getResumable()&&t<b&&(e.setStatus("paused"),await f(h[Math.min(t-1,h.length-1)]??1e3),E.signal.aborted))return}e.getResumable()&&m()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var LH,jS=ie(()=>{"use strict";LH=[1e3,2e3,4e3,8e3,8e3]});var DA,Ch,IR,Eu,ku,HR,_A,Lu,dc,RR,WR,OA,Pu=ie(()=>{"use strict";DA=null,Ch=()=>{if(DA!==null)return DA;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},IR="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Eu=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},ku=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 Eu("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Eu("unsupported",e),null):(n==="space"&&(o.key=" "),o)},HR=e=>IR.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),_A=(e,t)=>{let n=ku(e);if(!n)return"";let o=Ch(),r=HR(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("+")},Lu=e=>_A(e,!1),dc=e=>_A(e,!0),RR=(e,t)=>t.key?.toLowerCase()===e.key&&(Ch()?t.metaKey:t.ctrlKey)===e.mod&&!(Ch()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,WR=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},OA=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(RR(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&WR(i))){s.preventDefault();try{l.run(s)}catch(c){Eu(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=ku(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Eu(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",dc(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function KA(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 Hu(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Zr(e,t){return xr(e)-e.scrollTop<=t}function Ru(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Wu(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 GA(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function xh(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 YA(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Sh=ie(()=>{"use strict"});var pc,BR,Bu,DR,Th,QA,Pi,uc,Du,_R,OR,Ah,NR,FR,VR,fc,_u,mc,XA,$R,Mh,UR,JA,gc,hc=ie(()=>{"use strict";pc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},BR=["pre","code","a","script","style"],Bu=e=>({type:e?.type??pc.type,placeholder:e?.placeholder??pc.placeholder,speed:e?.speed??pc.speed,duration:e?.duration??pc.duration,buffer:e?.buffer??pc.buffer}),DR=[{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"}],Th=new Map;for(let e of DR)Th.set(e.name,e);QA=["wipe","glyph-cycle"],Pi=e=>{Th.set(e.name,e)},uc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Th.get(e)??null,Du=(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(`
204
- `);return s<0?"":e.slice(0,s)}return e},_R=(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},OR=(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},Ah=/\s/,NR=(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},FR=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Ah.test(s[l])){let c=l;for(;c<s.length&&Ah.test(s[c]);)c+=1;i.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let d=l;for(;d<s.length&&!Ah.test(s[d]);)c.appendChild(_R(o,s[d],t,n.value)),n.value+=1,d+=1;i.appendChild(c),l=d}r.replaceChild(i,e)},VR=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(OR(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},fc=(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??BR).map(f=>f.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)NR(c,s)||l.push(c),c=i.nextNode();let d={value:o?.startIndex??0},p=t==="char"?FR:VR;for(let f of l)p(f,n,d);return r.innerHTML},_u=(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},mc=(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},XA=new WeakMap,$R=(e,t)=>{if(!e.styles)return;let n=XA.get(t);if(n||(n=new Set,XA.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)},Mh=new WeakMap,UR=(e,t)=>{if(!e.onAttach)return;let n=Mh.get(t);if(n||(n=new Map,Mh.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},JA=e=>{let t=Mh.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},gc=(e,t)=>{$R(e,t),UR(e,t)}});var zR,ZA,eM,tM=ie(()=>{"use strict";hc();zR=`
203
+ ${CH}`.trim(),{status:Y.failed?"failed":"completed",text:_,...I(_)}):{status:!Y.failed&&_?"completed":"failed",text:_,...I(_)}}}}var yH,bH,vH,CH,wH,xH,ES,SH,AH,kS,LS,oh,Da,fu,HS=ie(()=>{"use strict";TS();yH=200,bH=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},vH=50,CH="I need your answer in the chat before I can continue.",wH=1e3,xH=5*6e4,ES="no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)",SH=new RegExp(`^(?:${ES})(?: (?:${ES}))?(?: thanks| thank you)?$`),AH=e=>SH.test(e.toLowerCase().replace(/[^a-z' ]+/g," ").replace(/\s+/g," ").trim()),kS="Briefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.",LS=()=>new Promise(e=>setTimeout(e,vH)),oh=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e,Da=e=>e.replace(/^webmcp:/,"").replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().toLowerCase();fu=e=>e.variant==="approval"&&e.approval?.status==="pending"});var RS,WS=ie(()=>{"use strict";RS=(e,t,n,o)=>{let r=e.session;try{e.keyed=n?new n({find:d=>r.messages.find(p=>p.id===d),inject:d=>r.injectMessage(d),upsert:d=>r.upsertMessage(d),settle:d=>{r.messages=r.messages.map(p=>d.has(p.id)?{...p,streaming:!1,voiceProcessing:!1}:p),r.callbacks.onMessagesChanged([...r.messages])},setStreaming:d=>{(d||!e.busy())&&e.setStreaming(d)},markSpoken:d=>{r.ttsSpokenMessageIds.add(d)}}):null,o&&t.setSessionBridge&&t.setSessionBridge(o({messages:()=>r.messages,busy:()=>e.busy(),parked:()=>r.webMcpApprovalResolvers.size>0,claim:(d,p)=>e.keyed?.claimUserTurn(d,p)??null,send:(d,p)=>r.sendMessage(d,{viaVoice:!0,voiceTurn:{userMessageId:p}}),track:d=>{e.setDelegation(d)},unspoken:d=>{for(let p of d)r.ttsSpokenMessageIds.delete(p);r.streaming||r.speakLatestAssistantMessage(d)},decide:d=>{if(r.webMcpApprovalResolvers.has(d))return r.resolveWebMcpApproval(d,"denied");let p=r.messages.find(f=>f.id===d)?.approval;p?.status==="pending"&&r.resolveApproval(p,"denied")}}));let s=e.generation(),i=()=>e.provider()===t&&s===e.generation(),c=(r.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";t.onResult(d=>{i()&&d.provider!=="runtype"&&d.text&&d.text.trim()&&r.sendMessage(d.text,{viaVoice:!0})}),t.onTranscript&&t.onTranscript((d,p,f,m)=>{if(i()){if(m?.turnId){e.keyed?.apply(d,p,f,m.turnId,m.startMs,m.caption);return}if(d==="user"){if(e.pendingUser)r.upsertMessage({id:e.pendingUser,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!f});else{let g=r.injectMessage({role:"user",content:p,streaming:!1,voiceProcessing:!f});e.pendingUser=g.id}if(f){e.turns().start(m?.turnId),e.pendingUser=null;let g=r.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});e.pendingAssistant=g.id,e.setStreaming(!0)}}else{if(!e.turns().accepts(m?.turnId))return;if(e.pendingAssistant)r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!f,voiceProcessing:!f});else{let g=r.injectMessage({role:"assistant",content:p,streaming:!f,voiceProcessing:!f});e.pendingAssistant=g.id}f&&(e.pendingAssistant&&r.ttsSpokenMessageIds.add(e.pendingAssistant),e.setStreaming(!1),e.pendingAssistant=null)}}}),t.onLevel&&t.onLevel(d=>{i()&&e.setLevel(Number.isFinite(d)?Math.max(0,Math.min(1,d)):0)}),t.onMetrics&&t.onMetrics(d=>{i()&&r.config.voiceRecognition?.onMetrics?.(d)}),t.onError(d=>{i()&&(console.error("Voice error:",d),e.pendingAssistant&&(r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),e.setStreaming(!1),e.pendingUser=null,e.pendingAssistant=null),e.keyed?.fail(c))}),t.onStatusChange(d=>{i()&&(e.setStatus(d),(d==="listening"||d==="idle"||d==="disconnected")&&e.settlePending(d!=="listening"),(d==="idle"||d==="disconnected")&&e.keyed?.settle(),r.callbacks.onVoiceStatusChanged?.(d))}),t.connect()}catch(s){console.error("Failed to setup voice:",s)}}});var BS,DS=ie(()=>{"use strict";BS=e=>{let t=c=>{if(e.original)return;let d=e.config().voiceRecognition??{};e.original={backgroundColor:c.style.backgroundColor,color:c.style.color,borderColor:c.style.borderColor,iconName:d.iconName??"mic",iconSize:parseFloat(d.iconSize??"")||e.iconFallbackPx}},n=(c,d,p)=>{let f=c.querySelector("svg");f&&f.remove();let m=e.original?.iconSize??(parseFloat(e.config().voiceRecognition?.iconSize??"")||e.iconFallbackPx),g=e.renderIcon(d,m,p,1.5);g&&c.appendChild(g)},o=c=>{c.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")};return{recording:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=d.recordingBackgroundColor,f=d.recordingIconColor,m=d.recordingBorderColor;if(o(c),c.classList.add("persona-voice-recording"),e.setMicState("recording"),c.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",c.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let g=c.querySelector("svg");g&&g.setAttribute("stroke",f)}m&&(c.style.borderColor=m),c.setAttribute("aria-label","Stop voice recognition")},processing:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=d.processingIconName??"loader",g=d.processingIconColor??f?.color??"",h=d.processingBackgroundColor??f?.backgroundColor??"",b=d.processingBorderColor??f?.borderColor??"";o(c),c.classList.add("persona-voice-processing"),e.setMicState("processing"),c.style.backgroundColor=h,c.style.borderColor=b;let C=g||"currentColor";c.style.color=C,n(c,m,C),c.setAttribute("aria-label","Processing voice input"),p==="none"&&(c.style.cursor="default")},speaking:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",g=d.speakingIconName??m,h=d.speakingIconColor??(p==="barge-in"?d.recordingIconColor??f?.color??"":f?.color??""),b=d.speakingBackgroundColor??(p==="barge-in"?d.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":f?.backgroundColor??""),C=d.speakingBorderColor??(p==="barge-in"?d.recordingBorderColor??"":f?.borderColor??"");o(c),c.classList.add("persona-voice-speaking"),e.setMicState("speaking"),c.style.backgroundColor=b,c.style.borderColor=C;let A=h||"currentColor";c.style.color=A,n(c,g,A);let S=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";c.setAttribute("aria-label",S),p==="none"&&(c.style.cursor="default"),p==="barge-in"&&c.classList.add("persona-voice-recording")},reset:()=>{let c=e.mic();if(!c)return;o(c),e.setMicState("idle");let d=e.original;d&&(c.style.backgroundColor=d.backgroundColor??"",c.style.color=d.color??"",c.style.borderColor=d.borderColor??"",n(c,d.iconName,d.color||"currentColor"),e.original=null),c.style.cursor="",c.setAttribute("aria-label","Start voice recognition")}}}});var _S={};En(_S,{BrowserVoiceProvider:()=>Ds,KeyedVoiceTranscript:()=>pu,RuntypeVoiceProvider:()=>Ba,createBestAvailableVoiceProvider:()=>th,createMicStateStyles:()=>BS,createVoiceProvider:()=>nc,createVoiceSessionBridge:()=>IS,isVoiceSupported:()=>CS,wireSessionVoice:()=>RS});var OS=ie(()=>{"use strict";wS();Zg();eh();SS();HS();WS();DS()});function kH(e){return e.replace(/\/+$/,"")}async function LH(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 mu,VS=ie(()=>{"use strict";Qg();mu=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#t=null;this.#n=0;this.#o=t}#e;#t;#n;#o;#a(){return this.#t??=Promise.resolve(this.#o.createPlaybackEngine?this.#o.createPlaybackEngine():new Wa(24e3,{prebufferMs:this.#o.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#n;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#a();if(t!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#n&&o.onStart?.()}),r.onFinished(()=>{t===this.#n&&o.onEnd?.()});let s=`${kH(this.#o.host)}/v1/agents/${encodeURIComponent(this.#o.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#o.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#o.voice,format:"pcm"})});if(t!==this.#n)return;if(!i.ok||!i.body)throw new Error(await LH(i));let l=i.body.getReader();for(;;){let{done:c,value:d}=await l.read();if(t!==this.#n){await l.cancel().catch(()=>{});return}if(c)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.#n)return;let s=r instanceof Error?r:new Error(String(r));this.#o.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}});var gu,$S=ie(()=>{"use strict";gu=class{constructor(t,n,o={}){this.id="fallback";this.#t=t,this.#n=n,this.#o=o,this.#e=t}#e;#t;#n;#o;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#t;let o=!1;this.#t.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#o.onFallback?.(r),this.#e=this.#n,this.#n.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}});var US={};En(US,{FallbackSpeechEngine:()=>gu,RuntypeSpeechEngine:()=>mu});var zS=ie(()=>{"use strict";VS();$S()});var jS={};En(jS,{createReconnectController:()=>IH});function IH(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},i=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},c=()=>{i()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},f=h=>new Promise(b=>{n=b,o=setTimeout(()=>{o=null,n=null,b()},h)}),m=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let b=!1;for(let A of e.getMessages())A.streaming&&(A.streaming=!1,b=!0);let C=e.buildErrorContent("Connection lost and the response could not be resumed.");C?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):b&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let h=e.config.reconnect?.backoffMs??PH,b=e.config.reconnect?.maxAttempts??h.length,C=e.config.reconnectStream;if(!C){e.setReconnecting(!1);return}for(;e.getResumable()&&t<b;){t+=1,e.setStatus("resuming");let A=e.getResumable(),S=A.lastEventId,E=new AbortController;e.setAbortController(E),e.emitReconnect({phase:"resuming",handle:A,attempt:t});let k=null;try{let D=await C({executionId:A.executionId,after:A.lastEventId,signal:E.signal});D&&D.ok&&D.body&&(k=D.body)}catch{k=null}if(E.signal.aborted)return;if(k){let D=e.getMessages().find(Y=>Y.id===A.assistantMessageId)?.content,z=typeof D=="string"?D:"";try{await e.resumeConnect(k,A.assistantMessageId,z)}catch{}if(E.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:A});return}e.getResumable().lastEventId!==S&&(t=0)}if(e.getResumable()&&t<b&&(e.setStatus("paused"),await f(h[Math.min(t-1,h.length-1)]??1e3),E.signal.aborted))return}e.getResumable()&&m()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var PH,KS=ie(()=>{"use strict";PH=[1e3,2e3,4e3,8e3,8e3]});var _A,Ch,HR,Eu,ku,RR,OA,Lu,dc,WR,BR,NA,Pu=ie(()=>{"use strict";_A=null,Ch=()=>{if(_A!==null)return _A;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},HR="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Eu=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},ku=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 Eu("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Eu("unsupported",e),null):(n==="space"&&(o.key=" "),o)},RR=e=>HR.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),OA=(e,t)=>{let n=ku(e);if(!n)return"";let o=Ch(),r=RR(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("+")},Lu=e=>OA(e,!1),dc=e=>OA(e,!0),WR=(e,t)=>t.key?.toLowerCase()===e.key&&(Ch()?t.metaKey:t.ctrlKey)===e.mod&&!(Ch()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,BR=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},NA=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(WR(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&BR(i))){s.preventDefault();try{l.run(s)}catch(c){Eu(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=ku(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Eu(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",dc(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function GA(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 Hu(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Zr(e,t){return xr(e)-e.scrollTop<=t}function Ru(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Wu(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 YA(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function xh(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 XA(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Sh=ie(()=>{"use strict"});var pc,DR,Bu,_R,Th,JA,Pi,uc,Du,OR,NR,Ah,FR,VR,$R,fc,_u,mc,QA,UR,Mh,zR,ZA,gc,hc=ie(()=>{"use strict";pc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},DR=["pre","code","a","script","style"],Bu=e=>({type:e?.type??pc.type,placeholder:e?.placeholder??pc.placeholder,speed:e?.speed??pc.speed,duration:e?.duration??pc.duration,buffer:e?.buffer??pc.buffer}),_R=[{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"}],Th=new Map;for(let e of _R)Th.set(e.name,e);JA=["wipe","glyph-cycle"],Pi=e=>{Th.set(e.name,e)},uc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Th.get(e)??null,Du=(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(`
204
+ `);return s<0?"":e.slice(0,s)}return e},OR=(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},NR=(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},Ah=/\s/,FR=(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},VR=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Ah.test(s[l])){let c=l;for(;c<s.length&&Ah.test(s[c]);)c+=1;i.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let d=l;for(;d<s.length&&!Ah.test(s[d]);)c.appendChild(OR(o,s[d],t,n.value)),n.value+=1,d+=1;i.appendChild(c),l=d}r.replaceChild(i,e)},$R=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(NR(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},fc=(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??DR).map(f=>f.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)FR(c,s)||l.push(c),c=i.nextNode();let d={value:o?.startIndex??0},p=t==="char"?VR:$R;for(let f of l)p(f,n,d);return r.innerHTML},_u=(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},mc=(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},QA=new WeakMap,UR=(e,t)=>{if(!e.styles)return;let n=QA.get(t);if(n||(n=new Set,QA.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)},Mh=new WeakMap,zR=(e,t)=>{if(!e.onAttach)return;let n=Mh.get(t);if(n||(n=new Map,Mh.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},ZA=e=>{let t=Mh.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},gc=(e,t)=>{UR(e,t),zR(e,t)}});var qR,eM,tM,nM=ie(()=>{"use strict";hc();qR=`
205
205
  @keyframes persona-stream-wipe {
206
206
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
207
207
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -237,7 +237,7 @@ ${vH}`.trim(),{status:Y.failed?"failed":"completed",text:_,...I(_)}):{status:!Y.
237
237
  mask-image: none !important;
238
238
  }
239
239
  }
240
- `.trim(),ZA={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:zR};Pi(ZA);eM=ZA});var qR,yc,jR,KR,Eh,GR,YR,XR,cM,kh,QR,nM,oM,rM,JR,sM,iM,aM,ZR,Oa,eW,tW,nW,dM,oW,lM,rW,pM,uM,fM=ie(()=>{"use strict";hc();qR=`
240
+ `.trim(),eM={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:qR};Pi(eM);tM=eM});var jR,yc,KR,GR,Eh,YR,XR,QR,dM,kh,JR,oM,rM,sM,ZR,iM,aM,lM,eW,Oa,tW,nW,oW,pM,rW,cM,sW,uM,fM,mM=ie(()=>{"use strict";hc();jR=`
241
241
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
242
242
  animation: persona-stream-glyph-cycle-fade
243
243
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -255,13 +255,13 @@ ${vH}`.trim(),{status:Y.failed?"failed":"completed",text:_,...I(_)}):{status:!Y.
255
255
  opacity: 1 !important;
256
256
  }
257
257
  }
258
- `.trim(),yc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",jR=10,KR=120,Eh=120,GR=.4,YR=50,XR=e=>{if(!e)return Eh;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Eh},cM=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=XR(t);return KR*n/Eh},kh=e=>{let t=yc[Math.floor(Math.random()*yc.length)];return e&&t===e&&(t=yc[(yc.indexOf(t)+1)%yc.length]),t},QR=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<GR&&(r.textContent=kh())}},nM=new WeakMap,oM=25,rM=.5,JR=6,sM=.25,iM=new WeakMap,aM=new WeakMap,ZR=(e,t)=>{if(!e)return oM*rM;let n=iM.get(e);iM.set(e,t);let o=aM.get(e)??oM;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-sM)+r*sM,aM.set(e,o))}return Math.max(JR,o*rM)},Oa=new Map,eW=e=>e.closest("[data-message-id]")?.dataset.messageId??null,tW=e=>{e&&Oa.set(e,(Oa.get(e)??0)+1)},nW=e=>{if(!e)return;let t=Oa.get(e)??0;t<=1?Oa.delete(e):Oa.set(e,t-1)},dM=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=kh();let n=eW(e);n&&(e.dataset.glyphCycleMessageId=n),tW(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=ZR(o,r),i=cM(e),l=jR*i,c=r+l;if(o){let d=nM.get(o);d!==void 0&&(c=Math.max(c,d)),nM.set(o,c+s)}oW(e,t,c)},oW=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=cM(e),r=e.textContent??void 0,s=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,nW(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let i=kh(r);e.textContent=i,r=i,QR(e),setTimeout(s,o)};setTimeout(s,o)},lM=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))dM(n)},rW=e=>e.nodeType===1,pM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:qR,bufferContent(e){if(e.length<YR)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(Oa.get(e.id)??0)>0},onAttach(e){lM(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))rW(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?dM(r):lM(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};Pi(pM);uM=pM});var mM={};En(mM,{glyphCycle:()=>uM,wipe:()=>eM});var gM=ie(()=>{"use strict";tM();fM()});function Sc(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=v("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(Ta)):(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 h of t){if(h.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",h.id),h.destructive&&b.setAttribute("data-destructive",""),h.icon){let A=We(h.icon,16,"currentColor",1.5);A&&b.appendChild(A)}let C=document.createElement("span");C.textContent=h.label,b.appendChild(C),b.addEventListener("click",A=>{A.stopPropagation(),f(),n(h.id)}),l.appendChild(b)}let c=null;function d(){if(!s)return;let h=o.getBoundingClientRect();l.style.top=`${h.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-h.right}px`,l.style.left="auto"):(l.style.left=`${h.left}px`,l.style.right="auto")}function p(){let h=l.classList.contains("persona-hidden");d(),l.classList.remove("persona-hidden"),h&&i?.(!0),requestAnimationFrame(()=>{let b=C=>{!l.contains(C.target)&&!o.contains(C.target)&&f()};document.addEventListener("click",b,!0),c=()=>document.removeEventListener("click",b,!0)})}function f(){let h=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,h&&i?.(!1)}function m(){l.classList.contains("persona-hidden")?p():f()}function g(){f(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:f,toggle:m,destroy:g}}var Bh=ie(()=>{"use strict";Ge();ln();nr()});function Ln(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,d=v("button",Jt(!i&&"persona-icon-btn",s));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=We(t,o??16,"currentColor",r??2);if(p&&d.appendChild(p),l&&d.addEventListener("click",l),c)for(let[f,m]of Object.entries(c))d.setAttribute(f,m);return d}function Hi(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,i&&(d+=" "+i);let p=v("button",d);if(p.type="button",p.setAttribute("aria-label",n),t){let m=We(t,s??14,"currentColor",2);m&&p.appendChild(m)}let f=v("span");if(f.textContent=n,p.appendChild(f),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Nu(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let f;p.icon?f=Ln({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),o(p.id)}}):(f=v("button","persona-icon-btn"+(p.className?" "+p.className:"")),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{i=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:f}),s.appendChild(f)}function d(p){i=p,c()}return{element:s,setSelected:d}}function CM(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:d,chevronLabel:p="More options",chevronIconSize:f,className:m,primaryClassName:g,chevronClassName:h}=e,b=v("div","persona-split-btn"+(m?" "+m:"")),C={label:t,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},A=r&&n?Ln({...C,icon:n,size:o??14}):Hi({...C,icon:n,iconSize:o??14}),S=Ln({icon:"chevron-down",label:p,size:f??14,className:"persona-split-btn-chevron"+(h?" "+h:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});b.append(A,S);let E=null,k=()=>{if(E)return E;let D=(typeof d=="function"?d():d)??void 0;return E=Sc({items:s,onSelect:i,anchor:b,position:c,portal:D,onOpenChange:z=>{S.setAttribute("aria-expanded",z?"true":"false")}}),D||b.appendChild(E.element),E};return b.isConnected?k():requestAnimationFrame(()=>{E||k()}),S.addEventListener("click",D=>{D.stopPropagation(),k().toggle()}),{element:b,primaryButton:A,chevronButton:S,openMenu:()=>k().show(),closeMenu:()=>E?.hide(),toggleMenu:()=>k().toggle(),destroy:()=>{E?.destroy(),b.remove()}}}function wM(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,d=v("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=v("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let f=We(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),c&&(d.style.borderRadius=c.borderRadius??"10px",d.style.padding=c.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=c.background??"",d.style.borderColor=c.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let m=Sc({items:o,onSelect:h=>{d.setAttribute("aria-expanded","false"),r(h)},anchor:d,position:s,portal:i});i||d.appendChild(m.element);let g=()=>d.getAttribute("data-persona-menu-locked")==="true";return d.addEventListener("click",h=>{if(h.stopPropagation(),g())return;let b=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),m.toggle()}),d.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d.click())}),{element:d,setLabel:h=>{p.textContent=h,d.setAttribute("aria-label",h)},open:()=>{d.setAttribute("aria-expanded","true"),m.show()},close:()=>{d.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let h=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),d.remove()}}}var Ri=ie(()=>{"use strict";Ge();ln();Bh()});var Fs,Gu=ie(()=>{"use strict";Ge();Fs=(e,t,n)=>{let o=n;for(let r of t){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o}});var JM,ty,Yu,Xu=ie(()=>{"use strict";JM=()=>{},ty=e=>{JM=e.webMcpToolTitle},Yu=e=>JM(e)});var Uo,Bi,ZM,eT,tT,ny,oy,ry=ie(()=>{"use strict";Ge();Gr();Xu();Uo=require("lucide");ao();Ai();Bi=e=>{let n=(e.startsWith(Kr)?e.slice(Kr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ZM=e=>e?.approval!==!1?e?.approval:void 0,eT=(e,t,n)=>{let o=ZM(n)?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},tT=(e,t,n)=>{let o=ZM(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=Je(t?Uo.ChevronUp:Uo.ChevronDown,14,"currentColor",2);i&&s.appendChild(i)}},ny=(e,t,n,o=new Map)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let i=eT(e,o,n);tT(r,i,n),s.style.display=i?"":"none"},oy=(e,t,n=new Map)=>{let o=e.approval,r=t?.approval!==!1?t?.approval:void 0,s=o?.status==="pending",i=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",i.style.borderColor=r?.borderColor??"var(--persona-approval-border)",i.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return i;let l=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=v("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let d=o.status==="denied"?Uo.ShieldX:o.status==="timeout"?Uo.ShieldAlert:Uo.ShieldCheck,p=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",f=Je(d,20,p,2);f&&c.appendChild(f);let m=v("div","persona-flex-1 persona-min-w-0"),g=v("div","persona-flex persona-items-center persona-gap-2"),h=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(h.style.color=r.titleColor),h.textContent=r?.title??"Approval Required",g.appendChild(h),!s){let T=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");T.setAttribute("data-approval-status",o.status),o.status==="approved"?(T.style.backgroundColor="var(--persona-palette-colors-success-100)",T.style.color="var(--persona-palette-colors-success-700)",T.textContent="Approved"):o.status==="denied"?(T.style.backgroundColor="var(--persona-palette-colors-error-100)",T.style.color="var(--persona-palette-colors-error-700)",T.textContent="Denied"):o.status==="timeout"&&(T.style.backgroundColor="var(--persona-palette-colors-warning-100)",T.style.color="var(--persona-palette-colors-warning-700)",T.textContent="Timeout"),g.appendChild(T)}m.appendChild(g);let C=o.toolType==="webmcp"||o.toolName.startsWith(Kr)?Yu(o.toolName):void 0,A=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...C?{displayTitle:C}:{},...o.reason?{reason:o.reason}:{}}),S=!o.toolName,E=A||(S?o.description:`The assistant wants to use \u201C${C??Bi(o.toolName)}\u201D.`),k=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=E,m.appendChild(k),o.reason){let T=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");T.setAttribute("data-approval-reason","true"),r?.reasonColor?T.style.color=r.reasonColor:r?.descriptionColor&&(T.style.color=r.descriptionColor);let W=v("span","persona-font-medium");W.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,T.appendChild(W),T.appendChild(document.createTextNode(o.reason)),m.appendChild(T)}let D=r?.detailsDisplay??"collapsed",z=!!o.description&&!S,Y=z||!!o.parameters;if(D!=="hidden"&&Y){let T=eT(e.id,n,t),W=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(W.style.color=r.descriptionColor);let L=v("span");L.setAttribute("data-approval-details-label","true");let w=v("span","persona-inline-flex persona-items-center");w.setAttribute("data-approval-details-chevron","true"),W.append(L,w),tT(W,T,t),m.appendChild(W);let x=v("div");if(x.setAttribute("data-approval-details","true"),x.style.display=T?"":"none",z){let P=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=o.description,x.appendChild(P)}if(o.parameters){let P=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(P.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(P.style.color=r.parameterTextColor),P.style.fontSize="0.75rem",P.style.lineHeight="1rem",P.textContent=tr(o.parameters),x.appendChild(P)}m.appendChild(x)}if(s){let T=v("div","persona-flex persona-gap-2 persona-mt-2");T.setAttribute("data-approval-buttons","true");let W=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",W.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",W.setAttribute("data-approval-action","approve");let L=Je(Uo.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);L&&(L.style.marginRight="4px",W.appendChild(L));let w=document.createTextNode(r?.approveLabel??"Approve");W.appendChild(w);let x=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");x.type="button",x.style.backgroundColor=r?.denyButtonColor??"transparent",x.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",x.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,x.setAttribute("data-approval-action","deny");let P=Je(Uo.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);P&&(P.style.marginRight="4px",x.appendChild(P));let I=document.createTextNode(r?.denyLabel??"Deny");x.appendChild(I),T.append(W,x),m.appendChild(T)}return l.append(c,m),i.appendChild(l),i}});var _i,sB,nT,Di,iB,aB,sy,lB,cB,dB,iy,oT=ie(()=>{"use strict";Ge();Xu();_i=require("lucide");ao();Gr();Ai();Ra();ry();sB=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),nT=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Di=(e,t)=>{nT(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},iB=e=>e?.approval!==!1?e?.approval:void 0,aB=(e,t,n)=>{let o=n?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},sy=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},lB=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Kr)?Yu(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let i=r??Bi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=i,n.appendChild(c),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},cB=e=>{let t=v("div","persona-approval-resolved"),n=Je(_i.Ban,15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?Bi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},dB=(e,t,n,o,r,s,i,l,c=!1)=>{let d=v("div","persona-approval-card persona-shadow-sm");d.id=`bubble-${n.id}`,d.setAttribute("data-message-id",n.id),d.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(d.style.background=r.backgroundColor),r?.borderColor&&(d.style.borderColor=r.borderColor),r?.shadow!==void 0&&(d.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",f=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden"&&!c,g=f||m,h=g&&aB(n.id,t,r),b=r?.showDetailsLabel??"Show details",C=r?.hideDetailsLabel??"Hide details",A=v("button","persona-approval-head");A.type="button",g?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",h?"true":"false"),A.setAttribute("aria-label",h?C:b)):A.setAttribute("data-static","true");let S=v("span","persona-approval-logo"),E=Je(_i.ShieldCheck,16,"currentColor",2);E&&S.appendChild(E),A.appendChild(S);let k=lB(o,r);if(g){let L=v("span","persona-approval-toggle");L.setAttribute("aria-hidden","true");let w=Je(_i.ChevronDown,14,"currentColor",2);w&&L.appendChild(w),k.append(" "),k.appendChild(L)}A.appendChild(k),d.appendChild(A);let D=v("div","persona-approval-body");if(g){let L=v("div","persona-approval-details");if(L.setAttribute("data-role","params"),L.hidden=!h,f){let w=v("p","persona-approval-desc");r?.descriptionColor&&(w.style.color=r.descriptionColor),w.textContent=o.description,L.appendChild(w)}if(m){let w=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(w.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(w.style.color=r.parameterTextColor),w.textContent=tr(o.parameters),L.appendChild(w)}D.appendChild(L)}if(c){let L=v("div","persona-approval-call");L.setAttribute("data-role","raw-call");let w=v("code","persona-approval-tool-name");if(w.textContent=o.toolName,L.appendChild(w),o.parameters!=null){let x=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(x.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(x.style.color=r.parameterTextColor),x.textContent=tr(o.parameters),L.appendChild(x)}D.appendChild(L)}if(o.reason){let L=v("p","persona-approval-reason");r?.reasonColor?L.style.color=r.reasonColor:r?.descriptionColor&&(L.style.color=r.descriptionColor);let w=v("span","persona-approval-reason-label");w.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,L.append(w,document.createTextNode(o.reason)),D.appendChild(L)}let z=v("div","persona-approval-actions"),Y=null,T=L=>{r?.approveButtonColor&&(L.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(L.style.color=r.approveButtonTextColor)},W=v("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r?.denyButtonColor&&(W.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append(r?.denyLabel??"Deny"),l){let L=v("div","persona-approval-split"),w=v("button","persona-approval-primary");w.type="button",w.setAttribute("data-action","always"),T(w),w.append(r?.approveLabel??"Always allow",sy("\u23CE"));let x=v("button","persona-approval-caret");x.type="button",x.setAttribute("data-action","toggle-menu"),x.setAttribute("aria-label","More options"),T(x);let P=Je(_i.ChevronDown,15,"currentColor",2);P&&x.appendChild(P),L.append(w,x),z.append(L,W),W.append(sy("Esc"));let I=v("div","persona-approval-menu"),J=v("button","persona-approval-menu-item");J.type="button",J.append("Allow once",sy("\u2318\u23CE")),I.appendChild(J),Y=Bs({anchor:L,content:I,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(n.id,Y),J.addEventListener("click",()=>{Di(e,n.id),s()})}else{let L=v("button","persona-approval-primary persona-approval-primary--solo");L.type="button",L.setAttribute("data-action","allow"),T(L),L.append(r?.approveLabel??"Allow"),z.append(L,W)}return D.appendChild(z),d.appendChild(D),d.addEventListener("click",L=>{let w=L.target instanceof Element?L.target.closest("[data-action]"):null;if(!w)return;let x=w.getAttribute("data-action");if(x==="toggle-params"){let P=d.querySelector('[data-role="params"]');if(P){let I=P.hidden;P.hidden=!I,A.setAttribute("aria-expanded",I?"true":"false"),A.setAttribute("aria-label",I?C:b),t.set(n.id,I)}return}if(x==="toggle-menu"){Y?.toggle();return}if(x==="always"){Di(e,n.id),s({remember:!0});return}if(x==="allow"){Di(e,n.id),s();return}if(x==="deny"){Di(e,n.id),i();return}}),d},iy=(e=new Map)=>{let t=sB();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:i,config:l})=>{let c=r?.approval;if(!c)return null;let d=iB(l);if(c.status!=="pending"){if(Di(t,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return cB(c)}nT(t,r.id);let p=!!l?.clientToken,f=d?.enableAlwaysAllow===!0,m=dB(t,e,r,c,d,s,i,f,p);if(f){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=h=>{Ix(h)||r.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Di(t,r.id),h.key==="Escape"?i():h.metaKey||h.ctrlKey?s():s({remember:!0})))};t.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Di(t,r);t.latestPendingApprovalId=null}}}});var rT=ie(()=>{"use strict";ry();oT();Xu()});var sT={};En(sT,{createApprovalBubble:()=>oy,createBuiltInApprovalPlugin:()=>iy,humanizeToolName:()=>Bi,initApprovalUi:()=>ty,updateApprovalDetailsUI:()=>ny});var iT=ie(()=>{"use strict";rT()});function za(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}function cT(e,t){if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n]}function hB(e,t){return(t&&cT(e,t))??cT(e,es)??fB}function yB(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function bB(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function vB(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function CB(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function wB(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function xB(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function SB(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function AB(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function MB(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function ay(e,t,n,o,r,s,i,l){let c=r.has(e.id),d=v("div","persona-border-b persona-border-persona-divider persona-text-xs");za(d,o.classNames?.eventRow);let p=i.find(m=>m.renderEventStreamRow);if(p?.renderEventStreamRow&&l){let m=p.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>s(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(f()),d;function f(){let m=v("div",""),g=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let h=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=Je(c?qn.ChevronDown:qn.ChevronRight,"14px","currentColor",2);b&&h.appendChild(b);let C=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=o.timestampFormat??"relative";C.textContent=A==="relative"?bB(e.timestamp,n):vB(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let E=hB(e.type,o.badgeColors),k=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=yB(E.text),k.textContent=e.type;let D=o.descriptionFields??mB,z=CB(e.payload,D),Y=null;z&&(Y=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=z);let T=v("div","persona-flex-1 persona-min-w-0"),W=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),L=Je(qn.Clipboard,"12px","currentColor",1.5);return L&&W.appendChild(L),W.addEventListener("click",async w=>{w.stopPropagation(),await wB(xB(e)),W.innerHTML="";let x=Je(qn.Check,"12px","currentColor",1.5);x&&W.appendChild(x),setTimeout(()=>{W.innerHTML="";let P=Je(qn.Clipboard,"12px","currentColor",1.5);P&&W.appendChild(P)},1500)}),g.appendChild(h),g.appendChild(C),S&&g.appendChild(S),g.appendChild(k),Y&&g.appendChild(Y),g.appendChild(T),g.appendChild(W),m.appendChild(g),c&&m.appendChild(MB(e,i,l)),m}}function ly(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=e,l=e.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,d=c?.enabled!==!1,p=c?.iconName??"arrow-down",f=c?.label??"",m=r?.features?.eventStream??{},g=s.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>h().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return h();function h(){let b=m.classNames,C=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");za(C,b?.panel);let A=[],S="",E="",k=null,D=[],z={},Y=0,T=Hu(),W=0,L=0,w=!1,x=null,P=!1,I=0,J=new Set,_=new Map,j="",te="",K=null,X,oe,de,xe,Te=null,re=null,N=null;function ke(){let Ee=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),He=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(za(He,b?.headerBar),i){re=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),re.style.cursor="help",Te=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Te.textContent="-- tok/s",N=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),N.style.display="none",N.style.pointerEvents="none";let gn=re,Zn=N,ss=()=>{if(!Zn.textContent)return;let qs=gn.getBoundingClientRect(),oo=Ee.getBoundingClientRect();Zn.style.left=`${qs.left-oo.left}px`,Zn.style.top=`${qs.bottom-oo.top+4}px`,Zn.style.display="block"},jn=()=>{Zn.style.display="none"};re.addEventListener("mouseenter",ss),re.addEventListener("mouseleave",jn),re.appendChild(Te)}let je=v("div","persona-flex-1");X=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let It=v("option","");It.value="",It.textContent="All events (0)",X.appendChild(It),oe=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),oe.type="button",oe.title="Copy All";let nn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);nn&&oe.appendChild(nn);let Ot=v("span","persona-event-copy-all persona-text-xs");Ot.textContent="Copy All",oe.appendChild(Ot),re&&He.appendChild(re),He.appendChild(je),He.appendChild(X),He.appendChild(oe);let mt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");za(mt,b?.searchBar);let Ht=Je(qn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),St=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ht&&St.appendChild(Ht),de=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),za(de,b?.searchInput),de.type="text",de.placeholder="Search event payloads...",xe=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),xe.type="button",xe.style.display="none";let Kt=Je(qn.X,"12px","currentColor",2);return Kt&&xe.appendChild(Kt),mt.appendChild(St),mt.appendChild(de),mt.appendChild(xe),Ee.appendChild(He),Ee.appendChild(mt),N&&Ee.appendChild(N),Ee}let ve,tt=s.find(Ee=>Ee.renderEventStreamToolbar);tt?.renderEventStreamToolbar&&r?ve=tt.renderEventStreamToolbar({config:r,defaultRenderer:()=>ke(),eventCount:t.getSize(),filteredCount:0,onFilterChange:He=>{S=He,Z(),Ie()},onSearchChange:He=>{E=He,Z(),Ie()}})??ke():ve=ke();let xt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");xt.style.display="none";function ht(){if(!i||!Te||!re)return;let Ee=i(),He=SB(Ee);Te.textContent=He;let je=AB(Ee);N&&(N.textContent=je,je||(N.style.display="none")),re.setAttribute("aria-label",je?`Throughput: ${He}, ${je}`:`Throughput: ${He}`)}let lt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Ye=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ye.style.height="100%";let dt=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");za(dt,b?.scrollIndicator),dt.style.display="none",dt.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let Pe=l(p,"14px","currentColor",2);Pe&&dt.appendChild(Pe);let Se=v("span","");Se.textContent=f,dt.appendChild(Se);let U=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");U.style.display="none",lt.appendChild(Ye),lt.appendChild(U),lt.appendChild(dt),C.setAttribute("tabindex","0"),C.appendChild(ve),C.appendChild(xt),C.appendChild(lt);function R(){let Ee=t.getAll(),He={};for(let mt of Ee)He[mt.type]=(He[mt.type]||0)+1;let je=Object.keys(He).sort(),It=je.length!==D.length||!je.every((mt,Ht)=>mt===D[Ht]),wn=!It&&je.some(mt=>He[mt]!==z[mt]),nn=Ee.length!==Object.values(z).reduce((mt,Ht)=>mt+Ht,0);if(!It&&!wn&&!nn||(D=je,z=He,!X))return;let Ot=X.value;if(X.options[0].textContent=`All events (${Ee.length})`,It){for(;X.options.length>1;)X.remove(1);for(let mt of je){let Ht=v("option","");Ht.value=mt,Ht.textContent=`${mt} (${He[mt]||0})`,X.appendChild(Ht)}Ot&&je.includes(Ot)?X.value=Ot:Ot&&(X.value="",S="")}else for(let mt=1;mt<X.options.length;mt++){let Ht=X.options[mt];Ht.textContent=`${Ht.value} (${He[Ht.value]||0})`}}function G(){let Ee=t.getAll();if(S&&(Ee=Ee.filter(He=>He.type===S)),E){let He=E.toLowerCase();Ee=Ee.filter(je=>je.type.toLowerCase().includes(He)||je.payload.toLowerCase().includes(He))}return Ee}function ne(){return S!==""||E!==""}function Z(){Y=0,W=0,T.resume(),dt.style.display="none"}function le(Ee){J.has(Ee)?J.delete(Ee):J.add(Ee),K=Ee;let He=Ye.scrollTop,je=T.isFollowing();P=!0,T.pause(),Ie(),Ye.scrollTop=He,je&&T.resume(),P=!1}function Me(){return Zr(Ye,50)}function Ie(){L=Date.now(),w=!1,ht(),R();let Ee=t.getEvictedCount();Ee>0?(xt.textContent=`${Ee.toLocaleString()} older events truncated`,xt.style.display=""):xt.style.display="none",A=G();let He=A.length,je=t.getSize()>0;He===0&&je&&ne()?(U.textContent=E?`No events matching '${E}'`:"No events matching filter",U.style.display="",Ye.style.display="none"):(U.style.display="none",Ye.style.display=""),oe&&(oe.title=ne()?`Copy Filtered (${He})`:"Copy All"),d&&!T.isFollowing()&&He>Y&&(W+=He-Y,Se.textContent=f?`${f}${W>0?` (${W})`:""}`:"",dt.style.display=""),Y=He;let It=t.getAll(),wn=It.length>0?It[0].timestamp:0,nn=new Set(A.map(Ht=>Ht.id));for(let Ht of J)nn.has(Ht)||J.delete(Ht);let Ot=S!==j||E!==te,mt=_.size===0&&A.length>0;if(Ot||mt||A.length===0){Ye.innerHTML="",_.clear();let Ht=document.createDocumentFragment();for(let St=0;St<A.length;St++){let Kt=ay(A[St],St,wn,m,J,le,s,r);_.set(A[St].id,Kt),Ht.appendChild(Kt)}Ye.appendChild(Ht),j=S,te=E,K=null}else{if(K!==null){let St=_.get(K);if(St&&St.parentNode===Ye){let Kt=A.findIndex(gn=>gn.id===K);if(Kt>=0){let gn=ay(A[Kt],Kt,wn,m,J,le,s,r);Ye.insertBefore(gn,St),St.remove(),_.set(K,gn)}}K=null}let Ht=new Set(A.map(St=>St.id));for(let[St,Kt]of _)Ht.has(St)||(Kt.remove(),_.delete(St));for(let St=0;St<A.length;St++){let Kt=A[St];if(!_.has(Kt.id)){let gn=ay(Kt,St,wn,m,J,le,s,r);_.set(Kt.id,gn),Ye.appendChild(gn)}}}T.isFollowing()&&(Ye.scrollTop=Ye.scrollHeight)}function _e(){if(Date.now()-L>=gB){x!==null&&(cancelAnimationFrame(x),x=null),Ie();return}w||(w=!0,x=requestAnimationFrame(()=>{x=null,Ie()}))}let ct=(Ee,He)=>{if(!oe)return;oe.innerHTML="";let je=Je(Ee,"12px","currentColor",1.5);je&&oe.appendChild(je);let It=v("span","persona-text-xs");It.textContent="Copy All",oe.appendChild(It),setTimeout(()=>{oe.innerHTML="";let wn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);wn&&oe.appendChild(wn);let nn=v("span","persona-text-xs");nn.textContent="Copy All",oe.appendChild(nn),oe.disabled=!1},He)},Tt=async()=>{if(oe){oe.disabled=!0;try{let Ee;ne()?Ee=A:n?(Ee=await n(),Ee.length===0&&(Ee=t.getAll())):Ee=t.getAll();let He=Ee.map(je=>{try{return JSON.parse(je.payload)}catch{return je.payload}});await navigator.clipboard.writeText(JSON.stringify(He,null,2)),ct(qn.Check,1500)}catch{ct(qn.X,1500)}}},qe=()=>{X&&(S=X.value,Z(),Ie())},nt=()=>{!de||!xe||(xe.style.display=de.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{E=de.value,Z(),Ie()},150))},Ut=()=>{!de||!xe||(de.value="",E="",xe.style.display="none",k&&clearTimeout(k),Z(),Ie())},tn=()=>{if(P)return;let Ee=Ye.scrollTop,{action:He,nextLastScrollTop:je}=Ru({following:T.isFollowing(),currentScrollTop:Ee,lastScrollTop:I,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});I=je,He==="resume"?(T.resume(),W=0,dt.style.display="none"):He==="pause"&&(T.pause(),d&&(Se.textContent=f,dt.style.display=""))},ee=Ee=>{let He=Wu({following:T.isFollowing(),deltaY:Ee.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});He==="pause"?(T.pause(),d&&(Se.textContent=f,dt.style.display="")):He==="resume"&&(T.resume(),W=0,dt.style.display="none")},Re=()=>{d&&(Ye.scrollTop=Ye.scrollHeight,T.resume(),W=0,dt.style.display="none")},Fe=Ee=>{let He=Ee.target;if(!He||He.closest("button"))return;let je=He.closest("[data-event-id]");if(!je)return;let It=je.getAttribute("data-event-id");It&&le(It)},yt=Ee=>{if((Ee.metaKey||Ee.ctrlKey)&&Ee.key==="f"){Ee.preventDefault(),de?.focus(),de?.select();return}Ee.key==="Escape"&&(de&&document.activeElement===de?(Ut(),de.blur(),C.focus()):o&&o())};oe&&oe.addEventListener("click",Tt),X&&X.addEventListener("change",qe),de&&de.addEventListener("input",nt),xe&&xe.addEventListener("click",Ut),Ye.addEventListener("scroll",tn),Ye.addEventListener("wheel",ee,{passive:!0}),Ye.addEventListener("click",Fe),dt.addEventListener("click",Re),C.addEventListener("keydown",yt);function bt(){k&&clearTimeout(k),x!==null&&(cancelAnimationFrame(x),x=null),w=!1,_.clear(),oe&&oe.removeEventListener("click",Tt),X&&X.removeEventListener("change",qe),de&&de.removeEventListener("input",nt),xe&&xe.removeEventListener("click",Ut),Ye.removeEventListener("scroll",tn),Ye.removeEventListener("wheel",ee),Ye.removeEventListener("click",Fe),dt.removeEventListener("click",Re),C.removeEventListener("keydown",yt)}return{element:C,update:_e,destroy:bt}}}var qn,es,fB,mB,gB,dT=ie(()=>{"use strict";Ge();qn=require("lucide");ao();Sh();es={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};es.execution_error=es.error;es.execution_=es.flow_;es.turn_=es.agent_;es.text_=es.agent_;fB={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},mB=["flowName","stepName","reasoningText","text","name","tool","toolName"],gB=100});var Ec,pT=ie(()=>{"use strict";Ec=class{#e;#t=0;#n=0;#o=0;#a=new Set;#r;#s;constructor(t=2e3,n=null){this.#r=t,this.#e=new Array(t),this.#s=n}push(t){this.#e[this.#t]=t,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#o++,this.#a.add(t.type),this.#s?.put(t)}getAll(){return this.#n===0?[]:this.#n<this.#r?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#r),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#s)return 0;let t=await this.#s.getAll();if(t.length===0)return 0;let n=t.length>this.#r?t.slice(t.length-this.#r):t;for(let o of n)this.#e[this.#t]=o,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#a.add(o.type);return this.#o=t.length,n.length}getAllFromStore(){return this.#s?this.#s.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.#n}getTotalCaptured(){return this.#o}getEvictedCount(){return this.#o-this.#n}clear(){this.#e=new Array(this.#r),this.#t=0,this.#n=0,this.#o=0,this.#a.clear(),this.#s?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#o=0,this.#a.clear(),this.#s?.destroy()}getEventTypes(){return Array.from(this.#a)}}});var kc,uT=ie(()=>{"use strict";kc=class{#e=null;#t=[];#n=!1;#o=!1;#a;#r;constructor(t="persona-event-stream",n="events"){this.#a=t,this.#r=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.#a,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.#r)||r.createObjectStore(this.#r,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.#e=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.#e||this.#o||(this.#t.push(t),this.#n||(this.#n=!0,queueMicrotask(()=>this.#s())))}putBatch(t){if(!(!this.#e||this.#o||t.length===0))try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.#e){t([]);return}try{let i=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.#e){t(0);return}try{let s=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.#e){t();return}this.#t=[];try{let s=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.#e&&(this.#e.close(),this.#e=null)}destroy(){return this.#o=!0,this.#t=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.#a);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}#s(){if(this.#n=!1,!this.#e||this.#o||this.#t.length===0)return;let t=this.#t;this.#t=[];try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}}});function cy(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Qu(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function kB(e,t){return typeof t.type=="string"?t.type:e}function mT(e){let t=fT(e,"tokens")??fT(e,"totalTokens");return t?hT(t.output):void 0}function LB(e){return hT(e.durationMs)}function PB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var TB,EB,gT,hT,fT,Lc,yT=ie(()=>{"use strict";TB=new Set(["step_start","turn_start"]),EB=new Set(["step_complete","turn_complete"]),gT=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hT=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fT=(e,t)=>{let n=e[t];return gT(n)?n:void 0};Lc=class{#e={status:"idle"};#t=null;constructor(t=PB){this.now=t}getMetric(){let t=this.#t;if(t&&this.#e.status==="running"&&t.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.#e,durationMs:n,tokensPerSecond:Qu(this.#e.outputTokens,n)}}return this.#e}reset(){this.#t=null,this.#e={status:"idle"}}#n(t){this.#t={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.#e={status:"running"}}processEvent(t,n){if(!gT(n)){t==="execution_error"&&this.#t&&(this.#t=null,this.#e={status:"error"});return}let o=kB(t,n),r=this.now();if(o==="execution_start"){this.#n(r);return}if(TB.has(o)){this.#t||this.#n(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.#t||this.#n(r);let i=this.#t;i.firstDeltaAt??=r,i.visibleCharCount+=s.length;let l=i.exactOutputTokens+cy(i.visibleCharCount),c=r-i.firstDeltaAt;this.#e={status:"running",tokensPerSecond:Qu(l,c),outputTokens:l,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(EB.has(o)){if(!this.#t)return;let s=this.#t,i=mT(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+cy(s.visibleCharCount),d=this.#o(s,n,r);this.#e={status:"running",tokensPerSecond:Qu(c,d),outputTokens:c,durationMs:d,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.#t)return;let s=this.#t,i=mT(n),l=i??s.exactOutputTokens+cy(s.visibleCharCount),c=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.#o(s,n,r);this.#e={status:"complete",tokensPerSecond:Qu(l,d),outputTokens:l,durationMs:d,source:c},this.#t=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:"error"}}}#o(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:LB(n)??o-t.startedAt}}});var bT=ie(()=>{"use strict";dT();pT();uT();yT()});var vT={};En(vT,{EventStreamBuffer:()=>Ec,EventStreamStore:()=>kc,ThroughputTracker:()=>Lc,createEventStreamView:()=>ly});var CT=ie(()=>{"use strict";bT()});var py,sr,Pc=ie(()=>{"use strict";py=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},sr=new py});function Sr(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function wT(e){let t=Sr(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ju(e){if(typeof e!="string")return"";let t=e.indexOf(`
258
+ `.trim(),yc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",KR=10,GR=120,Eh=120,YR=.4,XR=50,QR=e=>{if(!e)return Eh;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Eh},dM=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=QR(t);return GR*n/Eh},kh=e=>{let t=yc[Math.floor(Math.random()*yc.length)];return e&&t===e&&(t=yc[(yc.indexOf(t)+1)%yc.length]),t},JR=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<YR&&(r.textContent=kh())}},oM=new WeakMap,rM=25,sM=.5,ZR=6,iM=.25,aM=new WeakMap,lM=new WeakMap,eW=(e,t)=>{if(!e)return rM*sM;let n=aM.get(e);aM.set(e,t);let o=lM.get(e)??rM;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-iM)+r*iM,lM.set(e,o))}return Math.max(ZR,o*sM)},Oa=new Map,tW=e=>e.closest("[data-message-id]")?.dataset.messageId??null,nW=e=>{e&&Oa.set(e,(Oa.get(e)??0)+1)},oW=e=>{if(!e)return;let t=Oa.get(e)??0;t<=1?Oa.delete(e):Oa.set(e,t-1)},pM=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=kh();let n=tW(e);n&&(e.dataset.glyphCycleMessageId=n),nW(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=eW(o,r),i=dM(e),l=KR*i,c=r+l;if(o){let d=oM.get(o);d!==void 0&&(c=Math.max(c,d)),oM.set(o,c+s)}rW(e,t,c)},rW=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=dM(e),r=e.textContent??void 0,s=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,oW(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let i=kh(r);e.textContent=i,r=i,JR(e),setTimeout(s,o)};setTimeout(s,o)},cM=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))pM(n)},sW=e=>e.nodeType===1,uM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:jR,bufferContent(e){if(e.length<XR)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(Oa.get(e.id)??0)>0},onAttach(e){cM(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))sW(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?pM(r):cM(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};Pi(uM);fM=uM});var gM={};En(gM,{glyphCycle:()=>fM,wipe:()=>tM});var hM=ie(()=>{"use strict";nM();mM()});function Sc(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=v("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(Ta)):(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 h of t){if(h.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",h.id),h.destructive&&b.setAttribute("data-destructive",""),h.icon){let A=We(h.icon,16,"currentColor",1.5);A&&b.appendChild(A)}let C=document.createElement("span");C.textContent=h.label,b.appendChild(C),b.addEventListener("click",A=>{A.stopPropagation(),f(),n(h.id)}),l.appendChild(b)}let c=null;function d(){if(!s)return;let h=o.getBoundingClientRect();l.style.top=`${h.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-h.right}px`,l.style.left="auto"):(l.style.left=`${h.left}px`,l.style.right="auto")}function p(){let h=l.classList.contains("persona-hidden");d(),l.classList.remove("persona-hidden"),h&&i?.(!0),requestAnimationFrame(()=>{let b=C=>{!l.contains(C.target)&&!o.contains(C.target)&&f()};document.addEventListener("click",b,!0),c=()=>document.removeEventListener("click",b,!0)})}function f(){let h=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,h&&i?.(!1)}function m(){l.classList.contains("persona-hidden")?p():f()}function g(){f(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:f,toggle:m,destroy:g}}var Bh=ie(()=>{"use strict";Ge();ln();nr()});function Ln(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,d=v("button",Jt(!i&&"persona-icon-btn",s));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=We(t,o??16,"currentColor",r??2);if(p&&d.appendChild(p),l&&d.addEventListener("click",l),c)for(let[f,m]of Object.entries(c))d.setAttribute(f,m);return d}function Hi(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,i&&(d+=" "+i);let p=v("button",d);if(p.type="button",p.setAttribute("aria-label",n),t){let m=We(t,s??14,"currentColor",2);m&&p.appendChild(m)}let f=v("span");if(f.textContent=n,p.appendChild(f),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Nu(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let f;p.icon?f=Ln({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),o(p.id)}}):(f=v("button","persona-icon-btn"+(p.className?" "+p.className:"")),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{i=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:f}),s.appendChild(f)}function d(p){i=p,c()}return{element:s,setSelected:d}}function wM(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:d,chevronLabel:p="More options",chevronIconSize:f,className:m,primaryClassName:g,chevronClassName:h}=e,b=v("div","persona-split-btn"+(m?" "+m:"")),C={label:t,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},A=r&&n?Ln({...C,icon:n,size:o??14}):Hi({...C,icon:n,iconSize:o??14}),S=Ln({icon:"chevron-down",label:p,size:f??14,className:"persona-split-btn-chevron"+(h?" "+h:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});b.append(A,S);let E=null,k=()=>{if(E)return E;let D=(typeof d=="function"?d():d)??void 0;return E=Sc({items:s,onSelect:i,anchor:b,position:c,portal:D,onOpenChange:z=>{S.setAttribute("aria-expanded",z?"true":"false")}}),D||b.appendChild(E.element),E};return b.isConnected?k():requestAnimationFrame(()=>{E||k()}),S.addEventListener("click",D=>{D.stopPropagation(),k().toggle()}),{element:b,primaryButton:A,chevronButton:S,openMenu:()=>k().show(),closeMenu:()=>E?.hide(),toggleMenu:()=>k().toggle(),destroy:()=>{E?.destroy(),b.remove()}}}function xM(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,d=v("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=v("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let f=We(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),c&&(d.style.borderRadius=c.borderRadius??"10px",d.style.padding=c.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=c.background??"",d.style.borderColor=c.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let m=Sc({items:o,onSelect:h=>{d.setAttribute("aria-expanded","false"),r(h)},anchor:d,position:s,portal:i});i||d.appendChild(m.element);let g=()=>d.getAttribute("data-persona-menu-locked")==="true";return d.addEventListener("click",h=>{if(h.stopPropagation(),g())return;let b=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),m.toggle()}),d.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d.click())}),{element:d,setLabel:h=>{p.textContent=h,d.setAttribute("aria-label",h)},open:()=>{d.setAttribute("aria-expanded","true"),m.show()},close:()=>{d.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let h=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),d.remove()}}}var Ri=ie(()=>{"use strict";Ge();ln();Bh()});var Fs,Gu=ie(()=>{"use strict";Ge();Fs=(e,t,n)=>{let o=n;for(let r of t){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o}});var ZM,ty,Yu,Xu=ie(()=>{"use strict";ZM=()=>{},ty=e=>{ZM=e.webMcpToolTitle},Yu=e=>ZM(e)});var Uo,Bi,eT,tT,nT,ny,oy,ry=ie(()=>{"use strict";Ge();Gr();Xu();Uo=require("lucide");ao();Ai();Bi=e=>{let n=(e.startsWith(Kr)?e.slice(Kr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},eT=e=>e?.approval!==!1?e?.approval:void 0,tT=(e,t,n)=>{let o=eT(n)?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},nT=(e,t,n)=>{let o=eT(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=Je(t?Uo.ChevronUp:Uo.ChevronDown,14,"currentColor",2);i&&s.appendChild(i)}},ny=(e,t,n,o=new Map)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let i=tT(e,o,n);nT(r,i,n),s.style.display=i?"":"none"},oy=(e,t,n=new Map)=>{let o=e.approval,r=t?.approval!==!1?t?.approval:void 0,s=o?.status==="pending",i=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",i.style.borderColor=r?.borderColor??"var(--persona-approval-border)",i.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return i;let l=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=v("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let d=o.status==="denied"?Uo.ShieldX:o.status==="timeout"?Uo.ShieldAlert:Uo.ShieldCheck,p=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",f=Je(d,20,p,2);f&&c.appendChild(f);let m=v("div","persona-flex-1 persona-min-w-0"),g=v("div","persona-flex persona-items-center persona-gap-2"),h=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(h.style.color=r.titleColor),h.textContent=r?.title??"Approval Required",g.appendChild(h),!s){let T=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");T.setAttribute("data-approval-status",o.status),o.status==="approved"?(T.style.backgroundColor="var(--persona-palette-colors-success-100)",T.style.color="var(--persona-palette-colors-success-700)",T.textContent="Approved"):o.status==="denied"?(T.style.backgroundColor="var(--persona-palette-colors-error-100)",T.style.color="var(--persona-palette-colors-error-700)",T.textContent="Denied"):o.status==="timeout"&&(T.style.backgroundColor="var(--persona-palette-colors-warning-100)",T.style.color="var(--persona-palette-colors-warning-700)",T.textContent="Timeout"),g.appendChild(T)}m.appendChild(g);let C=o.toolType==="webmcp"||o.toolName.startsWith(Kr)?Yu(o.toolName):void 0,A=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...C?{displayTitle:C}:{},...o.reason?{reason:o.reason}:{}}),S=!o.toolName,E=A||(S?o.description:`The assistant wants to use \u201C${C??Bi(o.toolName)}\u201D.`),k=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=E,m.appendChild(k),o.reason){let T=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");T.setAttribute("data-approval-reason","true"),r?.reasonColor?T.style.color=r.reasonColor:r?.descriptionColor&&(T.style.color=r.descriptionColor);let W=v("span","persona-font-medium");W.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,T.appendChild(W),T.appendChild(document.createTextNode(o.reason)),m.appendChild(T)}let D=r?.detailsDisplay??"collapsed",z=!!o.description&&!S,Y=z||!!o.parameters;if(D!=="hidden"&&Y){let T=tT(e.id,n,t),W=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(W.style.color=r.descriptionColor);let L=v("span");L.setAttribute("data-approval-details-label","true");let w=v("span","persona-inline-flex persona-items-center");w.setAttribute("data-approval-details-chevron","true"),W.append(L,w),nT(W,T,t),m.appendChild(W);let x=v("div");if(x.setAttribute("data-approval-details","true"),x.style.display=T?"":"none",z){let P=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=o.description,x.appendChild(P)}if(o.parameters){let P=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(P.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(P.style.color=r.parameterTextColor),P.style.fontSize="0.75rem",P.style.lineHeight="1rem",P.textContent=tr(o.parameters),x.appendChild(P)}m.appendChild(x)}if(s){let T=v("div","persona-flex persona-gap-2 persona-mt-2");T.setAttribute("data-approval-buttons","true");let W=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",W.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",W.setAttribute("data-approval-action","approve");let L=Je(Uo.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);L&&(L.style.marginRight="4px",W.appendChild(L));let w=document.createTextNode(r?.approveLabel??"Approve");W.appendChild(w);let x=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");x.type="button",x.style.backgroundColor=r?.denyButtonColor??"transparent",x.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",x.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,x.setAttribute("data-approval-action","deny");let P=Je(Uo.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);P&&(P.style.marginRight="4px",x.appendChild(P));let I=document.createTextNode(r?.denyLabel??"Deny");x.appendChild(I),T.append(W,x),m.appendChild(T)}return l.append(c,m),i.appendChild(l),i}});var _i,iB,oT,Di,aB,lB,sy,cB,dB,pB,iy,rT=ie(()=>{"use strict";Ge();Xu();_i=require("lucide");ao();Gr();Ai();Ra();ry();iB=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),oT=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Di=(e,t)=>{oT(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},aB=e=>e?.approval!==!1?e?.approval:void 0,lB=(e,t,n)=>{let o=n?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},sy=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},cB=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Kr)?Yu(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let i=r??Bi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=i,n.appendChild(c),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},dB=e=>{let t=v("div","persona-approval-resolved"),n=Je(_i.Ban,15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?Bi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},pB=(e,t,n,o,r,s,i,l,c=!1)=>{let d=v("div","persona-approval-card persona-shadow-sm");d.id=`bubble-${n.id}`,d.setAttribute("data-message-id",n.id),d.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(d.style.background=r.backgroundColor),r?.borderColor&&(d.style.borderColor=r.borderColor),r?.shadow!==void 0&&(d.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",f=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden"&&!c,g=f||m,h=g&&lB(n.id,t,r),b=r?.showDetailsLabel??"Show details",C=r?.hideDetailsLabel??"Hide details",A=v("button","persona-approval-head");A.type="button",g?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",h?"true":"false"),A.setAttribute("aria-label",h?C:b)):A.setAttribute("data-static","true");let S=v("span","persona-approval-logo"),E=Je(_i.ShieldCheck,16,"currentColor",2);E&&S.appendChild(E),A.appendChild(S);let k=cB(o,r);if(g){let L=v("span","persona-approval-toggle");L.setAttribute("aria-hidden","true");let w=Je(_i.ChevronDown,14,"currentColor",2);w&&L.appendChild(w),k.append(" "),k.appendChild(L)}A.appendChild(k),d.appendChild(A);let D=v("div","persona-approval-body");if(g){let L=v("div","persona-approval-details");if(L.setAttribute("data-role","params"),L.hidden=!h,f){let w=v("p","persona-approval-desc");r?.descriptionColor&&(w.style.color=r.descriptionColor),w.textContent=o.description,L.appendChild(w)}if(m){let w=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(w.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(w.style.color=r.parameterTextColor),w.textContent=tr(o.parameters),L.appendChild(w)}D.appendChild(L)}if(c){let L=v("div","persona-approval-call");L.setAttribute("data-role","raw-call");let w=v("code","persona-approval-tool-name");if(w.textContent=o.toolName,L.appendChild(w),o.parameters!=null){let x=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(x.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(x.style.color=r.parameterTextColor),x.textContent=tr(o.parameters),L.appendChild(x)}D.appendChild(L)}if(o.reason){let L=v("p","persona-approval-reason");r?.reasonColor?L.style.color=r.reasonColor:r?.descriptionColor&&(L.style.color=r.descriptionColor);let w=v("span","persona-approval-reason-label");w.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,L.append(w,document.createTextNode(o.reason)),D.appendChild(L)}let z=v("div","persona-approval-actions"),Y=null,T=L=>{r?.approveButtonColor&&(L.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(L.style.color=r.approveButtonTextColor)},W=v("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r?.denyButtonColor&&(W.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append(r?.denyLabel??"Deny"),l){let L=v("div","persona-approval-split"),w=v("button","persona-approval-primary");w.type="button",w.setAttribute("data-action","always"),T(w),w.append(r?.approveLabel??"Always allow",sy("\u23CE"));let x=v("button","persona-approval-caret");x.type="button",x.setAttribute("data-action","toggle-menu"),x.setAttribute("aria-label","More options"),T(x);let P=Je(_i.ChevronDown,15,"currentColor",2);P&&x.appendChild(P),L.append(w,x),z.append(L,W),W.append(sy("Esc"));let I=v("div","persona-approval-menu"),J=v("button","persona-approval-menu-item");J.type="button",J.append("Allow once",sy("\u2318\u23CE")),I.appendChild(J),Y=Bs({anchor:L,content:I,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(n.id,Y),J.addEventListener("click",()=>{Di(e,n.id),s()})}else{let L=v("button","persona-approval-primary persona-approval-primary--solo");L.type="button",L.setAttribute("data-action","allow"),T(L),L.append(r?.approveLabel??"Allow"),z.append(L,W)}return D.appendChild(z),d.appendChild(D),d.addEventListener("click",L=>{let w=L.target instanceof Element?L.target.closest("[data-action]"):null;if(!w)return;let x=w.getAttribute("data-action");if(x==="toggle-params"){let P=d.querySelector('[data-role="params"]');if(P){let I=P.hidden;P.hidden=!I,A.setAttribute("aria-expanded",I?"true":"false"),A.setAttribute("aria-label",I?C:b),t.set(n.id,I)}return}if(x==="toggle-menu"){Y?.toggle();return}if(x==="always"){Di(e,n.id),s({remember:!0});return}if(x==="allow"){Di(e,n.id),s();return}if(x==="deny"){Di(e,n.id),i();return}}),d},iy=(e=new Map)=>{let t=iB();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:i,config:l})=>{let c=r?.approval;if(!c)return null;let d=aB(l);if(c.status!=="pending"){if(Di(t,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return dB(c)}oT(t,r.id);let p=!!l?.clientToken,f=d?.enableAlwaysAllow===!0,m=pB(t,e,r,c,d,s,i,f,p);if(f){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=h=>{Hx(h)||r.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Di(t,r.id),h.key==="Escape"?i():h.metaKey||h.ctrlKey?s():s({remember:!0})))};t.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Di(t,r);t.latestPendingApprovalId=null}}}});var sT=ie(()=>{"use strict";ry();rT();Xu()});var iT={};En(iT,{createApprovalBubble:()=>oy,createBuiltInApprovalPlugin:()=>iy,humanizeToolName:()=>Bi,initApprovalUi:()=>ty,updateApprovalDetailsUI:()=>ny});var aT=ie(()=>{"use strict";sT()});function za(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}function dT(e,t){if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n]}function yB(e,t){return(t&&dT(e,t))??dT(e,es)??mB}function bB(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function vB(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function CB(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function wB(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function xB(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function SB(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function AB(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function MB(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function TB(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function ay(e,t,n,o,r,s,i,l){let c=r.has(e.id),d=v("div","persona-border-b persona-border-persona-divider persona-text-xs");za(d,o.classNames?.eventRow);let p=i.find(m=>m.renderEventStreamRow);if(p?.renderEventStreamRow&&l){let m=p.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>s(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(f()),d;function f(){let m=v("div",""),g=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let h=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=Je(c?qn.ChevronDown:qn.ChevronRight,"14px","currentColor",2);b&&h.appendChild(b);let C=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=o.timestampFormat??"relative";C.textContent=A==="relative"?vB(e.timestamp,n):CB(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let E=yB(e.type,o.badgeColors),k=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=bB(E.text),k.textContent=e.type;let D=o.descriptionFields??gB,z=wB(e.payload,D),Y=null;z&&(Y=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=z);let T=v("div","persona-flex-1 persona-min-w-0"),W=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),L=Je(qn.Clipboard,"12px","currentColor",1.5);return L&&W.appendChild(L),W.addEventListener("click",async w=>{w.stopPropagation(),await xB(SB(e)),W.innerHTML="";let x=Je(qn.Check,"12px","currentColor",1.5);x&&W.appendChild(x),setTimeout(()=>{W.innerHTML="";let P=Je(qn.Clipboard,"12px","currentColor",1.5);P&&W.appendChild(P)},1500)}),g.appendChild(h),g.appendChild(C),S&&g.appendChild(S),g.appendChild(k),Y&&g.appendChild(Y),g.appendChild(T),g.appendChild(W),m.appendChild(g),c&&m.appendChild(TB(e,i,l)),m}}function ly(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=e,l=e.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,d=c?.enabled!==!1,p=c?.iconName??"arrow-down",f=c?.label??"",m=r?.features?.eventStream??{},g=s.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>h().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return h();function h(){let b=m.classNames,C=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");za(C,b?.panel);let A=[],S="",E="",k=null,D=[],z={},Y=0,T=Hu(),W=0,L=0,w=!1,x=null,P=!1,I=0,J=new Set,_=new Map,j="",te="",K=null,X,oe,de,xe,Te=null,re=null,N=null;function ke(){let Ee=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),He=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(za(He,b?.headerBar),i){re=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),re.style.cursor="help",Te=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Te.textContent="-- tok/s",N=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),N.style.display="none",N.style.pointerEvents="none";let gn=re,Zn=N,ss=()=>{if(!Zn.textContent)return;let qs=gn.getBoundingClientRect(),oo=Ee.getBoundingClientRect();Zn.style.left=`${qs.left-oo.left}px`,Zn.style.top=`${qs.bottom-oo.top+4}px`,Zn.style.display="block"},jn=()=>{Zn.style.display="none"};re.addEventListener("mouseenter",ss),re.addEventListener("mouseleave",jn),re.appendChild(Te)}let je=v("div","persona-flex-1");X=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let It=v("option","");It.value="",It.textContent="All events (0)",X.appendChild(It),oe=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),oe.type="button",oe.title="Copy All";let nn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);nn&&oe.appendChild(nn);let Ot=v("span","persona-event-copy-all persona-text-xs");Ot.textContent="Copy All",oe.appendChild(Ot),re&&He.appendChild(re),He.appendChild(je),He.appendChild(X),He.appendChild(oe);let mt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");za(mt,b?.searchBar);let Ht=Je(qn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),St=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ht&&St.appendChild(Ht),de=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),za(de,b?.searchInput),de.type="text",de.placeholder="Search event payloads...",xe=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),xe.type="button",xe.style.display="none";let Kt=Je(qn.X,"12px","currentColor",2);return Kt&&xe.appendChild(Kt),mt.appendChild(St),mt.appendChild(de),mt.appendChild(xe),Ee.appendChild(He),Ee.appendChild(mt),N&&Ee.appendChild(N),Ee}let ve,tt=s.find(Ee=>Ee.renderEventStreamToolbar);tt?.renderEventStreamToolbar&&r?ve=tt.renderEventStreamToolbar({config:r,defaultRenderer:()=>ke(),eventCount:t.getSize(),filteredCount:0,onFilterChange:He=>{S=He,Z(),Ie()},onSearchChange:He=>{E=He,Z(),Ie()}})??ke():ve=ke();let xt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");xt.style.display="none";function ht(){if(!i||!Te||!re)return;let Ee=i(),He=AB(Ee);Te.textContent=He;let je=MB(Ee);N&&(N.textContent=je,je||(N.style.display="none")),re.setAttribute("aria-label",je?`Throughput: ${He}, ${je}`:`Throughput: ${He}`)}let lt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Ye=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ye.style.height="100%";let dt=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");za(dt,b?.scrollIndicator),dt.style.display="none",dt.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let Pe=l(p,"14px","currentColor",2);Pe&&dt.appendChild(Pe);let Se=v("span","");Se.textContent=f,dt.appendChild(Se);let U=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");U.style.display="none",lt.appendChild(Ye),lt.appendChild(U),lt.appendChild(dt),C.setAttribute("tabindex","0"),C.appendChild(ve),C.appendChild(xt),C.appendChild(lt);function R(){let Ee=t.getAll(),He={};for(let mt of Ee)He[mt.type]=(He[mt.type]||0)+1;let je=Object.keys(He).sort(),It=je.length!==D.length||!je.every((mt,Ht)=>mt===D[Ht]),wn=!It&&je.some(mt=>He[mt]!==z[mt]),nn=Ee.length!==Object.values(z).reduce((mt,Ht)=>mt+Ht,0);if(!It&&!wn&&!nn||(D=je,z=He,!X))return;let Ot=X.value;if(X.options[0].textContent=`All events (${Ee.length})`,It){for(;X.options.length>1;)X.remove(1);for(let mt of je){let Ht=v("option","");Ht.value=mt,Ht.textContent=`${mt} (${He[mt]||0})`,X.appendChild(Ht)}Ot&&je.includes(Ot)?X.value=Ot:Ot&&(X.value="",S="")}else for(let mt=1;mt<X.options.length;mt++){let Ht=X.options[mt];Ht.textContent=`${Ht.value} (${He[Ht.value]||0})`}}function G(){let Ee=t.getAll();if(S&&(Ee=Ee.filter(He=>He.type===S)),E){let He=E.toLowerCase();Ee=Ee.filter(je=>je.type.toLowerCase().includes(He)||je.payload.toLowerCase().includes(He))}return Ee}function ne(){return S!==""||E!==""}function Z(){Y=0,W=0,T.resume(),dt.style.display="none"}function le(Ee){J.has(Ee)?J.delete(Ee):J.add(Ee),K=Ee;let He=Ye.scrollTop,je=T.isFollowing();P=!0,T.pause(),Ie(),Ye.scrollTop=He,je&&T.resume(),P=!1}function Me(){return Zr(Ye,50)}function Ie(){L=Date.now(),w=!1,ht(),R();let Ee=t.getEvictedCount();Ee>0?(xt.textContent=`${Ee.toLocaleString()} older events truncated`,xt.style.display=""):xt.style.display="none",A=G();let He=A.length,je=t.getSize()>0;He===0&&je&&ne()?(U.textContent=E?`No events matching '${E}'`:"No events matching filter",U.style.display="",Ye.style.display="none"):(U.style.display="none",Ye.style.display=""),oe&&(oe.title=ne()?`Copy Filtered (${He})`:"Copy All"),d&&!T.isFollowing()&&He>Y&&(W+=He-Y,Se.textContent=f?`${f}${W>0?` (${W})`:""}`:"",dt.style.display=""),Y=He;let It=t.getAll(),wn=It.length>0?It[0].timestamp:0,nn=new Set(A.map(Ht=>Ht.id));for(let Ht of J)nn.has(Ht)||J.delete(Ht);let Ot=S!==j||E!==te,mt=_.size===0&&A.length>0;if(Ot||mt||A.length===0){Ye.innerHTML="",_.clear();let Ht=document.createDocumentFragment();for(let St=0;St<A.length;St++){let Kt=ay(A[St],St,wn,m,J,le,s,r);_.set(A[St].id,Kt),Ht.appendChild(Kt)}Ye.appendChild(Ht),j=S,te=E,K=null}else{if(K!==null){let St=_.get(K);if(St&&St.parentNode===Ye){let Kt=A.findIndex(gn=>gn.id===K);if(Kt>=0){let gn=ay(A[Kt],Kt,wn,m,J,le,s,r);Ye.insertBefore(gn,St),St.remove(),_.set(K,gn)}}K=null}let Ht=new Set(A.map(St=>St.id));for(let[St,Kt]of _)Ht.has(St)||(Kt.remove(),_.delete(St));for(let St=0;St<A.length;St++){let Kt=A[St];if(!_.has(Kt.id)){let gn=ay(Kt,St,wn,m,J,le,s,r);_.set(Kt.id,gn),Ye.appendChild(gn)}}}T.isFollowing()&&(Ye.scrollTop=Ye.scrollHeight)}function _e(){if(Date.now()-L>=hB){x!==null&&(cancelAnimationFrame(x),x=null),Ie();return}w||(w=!0,x=requestAnimationFrame(()=>{x=null,Ie()}))}let ct=(Ee,He)=>{if(!oe)return;oe.innerHTML="";let je=Je(Ee,"12px","currentColor",1.5);je&&oe.appendChild(je);let It=v("span","persona-text-xs");It.textContent="Copy All",oe.appendChild(It),setTimeout(()=>{oe.innerHTML="";let wn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);wn&&oe.appendChild(wn);let nn=v("span","persona-text-xs");nn.textContent="Copy All",oe.appendChild(nn),oe.disabled=!1},He)},Tt=async()=>{if(oe){oe.disabled=!0;try{let Ee;ne()?Ee=A:n?(Ee=await n(),Ee.length===0&&(Ee=t.getAll())):Ee=t.getAll();let He=Ee.map(je=>{try{return JSON.parse(je.payload)}catch{return je.payload}});await navigator.clipboard.writeText(JSON.stringify(He,null,2)),ct(qn.Check,1500)}catch{ct(qn.X,1500)}}},qe=()=>{X&&(S=X.value,Z(),Ie())},nt=()=>{!de||!xe||(xe.style.display=de.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{E=de.value,Z(),Ie()},150))},Ut=()=>{!de||!xe||(de.value="",E="",xe.style.display="none",k&&clearTimeout(k),Z(),Ie())},tn=()=>{if(P)return;let Ee=Ye.scrollTop,{action:He,nextLastScrollTop:je}=Ru({following:T.isFollowing(),currentScrollTop:Ee,lastScrollTop:I,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});I=je,He==="resume"?(T.resume(),W=0,dt.style.display="none"):He==="pause"&&(T.pause(),d&&(Se.textContent=f,dt.style.display=""))},ee=Ee=>{let He=Wu({following:T.isFollowing(),deltaY:Ee.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});He==="pause"?(T.pause(),d&&(Se.textContent=f,dt.style.display="")):He==="resume"&&(T.resume(),W=0,dt.style.display="none")},Re=()=>{d&&(Ye.scrollTop=Ye.scrollHeight,T.resume(),W=0,dt.style.display="none")},Fe=Ee=>{let He=Ee.target;if(!He||He.closest("button"))return;let je=He.closest("[data-event-id]");if(!je)return;let It=je.getAttribute("data-event-id");It&&le(It)},yt=Ee=>{if((Ee.metaKey||Ee.ctrlKey)&&Ee.key==="f"){Ee.preventDefault(),de?.focus(),de?.select();return}Ee.key==="Escape"&&(de&&document.activeElement===de?(Ut(),de.blur(),C.focus()):o&&o())};oe&&oe.addEventListener("click",Tt),X&&X.addEventListener("change",qe),de&&de.addEventListener("input",nt),xe&&xe.addEventListener("click",Ut),Ye.addEventListener("scroll",tn),Ye.addEventListener("wheel",ee,{passive:!0}),Ye.addEventListener("click",Fe),dt.addEventListener("click",Re),C.addEventListener("keydown",yt);function bt(){k&&clearTimeout(k),x!==null&&(cancelAnimationFrame(x),x=null),w=!1,_.clear(),oe&&oe.removeEventListener("click",Tt),X&&X.removeEventListener("change",qe),de&&de.removeEventListener("input",nt),xe&&xe.removeEventListener("click",Ut),Ye.removeEventListener("scroll",tn),Ye.removeEventListener("wheel",ee),Ye.removeEventListener("click",Fe),dt.removeEventListener("click",Re),C.removeEventListener("keydown",yt)}return{element:C,update:_e,destroy:bt}}}var qn,es,mB,gB,hB,pT=ie(()=>{"use strict";Ge();qn=require("lucide");ao();Sh();es={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};es.execution_error=es.error;es.execution_=es.flow_;es.turn_=es.agent_;es.text_=es.agent_;mB={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},gB=["flowName","stepName","reasoningText","text","name","tool","toolName"],hB=100});var Ec,uT=ie(()=>{"use strict";Ec=class{#e;#t=0;#n=0;#o=0;#a=new Set;#r;#s;constructor(t=2e3,n=null){this.#r=t,this.#e=new Array(t),this.#s=n}push(t){this.#e[this.#t]=t,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#o++,this.#a.add(t.type),this.#s?.put(t)}getAll(){return this.#n===0?[]:this.#n<this.#r?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#r),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#s)return 0;let t=await this.#s.getAll();if(t.length===0)return 0;let n=t.length>this.#r?t.slice(t.length-this.#r):t;for(let o of n)this.#e[this.#t]=o,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#a.add(o.type);return this.#o=t.length,n.length}getAllFromStore(){return this.#s?this.#s.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.#n}getTotalCaptured(){return this.#o}getEvictedCount(){return this.#o-this.#n}clear(){this.#e=new Array(this.#r),this.#t=0,this.#n=0,this.#o=0,this.#a.clear(),this.#s?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#o=0,this.#a.clear(),this.#s?.destroy()}getEventTypes(){return Array.from(this.#a)}}});var kc,fT=ie(()=>{"use strict";kc=class{#e=null;#t=[];#n=!1;#o=!1;#a;#r;constructor(t="persona-event-stream",n="events"){this.#a=t,this.#r=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.#a,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.#r)||r.createObjectStore(this.#r,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.#e=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.#e||this.#o||(this.#t.push(t),this.#n||(this.#n=!0,queueMicrotask(()=>this.#s())))}putBatch(t){if(!(!this.#e||this.#o||t.length===0))try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.#e){t([]);return}try{let i=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.#e){t(0);return}try{let s=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.#e){t();return}this.#t=[];try{let s=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.#e&&(this.#e.close(),this.#e=null)}destroy(){return this.#o=!0,this.#t=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.#a);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}#s(){if(this.#n=!1,!this.#e||this.#o||this.#t.length===0)return;let t=this.#t;this.#t=[];try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}}});function cy(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Qu(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function LB(e,t){return typeof t.type=="string"?t.type:e}function gT(e){let t=mT(e,"tokens")??mT(e,"totalTokens");return t?yT(t.output):void 0}function PB(e){return yT(e.durationMs)}function IB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var EB,kB,hT,yT,mT,Lc,bT=ie(()=>{"use strict";EB=new Set(["step_start","turn_start"]),kB=new Set(["step_complete","turn_complete"]),hT=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yT=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,mT=(e,t)=>{let n=e[t];return hT(n)?n:void 0};Lc=class{#e={status:"idle"};#t=null;constructor(t=IB){this.now=t}getMetric(){let t=this.#t;if(t&&this.#e.status==="running"&&t.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.#e,durationMs:n,tokensPerSecond:Qu(this.#e.outputTokens,n)}}return this.#e}reset(){this.#t=null,this.#e={status:"idle"}}#n(t){this.#t={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.#e={status:"running"}}processEvent(t,n){if(!hT(n)){t==="execution_error"&&this.#t&&(this.#t=null,this.#e={status:"error"});return}let o=LB(t,n),r=this.now();if(o==="execution_start"){this.#n(r);return}if(EB.has(o)){this.#t||this.#n(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.#t||this.#n(r);let i=this.#t;i.firstDeltaAt??=r,i.visibleCharCount+=s.length;let l=i.exactOutputTokens+cy(i.visibleCharCount),c=r-i.firstDeltaAt;this.#e={status:"running",tokensPerSecond:Qu(l,c),outputTokens:l,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(kB.has(o)){if(!this.#t)return;let s=this.#t,i=gT(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+cy(s.visibleCharCount),d=this.#o(s,n,r);this.#e={status:"running",tokensPerSecond:Qu(c,d),outputTokens:c,durationMs:d,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.#t)return;let s=this.#t,i=gT(n),l=i??s.exactOutputTokens+cy(s.visibleCharCount),c=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.#o(s,n,r);this.#e={status:"complete",tokensPerSecond:Qu(l,d),outputTokens:l,durationMs:d,source:c},this.#t=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:"error"}}}#o(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:PB(n)??o-t.startedAt}}});var vT=ie(()=>{"use strict";pT();uT();fT();bT()});var CT={};En(CT,{EventStreamBuffer:()=>Ec,EventStreamStore:()=>kc,ThroughputTracker:()=>Lc,createEventStreamView:()=>ly});var wT=ie(()=>{"use strict";vT()});var py,sr,Pc=ie(()=>{"use strict";py=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},sr=new py});function Sr(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function xT(e){let t=Sr(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ju(e){if(typeof e!="string")return"";let t=e.indexOf(`
259
259
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
260
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Oi(e){let t=wT(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Vs(e){switch(Oi(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=wT(e.path);return t?t.toUpperCase():"File"}}}function Ic(e){let t=e.markdown??"";return e.file?{filename:Sr(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ju(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}function Hc(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e.filename,o.click(),URL.revokeObjectURL(n)}var Ni=ie(()=>{"use strict"});function qa(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Zu+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+Zu+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=v("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Hi({icon:e.icon,label:e.label,className:Zu+(n?" persona-artifact-doc-copy-btn":"")}):o=Ln({icon:e.icon,label:e.label,className:Zu+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Rc(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}var Zu,ef=ie(()=>{"use strict";Ri();Ge();Zu="persona-artifact-custom-action-btn"});function xT(e){let t=document.createElementNS(uy,"svg");t.setAttribute("class",Jt("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(uy,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(uy,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var uy,ST=ie(()=>{"use strict";Ge();uy="http://www.w3.org/2000/svg"});function AT(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Fs(e,t,0)}var MT=ie(()=>{"use strict";Gu()});function ja(e){e&&my.delete(e)}function HB(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Vs(t):e.artifactType==="component"?"Component":"Document"}function Ka(e,t,n){let o=HB(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=e.id,l=my.get(i);e.status!=="complete"&&l===void 0&&(l=kT(),my.set(i,l));let c=l===void 0?0:Math.max(0,kT()-l),d=e.artifactType==="component",p=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:p.length,m=d||p===""?0:p.split(`
261
- `).length,g=e.artifactType==="markdown"?e.file:void 0,h={artifactId:i,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:f,lines:m,elapsedMs:c,content:()=>d?"":p,surface:n};try{let b=s(h);return typeof b=="string"?{label:b}:b&&typeof b=="object"&&typeof b.label=="string"?{label:b.label,detail:typeof b.detail=="string"?b.detail:void 0}:{label:r}}catch{return{label:r}}}function RB(e){e.className=fy,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Fi(e,t,n){let o=e.querySelector(`:scope > .${fy}`);o||(o=v("span",fy),e.appendChild(o)),o.getAttribute(ET)!==t.label&&(RB(o),AT(o,t.label,n),o.setAttribute(ET,t.label));let r=e.querySelector(`:scope > .${TT}`),s=t.detail;s?(r||(r=v("span",TT),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var fy,TT,ET,my,kT,tf=ie(()=>{"use strict";Ge();Ni();MT();fy="persona-artifact-status-label",TT="persona-artifact-status-detail",ET="data-artifact-status-label",my=new Map,kT=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function DB(e,t){let n=(e||"").trim().toLowerCase();if(n&&nf[n])return nf[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(nf[r])return nf[r]}}return null}function of(e,t){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:e.slice(r,i)})};for(;o<e.length;){let i=!1;for(let l of t){l.re.lastIndex=o;let c=l.re.exec(e);if(c&&c.index===o&&c[0].length>0){s(o);let d=l.map?l.map(c[0]):l.type;n.push({type:d,value:c[0]}),o+=c[0].length,r=o,i=!0;break}}i||(o+=1)}return s(e.length),n}function LT(e){return of(e,OB)}function FB(e){let t=of(e,NB);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}function PT(e){let t=of(e,VB),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<t.length&&t[i].value.trim()==="";)i+=1;let l=t[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}function UB(e){let t=[],n=(s,i)=>{i&&t.push({type:s,value:i})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let i=e.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let i=e.indexOf(">",r),l=i===-1?o:i+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let i=e.indexOf(">",r),l=i===-1?o:i+1,c=e.slice(r,l);for(let p of of(c,$B))t.push(p);r=l;let d=/^<\s*(script|style)\b/i.exec(c);if(d&&!/\/>\s*$/.test(c)){let p=d[1].toLowerCase(),m=new RegExp("</\\s*"+p+"\\s*>","i").exec(e.slice(r)),g=m?r+m.index:o,h=e.slice(r,g),b=p==="script"?LT(h):PT(h);for(let C of b)t.push(C);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let i=s===-1?o:s;n("plain",e.slice(r,i)),r=i}}return t}function zB(e,t){switch(t){case"html":return UB(e);case"css":return PT(e);case"js":return LT(e);case"json":return FB(e)}}function qB(e){let t=TC(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=WB[r];if(i){let l=v("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
260
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Oi(e){let t=xT(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Vs(e){switch(Oi(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=xT(e.path);return t?t.toUpperCase():"File"}}}function Ic(e){let t=e.markdown??"";return e.file?{filename:Sr(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ju(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}function Hc(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e.filename,o.click(),URL.revokeObjectURL(n)}var Ni=ie(()=>{"use strict"});function qa(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Zu+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+Zu+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=v("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Hi({icon:e.icon,label:e.label,className:Zu+(n?" persona-artifact-doc-copy-btn":"")}):o=Ln({icon:e.icon,label:e.label,className:Zu+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Rc(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}var Zu,ef=ie(()=>{"use strict";Ri();Ge();Zu="persona-artifact-custom-action-btn"});function ST(e){let t=document.createElementNS(uy,"svg");t.setAttribute("class",Jt("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(uy,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(uy,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var uy,AT=ie(()=>{"use strict";Ge();uy="http://www.w3.org/2000/svg"});function MT(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Fs(e,t,0)}var TT=ie(()=>{"use strict";Gu()});function ja(e){e&&my.delete(e)}function RB(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Vs(t):e.artifactType==="component"?"Component":"Document"}function Ka(e,t,n){let o=RB(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=e.id,l=my.get(i);e.status!=="complete"&&l===void 0&&(l=LT(),my.set(i,l));let c=l===void 0?0:Math.max(0,LT()-l),d=e.artifactType==="component",p=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:p.length,m=d||p===""?0:p.split(`
261
+ `).length,g=e.artifactType==="markdown"?e.file:void 0,h={artifactId:i,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:f,lines:m,elapsedMs:c,content:()=>d?"":p,surface:n};try{let b=s(h);return typeof b=="string"?{label:b}:b&&typeof b=="object"&&typeof b.label=="string"?{label:b.label,detail:typeof b.detail=="string"?b.detail:void 0}:{label:r}}catch{return{label:r}}}function WB(e){e.className=fy,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Fi(e,t,n){let o=e.querySelector(`:scope > .${fy}`);o||(o=v("span",fy),e.appendChild(o)),o.getAttribute(kT)!==t.label&&(WB(o),MT(o,t.label,n),o.setAttribute(kT,t.label));let r=e.querySelector(`:scope > .${ET}`),s=t.detail;s?(r||(r=v("span",ET),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var fy,ET,kT,my,LT,tf=ie(()=>{"use strict";Ge();Ni();TT();fy="persona-artifact-status-label",ET="persona-artifact-status-detail",kT="data-artifact-status-label",my=new Map,LT=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function _B(e,t){let n=(e||"").trim().toLowerCase();if(n&&nf[n])return nf[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(nf[r])return nf[r]}}return null}function of(e,t){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:e.slice(r,i)})};for(;o<e.length;){let i=!1;for(let l of t){l.re.lastIndex=o;let c=l.re.exec(e);if(c&&c.index===o&&c[0].length>0){s(o);let d=l.map?l.map(c[0]):l.type;n.push({type:d,value:c[0]}),o+=c[0].length,r=o,i=!0;break}}i||(o+=1)}return s(e.length),n}function PT(e){return of(e,NB)}function VB(e){let t=of(e,FB);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}function IT(e){let t=of(e,$B),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<t.length&&t[i].value.trim()==="";)i+=1;let l=t[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}function zB(e){let t=[],n=(s,i)=>{i&&t.push({type:s,value:i})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let i=e.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let i=e.indexOf(">",r),l=i===-1?o:i+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let i=e.indexOf(">",r),l=i===-1?o:i+1,c=e.slice(r,l);for(let p of of(c,UB))t.push(p);r=l;let d=/^<\s*(script|style)\b/i.exec(c);if(d&&!/\/>\s*$/.test(c)){let p=d[1].toLowerCase(),m=new RegExp("</\\s*"+p+"\\s*>","i").exec(e.slice(r)),g=m?r+m.index:o,h=e.slice(r,g),b=p==="script"?PT(h):IT(h);for(let C of b)t.push(C);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let i=s===-1?o:s;n("plain",e.slice(r,i)),r=i}}return t}function qB(e,t){switch(t){case"html":return zB(e);case"css":return IT(e);case"js":return PT(e);case"json":return VB(e)}}function jB(e){let t=TC(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=BB[r];if(i){let l=v("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
262
262
  `);for(let i=0;i<s.length;i+=1)i>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
263
- `)),n=v("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function IT(e,t,n){let o=e.length<=BB?DB(t,n):null,r=o?zB(e,o):[{type:"plain",value:e}];return qB(r)}var WB,BB,nf,_B,OB,NB,VB,$B,HT=ie(()=>{"use strict";Ge();WB={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},BB=15e4,nf={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};_B=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),OB=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>_B.has(e)?"keyword":"plain"}];NB=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];VB=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];$B=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}]});var RT,gy,WT,hy=ie(()=>{"use strict";RT=null,gy=e=>{RT=e.componentRegistry},WT=()=>RT});function Wc(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ju(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}function jB(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function BT(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||yy||s){o();return}yy=!0;let i=jB(n);e.style.setProperty("view-transition-name",i);let l=()=>{yy=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function YB(e){let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function XB(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}function JB(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function ZB(e){return`
264
- <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function eD(e,t,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(xT());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function tD(e,t,n,o,r,s){let i=null,l=0,c=!1,d=new Set,p=()=>{d.forEach(E=>clearTimeout(E)),d.clear()},f=(E,k)=>{let D=setTimeout(()=>{d.delete(D),!(typeof document>"u")&&E()},k);d.add(D)},m=()=>{i&&i.parentElement&&i.remove(),i=null},g=()=>{if(i||c)return;let E=eD(r,s,o);i=E.el,e.appendChild(i),l=Date.now(),o.label!==!1&&f(E.revealLabel,o.labelDelayMs)},h=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),f(m,QB))},b=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",A):t.removeEventListener("load",S)},C=()=>{if(c||(c=!0,b(),p(),!i))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-l));E>0?f(h,E):h()};function A(E){if(n===null)return;let k=E.data;!k||k.persona!=="artifact-preview-ready"||k.token!==n||E.source===t.contentWindow&&C()}function S(){let E=k=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>k()):setTimeout(k,0)};E(()=>E(()=>C()))}return f(g,o.delayMs),f(C,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",A):t.addEventListener("load",S),()=>{c=!0,p(),b(),m()}}function rf(e,t){let{config:n}=t,o=t.registry??WT()??sr,r=t.bodyLayout,s=n.markdown?ip(n.markdown):null,i=lp(n.sanitize),l=e,c=!1,d=j=>{let te=Oo()!==null;s&&!te&&!c&&(c=!0,va(()=>_(l)));let K=s?s(j):jr(j);return s&&te&&i?i(K):K},p=v("div","persona-artifact-preview-body"),f=null,m=null,g=null,h=()=>{g&&(g(),g=null),f=null,m=null},b=null,C=null,A=null,S=!1,E=()=>{b=null,C=null,A=null,S=!1},k=null,D=null,z=()=>{k=null,D=null},Y=40,T=0,W=j=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>j()):setTimeout(j,0),L=j=>j.scrollHeight-j.clientHeight-j.scrollTop<=Y,w=j=>{if(!r)return;let te=j.scrollHeight-j.clientHeight>1,K=j.scrollHeight-j.clientHeight-j.scrollTop;j.classList.toggle("persona-artifact-fade-top",r.fadeTop&&te&&j.scrollTop>1),j.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&te&&K>1)},x=j=>{T||(T=W(()=>{T=0,j.scrollTop=j.scrollHeight,w(j)}))},P=(j,te,K,X)=>{let oe=!!r,de=K.id+"|"+(oe?"w":"p");if(!b||A!==de||b.parentElement!==p){h(),z(),p.replaceChildren();let re=v("pre",KB+" persona-code-pre"),N=v("code","persona-code");if(re.appendChild(N),oe){let ke=v("div","persona-artifact-source-window");if(ke.appendChild(re),p.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let tt=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{L(ke)&&(S=!1),w(ke)},{passive:!0}),ke.addEventListener("wheel",xt=>{tt()&&xt.deltaY<0&&(S=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{tt()&&(S=!0)},{passive:!0})}b=ke}else p.appendChild(re),b=re;C=N,A=de}let xe=oe?b:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",X),xe.classList.toggle("persona-artifact-source-window--clip",X&&r?.overflow==="clip"));let Te=xe?L(xe):!0;if(C.replaceChildren(IT(j,te?.language,te?.path)),xe){let re=K.status!=="complete";X&&re&&r?.followOutput&&!S&&Te?x(xe):re||(S=!1),w(xe)}},I=j=>{h(),E(),z(),p.replaceChildren();let te=v("div",GB);te.innerHTML=d(j),p.appendChild(te)},J=j=>{let te=j.id,K=n.features?.artifacts,X=Ka(j,K,"status-body");if(k&&D===te&&k.parentElement===p){let xe=k.querySelector(".persona-artifact-status-view-text");xe&&Fi(xe,X,K);return}h(),E(),p.replaceChildren();let oe=v("div","persona-artifact-status-view"),de=v("div","persona-artifact-status-view-text");Fi(de,X,K),oe.appendChild(de),p.appendChild(oe),k=oe,D=te},_=j=>{l=j;let te=t.resolveViewMode?.(j)??r?.viewMode??"rendered",K=j.artifactType==="markdown"?j.file:void 0,X=j.status!=="complete";X||ja(j.id);let oe=X?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof oe=="number";if(r?.streamingView==="status"&&X){J(j);return}if(K){let Te=Ju(j.markdown??""),re=Oi(K),N=n.features?.artifacts?.filePreview?.enabled!==!1;if(!X&&te==="rendered"&&N&&(re==="html"||re==="svg")){let ve=j.id+"\0"+Te;if(f&&m===ve&&f.parentElement===p)return;E(),z(),h(),p.replaceChildren();let tt=n.features?.artifacts?.filePreview,xt=tt?.iframeSandbox??"allow-scripts";!tt?.dangerouslyAllowSameOrigin&&xt.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),xt=xt.split(/\s+/).filter(Pe=>Pe&&Pe!=="allow-same-origin").join(" "));let ht=XB(tt?.loading),lt=v("div","persona-artifact-frame"),Ye=v("iframe","persona-artifact-iframe");Ye.setAttribute("sandbox",xt),Ye.setAttribute("data-artifact-id",j.id);let dt=null;ht.enabled&&ht.injectReadySignal?(dt=JB(),Ye.srcdoc=Te+ZB(dt)):Ye.srcdoc=Te,lt.appendChild(Ye),p.appendChild(lt),ht.enabled&&(g=tD(lt,Ye,dt,ht,j.id,n)),f=lt,m=ve;return}if(h(),!X&&re==="markdown"&&te==="rendered"){I(Te);return}P(Te,{language:K.language,path:K.path},j,de);return}if(j.artifactType==="markdown"){if(te==="source"){h(),P(j.markdown??"",void 0,j,de);return}I(j.markdown??"");return}h(),E(),z(),p.replaceChildren();let xe=j.component?o.get(j.component):void 0;if(xe){let re={message:{id:j.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let N=xe(j.props??{},re);if(N){p.appendChild(N);return}}catch{}}p.appendChild(YB(j))};return _(e),{el:p,update(j){_(j)},destroy(){h()}}}var yy,KB,GB,QB,sf=ie(()=>{"use strict";Ge();ST();Ni();tf();HT();ap();Si();eg();Pc();hy();yy=!1;KB="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",GB="persona-text-sm persona-leading-relaxed persona-markdown-bubble";QB=220});function DT(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},c=f=>{let m=f;return s.findIndex(g=>g===m||g.contains(m))},d=f=>{let m=c(f.target);if(m<0)return;let g=m;if(f.key===r)g=Math.min(m+1,s.length-1);else if(f.key===o)g=Math.max(m-1,0);else if(f.key==="Home")g=0;else if(f.key==="End")g=s.length-1;else return;f.preventDefault(),g!==m&&t.onSelect(g)},p=f=>{let m=c(f.target);m>=0&&l(s[m])};return e.addEventListener("keydown",d),e.addEventListener("focusin",p),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(f,m){if(s=f,f.forEach((g,h)=>{g.setAttribute("role","tab");let b=h===m;g.setAttribute("aria-selected",b?"true":"false"),g.tabIndex=b||m<0&&h===0?0:-1}),i){let g=(m>=0?f[m]:void 0)??f[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",p)}}}var _T=ie(()=>{"use strict"});function by(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),c=n?.tabFadeSize?.trim(),d=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:p,end:f}=d(n?.tabFade),m=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{m?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),w?.closeMenu()};m&&m.addEventListener("click",()=>{g(),t.onDismiss?.()});let h=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let b=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");b.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&b.classList.add("persona-artifact-toolbar-document");let C=v("span","persona-text-xs persona-font-medium persona-truncate");C.textContent=s;let A=Ln({icon:"x",label:i});A.addEventListener("click",()=>{g(),t.onDismiss?.()});let S="rendered",E=Nu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{S=ee==="source"?"source":"rendered",nt()}}),k=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,z=n?.documentToolbarShowCopyChevron===!0,Y=n?.documentToolbarCopyMenuItems,T=!!(z&&Y&&Y.length>0),W=null,L,w=null;if(r&&(D||z)&&!T){if(L=D?Hi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),z){let ee=Je($s.ChevronDown,14,"currentColor",2);ee&&L.appendChild(ee)}}else r&&T?(w=CM({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(Y??[]).map(ee=>({id:ee.id,label:ee.label})),position:"bottom-right",portal:()=>h.closest("[data-persona-root]")??document.body,onSelect:ee=>{xe(ee)}}),W=w.element,L=w.primaryButton):r?L=Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(L=Ln({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&L.classList.add("persona-hidden"));let x=r?Ln({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ln({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||x.classList.add("persona-hidden");let P=r?Ln({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Ln({icon:"x",label:i}),I=Ln({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&I.classList.add("persona-hidden");let J=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),_=e.features?.artifacts?.toolbarActions??[],j=()=>{let ee=Pe.find(je=>je.id===Se)??Pe[Pe.length-1],Re=ee?.id??null,Fe=ee?.artifactType==="markdown"?ee.markdown??"":"",yt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"",{filename:bt,mime:Ee,content:He}=Ic({title:ee?.title,markdown:ee?.markdown??"",file:ee?.file});return{markdown:Fe,jsonPayload:yt,id:Re,file:ee?.file,suggestedFilename:bt,mime:Ee,content:He}},te=()=>{let{suggestedFilename:ee,mime:Re,content:Fe}=j();Fe&&Hc({filename:ee,mime:Re,content:Fe})},K=ee=>{let{id:Re,...Fe}=j();return{actionId:ee,artifactId:Re,...Fe}},X=async()=>{let ee=Pe.find(Re=>Re.id===Se)??Pe[Pe.length-1];try{return await navigator.clipboard.writeText(Wc(ee)),!0}catch{return!1}},oe=null,de=()=>{oe?.();let ee=L.querySelector("svg"),Re=Number(ee?.getAttribute("width"))||16,Fe=Je($s.Check,Re,"currentColor",2);if(!ee||!Fe)return;ee.replaceWith(Fe);let yt=L.querySelector("span");yt&&(yt.textContent="Copied");let bt=setTimeout(()=>oe?.(),2e3);oe=()=>{clearTimeout(bt),Fe.replaceWith(ee),yt&&(yt.textContent="Copy"),oe=null}};L.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&T){try{if(await ee(K("primary"))===!1){await X()&&de();return}de()}catch{}return}await X()&&de()});async function xe(ee){let Re=n?.onDocumentToolbarCopyMenuSelect;try{if(Re&&await Re(K(ee))!==!1)return;if(ee==="download"){te();return}let{markdown:Fe,jsonPayload:yt}=j();ee==="markdown"||ee==="md"?await navigator.clipboard.writeText(Fe):ee==="json"||ee==="source"?await navigator.clipboard.writeText(yt):await navigator.clipboard.writeText(Fe||yt),de()}catch{}}x.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}nt()}),P.addEventListener("click",()=>{g(),t.onDismiss?.()});let Te=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)b.replaceChildren(),W?k.append(W,x,P):k.append(L,x,P),k.insertBefore(J,P),k.insertBefore(I,P),b.append(E.element,Te,k);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(L,J,I,A),b.appendChild(C),b.appendChild(ee)}l&&(b.style.paddingLeft=l,b.style.paddingRight=l);let re=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");c&&re.style.setProperty("--persona-artifact-tab-fade-size",c);let N=e.features?.artifacts?.renderTabBar,ke=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ve=DT(re,{onSelect:ee=>t.onSelect(Pe[ee].id)}),tt=ee=>{let Re=ee.scrollWidth-ee.clientWidth,Fe=Re>1,yt=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",p&&Fe&&yt>1),ee.classList.toggle("persona-artifact-tab-fade-end",f&&Fe&&yt<Re-1)},xt=0,ht=()=>{if(xt)return;let ee=()=>{xt=0,tt(re)};xt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};re.addEventListener("scroll",()=>ht(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>tt(re)).observe(re);let lt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ye=()=>{lt.scrollLeft=0},dt=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ye):setTimeout(Ye,0)};if(l){for(let ee of[re,ke])ee.style.paddingLeft=l,ee.style.paddingRight=l;lt.style.padding=l}h.appendChild(b),h.appendChild(re),h.appendChild(ke),h.appendChild(lt);let Pe=[],Se=null,U=!1,R=!1,G=!0,ne=!1,Z=null,le="",Me=null,Ie=!1,_e=ee=>ee.artifactType==="markdown"&&!!ee.file||r?S:"rendered",ct=ee=>{r||(ee&&!Ie?(b.insertBefore(E.element,C),Ie=!0):!ee&&Ie&&(E.element.remove(),Ie=!1))},Tt=()=>Se&&Pe.find(ee=>ee.id===Se)||Pe[Pe.length-1],qe=()=>{let ee=Rc(Tt());if(!ee){J.replaceChildren();return}let Re=_.filter(Fe=>Fe.visible===void 0||Fe.visible(ee)).map(Fe=>qa(Fe,{documentChrome:r,onClick:()=>{let yt=Rc(Tt());if(yt)try{Promise.resolve(Fe.onClick(yt)).catch(()=>{})}catch{}}}));J.replaceChildren(...Re)},nt=()=>{qe();let ee=r&&Pe.length<=1,Re=!!N;if(re.classList.toggle("persona-hidden",ee||Re),ke.classList.toggle("persona-hidden",ee||!Re),Re&&N){let bt=Pe.map(Ee=>Ee.id).join("|")+" "+(Se??"");if(bt!==le){le=bt;let Ee=N({records:Pe,selectedId:Se,onSelect:t.onSelect});ke.firstElementChild!==Ee&&ke.replaceChildren(Ee)}}else{ve.beforeRender(),re.replaceChildren();let bt=[],Ee=-1;for(let[He,je]of Pe.entries()){let It=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");It.type="button";let wn=je.artifactType==="markdown"?je.file:void 0,nn=wn?Sr(wn.path):je.title||je.id.slice(0,8),Ot=wn?.path||je.title||nn;It.textContent=nn,It.title=Ot,It.setAttribute("aria-label",Ot),je.id===Se&&(It.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ee=He),It.addEventListener("click",()=>t.onSelect(je.id)),re.appendChild(It),bt.push(It)}if(ve.render(bt,Ee),Ee>=0&&Se!==Z){Z=Se;let He=bt[Ee];typeof He.scrollIntoView=="function"&&He.scrollIntoView({block:"nearest",inline:"nearest"})}tt(re)}let Fe=Se&&Pe.find(bt=>bt.id===Se)||Pe[Pe.length-1];if(!Fe){lt.replaceChildren(),Me?.destroy(),Me=null,ct(!1);return}let yt=Fe.artifactType==="markdown"?Fe.file:void 0;if(ct(!!yt&&Oi(yt)!=="other"),r){let bt=yt?Vs(yt):Fe.artifactType==="markdown"?"MD":Fe.component??"Component",Ee=(Fe.title||"Document").trim(),He=yt?Sr(yt.path):Ee.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Te.textContent=`${He} \xB7 ${bt}`}else C.textContent=yt?Sr(yt.path):s;Me?(Me.el.parentElement!==lt&&lt.replaceChildren(Me.el),Me.update(Fe)):(Me=rf(Fe,{config:e,resolveViewMode:_e}),lt.replaceChildren(Me.el)),lt.classList.toggle("persona-artifact-content-flush",!!lt.querySelector(".persona-code-pre"))},Ut=()=>{let ee=Pe.length>0;if(h.classList.toggle("persona-hidden",!ee),m){let yt=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&yt&&U?(m.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(m.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},tn=()=>{ne=!1,nt(),Ut()};return{element:h,backdrop:m,update(ee){let Re=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,Fe=Re!==Se;Pe=ee.artifacts,Se=Re,Pe.length>0&&(U=!0),ne=!0,G&&tn(),Fe&&Ye()},setMobileOpen(ee){U=ee,!ee&&m?(m.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):Ut()},setExpanded(ee){ee!==R&&(R=ee,dt());let Re=Je(ee?$s.Minimize:$s.Maximize,16,"currentColor",2);Re&&I.replaceChildren(Re);let Fe=ee?"Collapse artifacts panel":"Expand artifacts panel";I.setAttribute("aria-label",Fe),I.title=Fe},setExpandToggleVisible(ee){I.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||L.classList.toggle("persona-hidden",!ee)},setRefreshButtonVisible(ee){x.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){_=ee,qe()},setTabFade(ee){let Re=d(ee);Re.start===p&&Re.end===f||(p=Re.start,f=Re.end,tt(re))},setRenderTabBar(ee){ee!==N&&(N=ee,le="",nt())},setVisible(ee){ee!==G&&(G=ee,ee&&ne&&tn())},destroy(){Me?.destroy(),Me=null}}}var $s,OT=ie(()=>{"use strict";Ge();Ni();ef();sf();$s=require("lucide");ao();Ri();_T()});function NT(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Sr(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",i=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",c=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Vs(n):l==="component"?"Component":"Document",p=document.createElement("div");p.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&p.setAttribute("data-open-artifact",s);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let m=document.createElement("div");m.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let h=document.createElement("div");if(h.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",h.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let b=t?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},A=Ka(C,b,"card");Fi(h,A,b)}else s&&ja(s),h.textContent=d;if(m.append(g,h),p.append(f,m),i==="complete"){let b=t?.config?.features?.artifacts?.cardActions;if(b&&b.length>0){let A={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let S of b)try{if(S.visible===void 0||S.visible(A)){let E=qa(S);E.setAttribute("data-artifact-custom-action",S.id),E.className=`${E.className} persona-flex-shrink-0`,p.append(E)}}catch{}}let C=Hi({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),p.append(C)}return p}var Bc,vy=ie(()=>{"use strict";Ni();tf();Ri();ef();Bc=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>NT(e,t)});if(l)return l}return NT(e,t)}});function Cy(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Us.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function wy(e){return Us.has(e)}function nD(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let i=e.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function FT(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Sr(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Vs(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function oD(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}function dD(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let i=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:VT,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let A of i)A.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let c=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!c||Math.abs(c-t)<1){l(),r();return}let d=Math.abs(t-c),p=Math.round(Math.min(aD,Math.max(iD,rD+d*sD))),f=Math.round(p*cD),m=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=m?m.animate([{opacity:0},{opacity:1}],{duration:$T,delay:f,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${c}px`}],{duration:p,easing:lD});e.style.height=`${c}px`;let b=!1,C=()=>{b||(b=!0,l(),r())};Promise.allSettled([h.finished,g?.finished].filter(Boolean)).then(C),window.setTimeout(C,Math.max(p,f+$T)+120)},VT)}function pD(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function uD(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,i=t?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",c=l==="clip"?!1:t?.followOutput!==!1,d,p,f=t?.fadeMask;f===!0?(d=!0,p=!0):f===!1?(d=!1,p=!1):f&&typeof f=="object"?(d=f.top===!0,p=f.bottom===!0):l==="clip"?(d=!1,p=!0):(d=!0,p=!0);let m=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:c,overflow:l,fadeTop:d,fadeBottom:p,transition:m,completeDisplay:g}}function UT(e,t){let n=nD(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=pD(o),c=o?.inlineActions??[],d=uD(o),p=d.completeDisplay==="card",f=null,m=n,g=v("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let h=X=>Bc(oD(X),t),b=null,C=X=>{b?.destroy(),b=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Dc),g.replaceChildren(h(X)),Us.set(g,oe=>{g.replaceChildren(h(oe))})};if(p&&n.status==="complete")return C(n),g;let A=rf(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode});b=A;let S=v("div","persona-artifact-inline-body");S.appendChild(A.el);let E=X=>{let oe=X.status!=="complete",de=oe?d.streamingHeight:d.completeHeight,xe=typeof de=="number";xe?g.style.setProperty(Dc,`${de}px`):g.style.removeProperty(Dc);let Te=!!A.el.querySelector(".persona-code-pre"),re=!!A.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");S.classList.toggle("persona-artifact-content-flush",Te),S.classList.toggle("persona-artifact-inline-body--sized",xe&&re),S.classList.toggle("persona-artifact-inline-body--cap",!oe&&!re&&typeof d.completeHeight=="number")},k=n.status,D=(X,oe)=>{k!=="complete"&&X.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Dc,`${d.completeHeight}px`):g.style.removeProperty(Dc),BT(S,oe?.suppressTransition?"none":d.transition,X.id,()=>{A.update(X),E(X)})):A.update(X),E(X),k=X.status};E(n);let z=d.overflow==="clip"&&i&&!!n.id;if(z&&(S.setAttribute("data-expand-artifact-inline",n.id),S.setAttribute("role","button"),S.setAttribute("tabindex","0"),S.classList.add("persona-cursor-pointer"),S.setAttribute("aria-label",`Open ${FT(n).title} in panel`)),!r)return g.appendChild(S),Us.set(g,D),g;let Y=v("div","persona-artifact-inline-chrome");Y.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let T=v("div","persona-artifact-inline-chrome-lead"),W=v("span","persona-flex persona-items-center persona-flex-shrink-0"),L=Je(zT.FileText,16,"currentColor",2);L&&W.appendChild(L);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),x=v("span","persona-artifact-inline-type");T.append(W,w,x);let P=v("div","persona-artifact-inline-chrome-actions"),I=v("span","persona-flex persona-items-center persona-gap-1"),J=()=>f??d.viewMode,_=l?Nu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:J(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:X=>{let oe=X==="source"?"source":"rendered";oe!==J()&&(f=oe,A.update(m),E(m))}}):null,j=s?Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;j&&n.id&&j.setAttribute("data-copy-artifact",n.id);let te=i?Ln({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),P.appendChild(I),_&&P.appendChild(_.element),j&&P.appendChild(j),te&&P.appendChild(te),Y.append(T,P),g.append(Y,S);let K=X=>{let{title:oe,typeLabel:de}=FT(X);w.textContent=oe,w.title=oe,z&&S.setAttribute("aria-label",`Open ${oe} in panel`);let xe=X.status!=="complete";if(xe){x.classList.contains("persona-artifact-inline-status")||(x.className="persona-artifact-inline-status",x.removeAttribute("data-preserve-animation"),x.replaceChildren());let Te=Ka(X,o,"inline-chrome");Fi(x,Te,o)}else ja(X.id),x.className="persona-artifact-inline-type",x.removeAttribute("data-preserve-animation"),x.replaceChildren(),x.textContent=de;if(j&&j.classList.toggle("persona-hidden",xe),_){let Te=X.artifactType==="markdown"?X.file:void 0,re=!1;if(!xe&&Te&&d.viewMode!=="source"){let N=Oi(Te);N==="markdown"?re=!0:(N==="html"||N==="svg")&&(re=o?.filePreview?.enabled!==!1)}_.element.classList.toggle("persona-hidden",!re),_.setSelected(J())}if(I.replaceChildren(),!xe&&c.length>0){let Te=Rc(X);if(Te)for(let re of c)try{if(re.visible===void 0||re.visible(Te)){let N=qa(re,{documentChrome:!0});N.setAttribute("data-artifact-custom-action",re.id),N.classList.add("persona-flex-shrink-0"),I.appendChild(N)}}catch{}}};return K(n),Us.set(g,(X,oe)=>{if(p&&k!=="complete"&&X.status==="complete"){let de=g.isConnected?g.getBoundingClientRect().height:0;k="complete";let xe=X,Te=!1,re=N=>{xe=N,Te=!0};Us.set(g,re),dD(g,de,{swap:()=>{C(xe),Te=!1,Us.set(g,re)},onSettled:()=>{Te?C(xe):Us.set(g,N=>{g.replaceChildren(h(N))})}});return}(X.status!=="complete"||X.id!==m.id)&&(f=null),m=X,D(X,oe),K(X)}),g}var zT,Us,VT,rD,sD,iD,aD,lD,$T,cD,Dc,xy,qT=ie(()=>{"use strict";Ge();Ni();tf();ef();Ri();zT=require("lucide");ao();sf();vy();Us=new WeakMap;VT=180,rD=240,sD=.8,iD=300,aD=500,lD="cubic-bezier(0.2, 0, 0, 1)",$T=240,cD=.35;Dc="--persona-artifact-inline-body-height";xy=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>UT(e,t)});if(l)return l}return UT(e,t)}});var jT=ie(()=>{"use strict";OT();qT();vy();sf();Ni();hy();Si();Gd()});var KT={};En(KT,{PersonaArtifactCard:()=>Bc,PersonaArtifactInline:()=>xy,__provideMarkdownParsers:()=>Jm,__setIconsExtraLoader:()=>qm,artifactCopyText:()=>Wc,createArtifactPane:()=>by,downloadInfoFor:()=>Ic,hasLiveInlineArtifactBlock:()=>wy,initArtifactsUi:()=>gy,triggerArtifactDownload:()=>Hc,updateInlineArtifactBlocks:()=>Cy});var GT=ie(()=>{"use strict";jT()});var pf,sE,iE=ie(()=>{"use strict";Ge();pf={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},sE=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=pf[i]??pf.init;s.classList.add("persona-form-card","persona-space-y-4");let c=v("div","persona-space-y-1"),d=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,c.appendChild(d),l.description){let h=v("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,c.appendChild(h)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let b=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");b.htmlFor=`${t.id}-${i}-${h.name}`;let C=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");C.textContent=h.label,b.appendChild(C);let A=h.type??"text",S;A==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=A),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${i}-${h.name}`,S.name=h.name,S.placeholder=h.placeholder??"",h.required&&(S.required=!0),b.appendChild(S),p.appendChild(b)});let f=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",f.appendChild(m),f.appendChild(g),p.appendChild(f),s.replaceChildren(c,p),p.addEventListener("submit",async h=>{h.preventDefault();let b=n.formEndpoint??"/form",C=new FormData(p),A={};C.forEach((S,E)=>{A[E]=S}),A.type=i,g.disabled=!0,m.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let E=await S.json();m.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(S){m.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var aE={};En(aE,{enhanceWithForms:()=>sE,formDefinitions:()=>pf});var lE=ie(()=>{"use strict";iE()});function vE(){let e=document.createElement("div");e.className="persona-history-sr-only",e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.setAttribute("data-persona-history-live-region","");let t;return{element:e,announce(n){t!==void 0&&clearTimeout(t),e.textContent="",t=setTimeout(()=>{t=void 0,e.textContent=n},0)},destroy(){t!==void 0&&clearTimeout(t),e.remove()}}}var CE=ie(()=>{"use strict"});var wE,xE=ie(()=>{"use strict";wE=`
263
+ `)),n=v("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function HT(e,t,n){let o=e.length<=DB?_B(t,n):null,r=o?qB(e,o):[{type:"plain",value:e}];return jB(r)}var BB,DB,nf,OB,NB,FB,$B,UB,RT=ie(()=>{"use strict";Ge();BB={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},DB=15e4,nf={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};OB=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),NB=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>OB.has(e)?"keyword":"plain"}];FB=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];$B=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];UB=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}]});var WT,gy,BT,hy=ie(()=>{"use strict";WT=null,gy=e=>{WT=e.componentRegistry},BT=()=>WT});function Wc(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ju(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}function KB(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function DT(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||yy||s){o();return}yy=!0;let i=KB(n);e.style.setProperty("view-transition-name",i);let l=()=>{yy=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function XB(e){let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function QB(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}function ZB(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function eD(e){return`
264
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function tD(e,t,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(ST());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function nD(e,t,n,o,r,s){let i=null,l=0,c=!1,d=new Set,p=()=>{d.forEach(E=>clearTimeout(E)),d.clear()},f=(E,k)=>{let D=setTimeout(()=>{d.delete(D),!(typeof document>"u")&&E()},k);d.add(D)},m=()=>{i&&i.parentElement&&i.remove(),i=null},g=()=>{if(i||c)return;let E=tD(r,s,o);i=E.el,e.appendChild(i),l=Date.now(),o.label!==!1&&f(E.revealLabel,o.labelDelayMs)},h=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),f(m,JB))},b=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",A):t.removeEventListener("load",S)},C=()=>{if(c||(c=!0,b(),p(),!i))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-l));E>0?f(h,E):h()};function A(E){if(n===null)return;let k=E.data;!k||k.persona!=="artifact-preview-ready"||k.token!==n||E.source===t.contentWindow&&C()}function S(){let E=k=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>k()):setTimeout(k,0)};E(()=>E(()=>C()))}return f(g,o.delayMs),f(C,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",A):t.addEventListener("load",S),()=>{c=!0,p(),b(),m()}}function rf(e,t){let{config:n}=t,o=t.registry??BT()??sr,r=t.bodyLayout,s=n.markdown?ip(n.markdown):null,i=lp(n.sanitize),l=e,c=!1,d=j=>{let te=Oo()!==null;s&&!te&&!c&&(c=!0,va(()=>_(l)));let K=s?s(j):jr(j);return s&&te&&i?i(K):K},p=v("div","persona-artifact-preview-body"),f=null,m=null,g=null,h=()=>{g&&(g(),g=null),f=null,m=null},b=null,C=null,A=null,S=!1,E=()=>{b=null,C=null,A=null,S=!1},k=null,D=null,z=()=>{k=null,D=null},Y=40,T=0,W=j=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>j()):setTimeout(j,0),L=j=>j.scrollHeight-j.clientHeight-j.scrollTop<=Y,w=j=>{if(!r)return;let te=j.scrollHeight-j.clientHeight>1,K=j.scrollHeight-j.clientHeight-j.scrollTop;j.classList.toggle("persona-artifact-fade-top",r.fadeTop&&te&&j.scrollTop>1),j.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&te&&K>1)},x=j=>{T||(T=W(()=>{T=0,j.scrollTop=j.scrollHeight,w(j)}))},P=(j,te,K,X)=>{let oe=!!r,de=K.id+"|"+(oe?"w":"p");if(!b||A!==de||b.parentElement!==p){h(),z(),p.replaceChildren();let re=v("pre",GB+" persona-code-pre"),N=v("code","persona-code");if(re.appendChild(N),oe){let ke=v("div","persona-artifact-source-window");if(ke.appendChild(re),p.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let tt=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{L(ke)&&(S=!1),w(ke)},{passive:!0}),ke.addEventListener("wheel",xt=>{tt()&&xt.deltaY<0&&(S=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{tt()&&(S=!0)},{passive:!0})}b=ke}else p.appendChild(re),b=re;C=N,A=de}let xe=oe?b:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",X),xe.classList.toggle("persona-artifact-source-window--clip",X&&r?.overflow==="clip"));let Te=xe?L(xe):!0;if(C.replaceChildren(HT(j,te?.language,te?.path)),xe){let re=K.status!=="complete";X&&re&&r?.followOutput&&!S&&Te?x(xe):re||(S=!1),w(xe)}},I=j=>{h(),E(),z(),p.replaceChildren();let te=v("div",YB);te.innerHTML=d(j),p.appendChild(te)},J=j=>{let te=j.id,K=n.features?.artifacts,X=Ka(j,K,"status-body");if(k&&D===te&&k.parentElement===p){let xe=k.querySelector(".persona-artifact-status-view-text");xe&&Fi(xe,X,K);return}h(),E(),p.replaceChildren();let oe=v("div","persona-artifact-status-view"),de=v("div","persona-artifact-status-view-text");Fi(de,X,K),oe.appendChild(de),p.appendChild(oe),k=oe,D=te},_=j=>{l=j;let te=t.resolveViewMode?.(j)??r?.viewMode??"rendered",K=j.artifactType==="markdown"?j.file:void 0,X=j.status!=="complete";X||ja(j.id);let oe=X?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof oe=="number";if(r?.streamingView==="status"&&X){J(j);return}if(K){let Te=Ju(j.markdown??""),re=Oi(K),N=n.features?.artifacts?.filePreview?.enabled!==!1;if(!X&&te==="rendered"&&N&&(re==="html"||re==="svg")){let ve=j.id+"\0"+Te;if(f&&m===ve&&f.parentElement===p)return;E(),z(),h(),p.replaceChildren();let tt=n.features?.artifacts?.filePreview,xt=tt?.iframeSandbox??"allow-scripts";!tt?.dangerouslyAllowSameOrigin&&xt.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),xt=xt.split(/\s+/).filter(Pe=>Pe&&Pe!=="allow-same-origin").join(" "));let ht=QB(tt?.loading),lt=v("div","persona-artifact-frame"),Ye=v("iframe","persona-artifact-iframe");Ye.setAttribute("sandbox",xt),Ye.setAttribute("data-artifact-id",j.id);let dt=null;ht.enabled&&ht.injectReadySignal?(dt=ZB(),Ye.srcdoc=Te+eD(dt)):Ye.srcdoc=Te,lt.appendChild(Ye),p.appendChild(lt),ht.enabled&&(g=nD(lt,Ye,dt,ht,j.id,n)),f=lt,m=ve;return}if(h(),!X&&re==="markdown"&&te==="rendered"){I(Te);return}P(Te,{language:K.language,path:K.path},j,de);return}if(j.artifactType==="markdown"){if(te==="source"){h(),P(j.markdown??"",void 0,j,de);return}I(j.markdown??"");return}h(),E(),z(),p.replaceChildren();let xe=j.component?o.get(j.component):void 0;if(xe){let re={message:{id:j.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let N=xe(j.props??{},re);if(N){p.appendChild(N);return}}catch{}}p.appendChild(XB(j))};return _(e),{el:p,update(j){_(j)},destroy(){h()}}}var yy,GB,YB,JB,sf=ie(()=>{"use strict";Ge();AT();Ni();tf();RT();ap();Si();eg();Pc();hy();yy=!1;GB="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",YB="persona-text-sm persona-leading-relaxed persona-markdown-bubble";JB=220});function _T(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},c=f=>{let m=f;return s.findIndex(g=>g===m||g.contains(m))},d=f=>{let m=c(f.target);if(m<0)return;let g=m;if(f.key===r)g=Math.min(m+1,s.length-1);else if(f.key===o)g=Math.max(m-1,0);else if(f.key==="Home")g=0;else if(f.key==="End")g=s.length-1;else return;f.preventDefault(),g!==m&&t.onSelect(g)},p=f=>{let m=c(f.target);m>=0&&l(s[m])};return e.addEventListener("keydown",d),e.addEventListener("focusin",p),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(f,m){if(s=f,f.forEach((g,h)=>{g.setAttribute("role","tab");let b=h===m;g.setAttribute("aria-selected",b?"true":"false"),g.tabIndex=b||m<0&&h===0?0:-1}),i){let g=(m>=0?f[m]:void 0)??f[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",p)}}}var OT=ie(()=>{"use strict"});function by(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),c=n?.tabFadeSize?.trim(),d=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:p,end:f}=d(n?.tabFade),m=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{m?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),w?.closeMenu()};m&&m.addEventListener("click",()=>{g(),t.onDismiss?.()});let h=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let b=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");b.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&b.classList.add("persona-artifact-toolbar-document");let C=v("span","persona-text-xs persona-font-medium persona-truncate");C.textContent=s;let A=Ln({icon:"x",label:i});A.addEventListener("click",()=>{g(),t.onDismiss?.()});let S="rendered",E=Nu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{S=ee==="source"?"source":"rendered",nt()}}),k=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,z=n?.documentToolbarShowCopyChevron===!0,Y=n?.documentToolbarCopyMenuItems,T=!!(z&&Y&&Y.length>0),W=null,L,w=null;if(r&&(D||z)&&!T){if(L=D?Hi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),z){let ee=Je($s.ChevronDown,14,"currentColor",2);ee&&L.appendChild(ee)}}else r&&T?(w=wM({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(Y??[]).map(ee=>({id:ee.id,label:ee.label})),position:"bottom-right",portal:()=>h.closest("[data-persona-root]")??document.body,onSelect:ee=>{xe(ee)}}),W=w.element,L=w.primaryButton):r?L=Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(L=Ln({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&L.classList.add("persona-hidden"));let x=r?Ln({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ln({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||x.classList.add("persona-hidden");let P=r?Ln({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Ln({icon:"x",label:i}),I=Ln({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&I.classList.add("persona-hidden");let J=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),_=e.features?.artifacts?.toolbarActions??[],j=()=>{let ee=Pe.find(je=>je.id===Se)??Pe[Pe.length-1],Re=ee?.id??null,Fe=ee?.artifactType==="markdown"?ee.markdown??"":"",yt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"",{filename:bt,mime:Ee,content:He}=Ic({title:ee?.title,markdown:ee?.markdown??"",file:ee?.file});return{markdown:Fe,jsonPayload:yt,id:Re,file:ee?.file,suggestedFilename:bt,mime:Ee,content:He}},te=()=>{let{suggestedFilename:ee,mime:Re,content:Fe}=j();Fe&&Hc({filename:ee,mime:Re,content:Fe})},K=ee=>{let{id:Re,...Fe}=j();return{actionId:ee,artifactId:Re,...Fe}},X=async()=>{let ee=Pe.find(Re=>Re.id===Se)??Pe[Pe.length-1];try{return await navigator.clipboard.writeText(Wc(ee)),!0}catch{return!1}},oe=null,de=()=>{oe?.();let ee=L.querySelector("svg"),Re=Number(ee?.getAttribute("width"))||16,Fe=Je($s.Check,Re,"currentColor",2);if(!ee||!Fe)return;ee.replaceWith(Fe);let yt=L.querySelector("span");yt&&(yt.textContent="Copied");let bt=setTimeout(()=>oe?.(),2e3);oe=()=>{clearTimeout(bt),Fe.replaceWith(ee),yt&&(yt.textContent="Copy"),oe=null}};L.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&T){try{if(await ee(K("primary"))===!1){await X()&&de();return}de()}catch{}return}await X()&&de()});async function xe(ee){let Re=n?.onDocumentToolbarCopyMenuSelect;try{if(Re&&await Re(K(ee))!==!1)return;if(ee==="download"){te();return}let{markdown:Fe,jsonPayload:yt}=j();ee==="markdown"||ee==="md"?await navigator.clipboard.writeText(Fe):ee==="json"||ee==="source"?await navigator.clipboard.writeText(yt):await navigator.clipboard.writeText(Fe||yt),de()}catch{}}x.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}nt()}),P.addEventListener("click",()=>{g(),t.onDismiss?.()});let Te=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)b.replaceChildren(),W?k.append(W,x,P):k.append(L,x,P),k.insertBefore(J,P),k.insertBefore(I,P),b.append(E.element,Te,k);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(L,J,I,A),b.appendChild(C),b.appendChild(ee)}l&&(b.style.paddingLeft=l,b.style.paddingRight=l);let re=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");c&&re.style.setProperty("--persona-artifact-tab-fade-size",c);let N=e.features?.artifacts?.renderTabBar,ke=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ve=_T(re,{onSelect:ee=>t.onSelect(Pe[ee].id)}),tt=ee=>{let Re=ee.scrollWidth-ee.clientWidth,Fe=Re>1,yt=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",p&&Fe&&yt>1),ee.classList.toggle("persona-artifact-tab-fade-end",f&&Fe&&yt<Re-1)},xt=0,ht=()=>{if(xt)return;let ee=()=>{xt=0,tt(re)};xt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};re.addEventListener("scroll",()=>ht(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>tt(re)).observe(re);let lt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ye=()=>{lt.scrollLeft=0},dt=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ye):setTimeout(Ye,0)};if(l){for(let ee of[re,ke])ee.style.paddingLeft=l,ee.style.paddingRight=l;lt.style.padding=l}h.appendChild(b),h.appendChild(re),h.appendChild(ke),h.appendChild(lt);let Pe=[],Se=null,U=!1,R=!1,G=!0,ne=!1,Z=null,le="",Me=null,Ie=!1,_e=ee=>ee.artifactType==="markdown"&&!!ee.file||r?S:"rendered",ct=ee=>{r||(ee&&!Ie?(b.insertBefore(E.element,C),Ie=!0):!ee&&Ie&&(E.element.remove(),Ie=!1))},Tt=()=>Se&&Pe.find(ee=>ee.id===Se)||Pe[Pe.length-1],qe=()=>{let ee=Rc(Tt());if(!ee){J.replaceChildren();return}let Re=_.filter(Fe=>Fe.visible===void 0||Fe.visible(ee)).map(Fe=>qa(Fe,{documentChrome:r,onClick:()=>{let yt=Rc(Tt());if(yt)try{Promise.resolve(Fe.onClick(yt)).catch(()=>{})}catch{}}}));J.replaceChildren(...Re)},nt=()=>{qe();let ee=r&&Pe.length<=1,Re=!!N;if(re.classList.toggle("persona-hidden",ee||Re),ke.classList.toggle("persona-hidden",ee||!Re),Re&&N){let bt=Pe.map(Ee=>Ee.id).join("|")+" "+(Se??"");if(bt!==le){le=bt;let Ee=N({records:Pe,selectedId:Se,onSelect:t.onSelect});ke.firstElementChild!==Ee&&ke.replaceChildren(Ee)}}else{ve.beforeRender(),re.replaceChildren();let bt=[],Ee=-1;for(let[He,je]of Pe.entries()){let It=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");It.type="button";let wn=je.artifactType==="markdown"?je.file:void 0,nn=wn?Sr(wn.path):je.title||je.id.slice(0,8),Ot=wn?.path||je.title||nn;It.textContent=nn,It.title=Ot,It.setAttribute("aria-label",Ot),je.id===Se&&(It.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ee=He),It.addEventListener("click",()=>t.onSelect(je.id)),re.appendChild(It),bt.push(It)}if(ve.render(bt,Ee),Ee>=0&&Se!==Z){Z=Se;let He=bt[Ee];typeof He.scrollIntoView=="function"&&He.scrollIntoView({block:"nearest",inline:"nearest"})}tt(re)}let Fe=Se&&Pe.find(bt=>bt.id===Se)||Pe[Pe.length-1];if(!Fe){lt.replaceChildren(),Me?.destroy(),Me=null,ct(!1);return}let yt=Fe.artifactType==="markdown"?Fe.file:void 0;if(ct(!!yt&&Oi(yt)!=="other"),r){let bt=yt?Vs(yt):Fe.artifactType==="markdown"?"MD":Fe.component??"Component",Ee=(Fe.title||"Document").trim(),He=yt?Sr(yt.path):Ee.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Te.textContent=`${He} \xB7 ${bt}`}else C.textContent=yt?Sr(yt.path):s;Me?(Me.el.parentElement!==lt&&lt.replaceChildren(Me.el),Me.update(Fe)):(Me=rf(Fe,{config:e,resolveViewMode:_e}),lt.replaceChildren(Me.el)),lt.classList.toggle("persona-artifact-content-flush",!!lt.querySelector(".persona-code-pre"))},Ut=()=>{let ee=Pe.length>0;if(h.classList.toggle("persona-hidden",!ee),m){let yt=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&yt&&U?(m.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(m.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},tn=()=>{ne=!1,nt(),Ut()};return{element:h,backdrop:m,update(ee){let Re=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,Fe=Re!==Se;Pe=ee.artifacts,Se=Re,Pe.length>0&&(U=!0),ne=!0,G&&tn(),Fe&&Ye()},setMobileOpen(ee){U=ee,!ee&&m?(m.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):Ut()},setExpanded(ee){ee!==R&&(R=ee,dt());let Re=Je(ee?$s.Minimize:$s.Maximize,16,"currentColor",2);Re&&I.replaceChildren(Re);let Fe=ee?"Collapse artifacts panel":"Expand artifacts panel";I.setAttribute("aria-label",Fe),I.title=Fe},setExpandToggleVisible(ee){I.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||L.classList.toggle("persona-hidden",!ee)},setRefreshButtonVisible(ee){x.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){_=ee,qe()},setTabFade(ee){let Re=d(ee);Re.start===p&&Re.end===f||(p=Re.start,f=Re.end,tt(re))},setRenderTabBar(ee){ee!==N&&(N=ee,le="",nt())},setVisible(ee){ee!==G&&(G=ee,ee&&ne&&tn())},destroy(){Me?.destroy(),Me=null}}}var $s,NT=ie(()=>{"use strict";Ge();Ni();ef();sf();$s=require("lucide");ao();Ri();OT()});function FT(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Sr(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",i=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",c=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Vs(n):l==="component"?"Component":"Document",p=document.createElement("div");p.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&p.setAttribute("data-open-artifact",s);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let m=document.createElement("div");m.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let h=document.createElement("div");if(h.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",h.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let b=t?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},A=Ka(C,b,"card");Fi(h,A,b)}else s&&ja(s),h.textContent=d;if(m.append(g,h),p.append(f,m),i==="complete"){let b=t?.config?.features?.artifacts?.cardActions;if(b&&b.length>0){let A={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let S of b)try{if(S.visible===void 0||S.visible(A)){let E=qa(S);E.setAttribute("data-artifact-custom-action",S.id),E.className=`${E.className} persona-flex-shrink-0`,p.append(E)}}catch{}}let C=Hi({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),p.append(C)}return p}var Bc,vy=ie(()=>{"use strict";Ni();tf();Ri();ef();Bc=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>FT(e,t)});if(l)return l}return FT(e,t)}});function Cy(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Us.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function wy(e){return Us.has(e)}function oD(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let i=e.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function VT(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Sr(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Vs(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function rD(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}function pD(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let i=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:$T,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let A of i)A.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let c=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!c||Math.abs(c-t)<1){l(),r();return}let d=Math.abs(t-c),p=Math.round(Math.min(lD,Math.max(aD,sD+d*iD))),f=Math.round(p*dD),m=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=m?m.animate([{opacity:0},{opacity:1}],{duration:UT,delay:f,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${c}px`}],{duration:p,easing:cD});e.style.height=`${c}px`;let b=!1,C=()=>{b||(b=!0,l(),r())};Promise.allSettled([h.finished,g?.finished].filter(Boolean)).then(C),window.setTimeout(C,Math.max(p,f+UT)+120)},$T)}function uD(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function fD(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,i=t?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",c=l==="clip"?!1:t?.followOutput!==!1,d,p,f=t?.fadeMask;f===!0?(d=!0,p=!0):f===!1?(d=!1,p=!1):f&&typeof f=="object"?(d=f.top===!0,p=f.bottom===!0):l==="clip"?(d=!1,p=!0):(d=!0,p=!0);let m=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:c,overflow:l,fadeTop:d,fadeBottom:p,transition:m,completeDisplay:g}}function zT(e,t){let n=oD(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=uD(o),c=o?.inlineActions??[],d=fD(o),p=d.completeDisplay==="card",f=null,m=n,g=v("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let h=X=>Bc(rD(X),t),b=null,C=X=>{b?.destroy(),b=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Dc),g.replaceChildren(h(X)),Us.set(g,oe=>{g.replaceChildren(h(oe))})};if(p&&n.status==="complete")return C(n),g;let A=rf(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode});b=A;let S=v("div","persona-artifact-inline-body");S.appendChild(A.el);let E=X=>{let oe=X.status!=="complete",de=oe?d.streamingHeight:d.completeHeight,xe=typeof de=="number";xe?g.style.setProperty(Dc,`${de}px`):g.style.removeProperty(Dc);let Te=!!A.el.querySelector(".persona-code-pre"),re=!!A.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");S.classList.toggle("persona-artifact-content-flush",Te),S.classList.toggle("persona-artifact-inline-body--sized",xe&&re),S.classList.toggle("persona-artifact-inline-body--cap",!oe&&!re&&typeof d.completeHeight=="number")},k=n.status,D=(X,oe)=>{k!=="complete"&&X.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Dc,`${d.completeHeight}px`):g.style.removeProperty(Dc),DT(S,oe?.suppressTransition?"none":d.transition,X.id,()=>{A.update(X),E(X)})):A.update(X),E(X),k=X.status};E(n);let z=d.overflow==="clip"&&i&&!!n.id;if(z&&(S.setAttribute("data-expand-artifact-inline",n.id),S.setAttribute("role","button"),S.setAttribute("tabindex","0"),S.classList.add("persona-cursor-pointer"),S.setAttribute("aria-label",`Open ${VT(n).title} in panel`)),!r)return g.appendChild(S),Us.set(g,D),g;let Y=v("div","persona-artifact-inline-chrome");Y.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let T=v("div","persona-artifact-inline-chrome-lead"),W=v("span","persona-flex persona-items-center persona-flex-shrink-0"),L=Je(qT.FileText,16,"currentColor",2);L&&W.appendChild(L);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),x=v("span","persona-artifact-inline-type");T.append(W,w,x);let P=v("div","persona-artifact-inline-chrome-actions"),I=v("span","persona-flex persona-items-center persona-gap-1"),J=()=>f??d.viewMode,_=l?Nu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:J(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:X=>{let oe=X==="source"?"source":"rendered";oe!==J()&&(f=oe,A.update(m),E(m))}}):null,j=s?Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;j&&n.id&&j.setAttribute("data-copy-artifact",n.id);let te=i?Ln({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),P.appendChild(I),_&&P.appendChild(_.element),j&&P.appendChild(j),te&&P.appendChild(te),Y.append(T,P),g.append(Y,S);let K=X=>{let{title:oe,typeLabel:de}=VT(X);w.textContent=oe,w.title=oe,z&&S.setAttribute("aria-label",`Open ${oe} in panel`);let xe=X.status!=="complete";if(xe){x.classList.contains("persona-artifact-inline-status")||(x.className="persona-artifact-inline-status",x.removeAttribute("data-preserve-animation"),x.replaceChildren());let Te=Ka(X,o,"inline-chrome");Fi(x,Te,o)}else ja(X.id),x.className="persona-artifact-inline-type",x.removeAttribute("data-preserve-animation"),x.replaceChildren(),x.textContent=de;if(j&&j.classList.toggle("persona-hidden",xe),_){let Te=X.artifactType==="markdown"?X.file:void 0,re=!1;if(!xe&&Te&&d.viewMode!=="source"){let N=Oi(Te);N==="markdown"?re=!0:(N==="html"||N==="svg")&&(re=o?.filePreview?.enabled!==!1)}_.element.classList.toggle("persona-hidden",!re),_.setSelected(J())}if(I.replaceChildren(),!xe&&c.length>0){let Te=Rc(X);if(Te)for(let re of c)try{if(re.visible===void 0||re.visible(Te)){let N=qa(re,{documentChrome:!0});N.setAttribute("data-artifact-custom-action",re.id),N.classList.add("persona-flex-shrink-0"),I.appendChild(N)}}catch{}}};return K(n),Us.set(g,(X,oe)=>{if(p&&k!=="complete"&&X.status==="complete"){let de=g.isConnected?g.getBoundingClientRect().height:0;k="complete";let xe=X,Te=!1,re=N=>{xe=N,Te=!0};Us.set(g,re),pD(g,de,{swap:()=>{C(xe),Te=!1,Us.set(g,re)},onSettled:()=>{Te?C(xe):Us.set(g,N=>{g.replaceChildren(h(N))})}});return}(X.status!=="complete"||X.id!==m.id)&&(f=null),m=X,D(X,oe),K(X)}),g}var qT,Us,$T,sD,iD,aD,lD,cD,UT,dD,Dc,xy,jT=ie(()=>{"use strict";Ge();Ni();tf();ef();Ri();qT=require("lucide");ao();sf();vy();Us=new WeakMap;$T=180,sD=240,iD=.8,aD=300,lD=500,cD="cubic-bezier(0.2, 0, 0, 1)",UT=240,dD=.35;Dc="--persona-artifact-inline-body-height";xy=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>zT(e,t)});if(l)return l}return zT(e,t)}});var KT=ie(()=>{"use strict";NT();jT();vy();sf();Ni();hy();Si();Gd()});var GT={};En(GT,{PersonaArtifactCard:()=>Bc,PersonaArtifactInline:()=>xy,__provideMarkdownParsers:()=>Jm,__setIconsExtraLoader:()=>qm,artifactCopyText:()=>Wc,createArtifactPane:()=>by,downloadInfoFor:()=>Ic,hasLiveInlineArtifactBlock:()=>wy,initArtifactsUi:()=>gy,triggerArtifactDownload:()=>Hc,updateInlineArtifactBlocks:()=>Cy});var YT=ie(()=>{"use strict";KT()});var pf,iE,aE=ie(()=>{"use strict";Ge();pf={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},iE=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=pf[i]??pf.init;s.classList.add("persona-form-card","persona-space-y-4");let c=v("div","persona-space-y-1"),d=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,c.appendChild(d),l.description){let h=v("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,c.appendChild(h)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let b=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");b.htmlFor=`${t.id}-${i}-${h.name}`;let C=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");C.textContent=h.label,b.appendChild(C);let A=h.type??"text",S;A==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=A),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${i}-${h.name}`,S.name=h.name,S.placeholder=h.placeholder??"",h.required&&(S.required=!0),b.appendChild(S),p.appendChild(b)});let f=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",f.appendChild(m),f.appendChild(g),p.appendChild(f),s.replaceChildren(c,p),p.addEventListener("submit",async h=>{h.preventDefault();let b=n.formEndpoint??"/form",C=new FormData(p),A={};C.forEach((S,E)=>{A[E]=S}),A.type=i,g.disabled=!0,m.textContent="Submitting\u2026";try{let S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let E=await S.json();m.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(S){m.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var lE={};En(lE,{enhanceWithForms:()=>iE,formDefinitions:()=>pf});var cE=ie(()=>{"use strict";aE()});function CE(){let e=document.createElement("div");e.className="persona-history-sr-only",e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.setAttribute("data-persona-history-live-region","");let t;return{element:e,announce(n){t!==void 0&&clearTimeout(t),e.textContent="",t=setTimeout(()=>{t=void 0,e.textContent=n},0)},destroy(){t!==void 0&&clearTimeout(t),e.remove()}}}var wE=ie(()=>{"use strict"});var xE,SE=ie(()=>{"use strict";xE=`
265
265
  .persona-history-view {
266
266
  --persona-history-surface-bg: var(--persona-surface, #ffffff);
267
267
  --persona-history-topbar-bg: var(--persona-header-bg, var(--persona-surface, #ffffff));
@@ -1158,22 +1158,22 @@ ${vH}`.trim(),{status:Y.failed?"failed":"completed",text:_,...I(_)}):{status:!Y.
1158
1158
  .persona-history-view .persona-history-skeleton-bar { animation: none; }
1159
1159
  .persona-history-rail-host { transition: none; }
1160
1160
  }
1161
- `});function By(e){if(!e)return uf;let t={...uf};for(let n of $D){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var $D,uf,Dy=ie(()=>{"use strict";$D=["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"],uf={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 Vc(e){if(!e)return Fc;let t={...Fc};for(let[n,o]of Object.entries(e))typeof o=="string"&&o.length>0&&(t[n]=o);return t}function Mr(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n)}var Fc,$c=ie(()=>{"use strict";Dy();Fc={...uf,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function UD(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function Oy(e,t){let n=Date.parse(e);return Number.isFinite(n)?n:t}function zD(e,t){let n=Oy(e,t),o=UD(t);if(n>=o)return"today";if(n>=o-_y)return"yesterday";if(n>=o-7*_y)return"previous-7-days";if(n>=o-30*_y)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function qD(e,t,n,o){if(e==="today")return o.groupToday;if(e==="yesterday")return o.groupYesterday;if(e==="previous-7-days")return o.groupPrevious7Days;if(e==="previous-30-days")return o.groupPrevious30Days;let r=new Date(Oy(t,n));return Mr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function SE(e,t,n,o="time"){let r=e.filter(i=>i.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let i=e.filter(l=>!l.starred);return i.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:i}),s}for(let i of e){if(i.starred)continue;let l=zD(i.updatedAt,t),c=s[s.length-1];if(c&&c.key===l){c.items.push(i);continue}s.push({key:l,label:qD(l,i.updatedAt,t,n),items:[i]})}return s}function AE(e,t,n){let o=Math.max(0,t-Oy(e,t)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return Mr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return Mr(n.relativeHours,{value:s});let i=Math.floor(s/24);if(i<7)return Mr(n.relativeDays,{value:i});let l=Math.floor(i/7);return i<365?Mr(n.relativeWeeks,{value:l}):Mr(n.relativeYears,{value:Math.floor(i/365)})}function ME(e,t){return e===1?t.messageCountLabelOne:Mr(t.messageCountLabel,{count:e})}var _y,Ny=ie(()=>{"use strict";$c();_y=864e5});function zs(e,t=20){let n=document.createElementNS(ff,"svg");if(n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),e==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(ff,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=KD[e];if(o){let r=document.createElementNS(ff,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of jD[e]){let s=document.createElementNS(ff,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var ff,jD,KD,Fy=ie(()=>{"use strict";ff="http://www.w3.org/2000/svg",jD={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},KD={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function YD(e){let t=F("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return GD.test(e)?t.appendChild(F("img",{attrs:{src:e,alt:"",loading:"lazy"}})):t.textContent=e,t}function TE(e){let{conversation:t,copy:n,busy:o,pending:r}=e,s=o||r!==null,i=t.title.trim().length>0,l=t.starred?(()=>{let g=zs("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),F("span",{className:"persona-history-row-star"},g,F("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,c=F("div",{className:"persona-history-row-head"},F("span",{className:"persona-history-row-title persona-history-truncate",text:i?t.title:t.preview??""}),l,F("time",{className:"persona-history-row-time",attrs:{datetime:t.updatedAt},text:AE(t.updatedAt,e.nowMs,n)})),d=i&&t.preview?F("span",{className:"persona-history-row-preview persona-history-truncate",text:t.preview}):null,p=F("button",{className:Jt("persona-history-row",e.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":XD(t.id),"data-persona-history-conversation":t.id,...e.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},e.avatar?YD(e.avatar):null,F("div",{className:"persona-history-row-body"},c,d,F("span",{className:"persona-history-row-count persona-history-sr-only",text:ME(t.messageCount,n)})));p.addEventListener("click",()=>{s||e.onOpen()});let f=e.showDelete?Vy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${t.title}`,focusKey:QD(t.id),open:e.menuOpen,inert:s,onToggle:e.onToggleMenu}):null;return F("li",{className:Jt("persona-history-item",!e.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":t.id}},p,f,e.menuOpen&&e.showDelete?JD(e):null,e.error?ZD(e.error,n,t.id):null)}function JD(e){let{conversation:t,copy:n}=e;return $y({label:`${n.rowActionsLabel}: ${t.title}`,items:[{label:n.deleteConversationLabel,focusKey:Uc(t.id),danger:!0,onSelect:e.onDelete}],onCloseMenu:e.onCloseMenu})}function Vy(e){let t=F("button",{className:Jt("persona-history-icon-button",e.className),attrs:{type:"button","aria-label":e.label,"aria-haspopup":"menu","aria-expanded":e.open?"true":"false","data-persona-history-focus":e.focusKey,...e.inert?{"aria-disabled":"true"}:{}}});t.appendChild(zs("ellipsis",e.iconSize));let n=()=>t.getAttribute("aria-disabled")==="true";return t.addEventListener("click",o=>{o.stopPropagation(),!n()&&e.onToggle()}),t.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||t.getAttribute("aria-expanded")==="true")&&e.onToggle())}),t}function $y(e){let t=F("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":e.label}});for(let n of e.items){let o=F("button",{className:Jt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{e.onCloseMenu(),n.onSelect()}),t.appendChild(o)}return t.addEventListener("keydown",n=>{let o=Array.from(t.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){e.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),t}function ZD(e,t,n){let o=F("button",{className:"persona-history-secondary persona-history-state-action",text:t.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",e.retry),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:e.message}),o)}var GD,XD,QD,Uc,EE=ie(()=>{"use strict";Ge();Fy();Ny();GD=/^(https?:|\/|data:)/i;XD=e=>`row:${e}`,QD=e=>`menu:${e}`,Uc=e=>`menu-item:${e}`});function e_(e){switch(e){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return e;default:return"unknown"}}function kE(e){if(Tp(e)){if(e.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:e.retryAfterSeconds??0};let t=e_(e.code);return{kind:"error",reason:t,retryable:t!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function t_(e,t){switch(e.state){case"authentication_required":return{title:t.authenticationRequiredTitle,description:t.authenticationRequiredDescription};case"identity_provider_failed":return{title:t.identityProviderFailedTitle,description:t.identityProviderFailedDescription};case"configuration_error":return{title:t.proofNotAdmittedTitle,description:t.proofNotAdmittedDescription};default:return null}}function n_(e,t){switch(e){case"authentication_required":case"authentication_failed":return{title:t.authenticationRequiredTitle,description:t.authenticationRequiredDescription};case"identity_provider_failed":return{title:t.identityProviderFailedTitle,description:t.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:t.proofNotAdmittedTitle,description:t.proofNotAdmittedDescription};case"unavailable":return{title:t.unavailableTitle,description:t.unavailableDescription};default:return{title:t.errorTitle,description:t.errorDescription}}}function mf(e,t,n,o){let r=F("button",{className:"persona-history-secondary persona-history-state-action",text:e,attrs:{type:"button","data-persona-history-focus":t,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function zc(e,t,n,o,r){return F("div",{className:"persona-history-state",attrs:{"data-persona-history-state":e,...r?{role:"alert"}:{role:"status"}}},F("p",{className:"persona-history-state-title",text:t}),F("p",{className:"persona-history-state-description",text:n}),o)}function o_(e){let t=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>F("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},F("div",{className:"persona-history-skeleton-head"},F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:t[r]}}),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return F("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":e.loadingLabel}},...o)}function LE(e){let{state:t,copy:n,busy:o}=e;if(t.kind==="loading")return o_(n);if(t.kind==="empty"){let l=t_(e.identityStatus,n);return l?zc("identity",l.title,l.description,e.onRetry?mf(n.retryIdentityLabel,"state-retry",o,e.onRetry):null,!0):zc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(t.kind==="rate_limited"){let l=t.retryAfterSeconds>0?Mr(n.rateLimitedWaitDescription,{seconds:t.retryAfterSeconds}):n.rateLimitedDescription;return zc("rate_limited",n.rateLimitedTitle,l,e.onRetry?mf(n.retryLabel,"state-retry",o,e.onRetry):null,!1)}if(t.kind==="new_conversation_required")return zc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,e.onStartNew?mf(n.newConversationLabel,"state-retry",o,e.onStartNew):null,!0);let{title:r,description:s}=n_(t.reason,n),i=t.reason==="authentication_required"||t.reason==="authentication_failed"||t.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return zc("error",r,s,t.retryable&&e.onRetry?mf(i,"state-retry",o,e.onRetry):null,!0)}var PE=ie(()=>{"use strict";Ge();$c();zl()});function gf(e){return`${e.state}:${"reason"in e?e.reason:""}`}function HE(e,t){switch(e.state){case"verified":return{title:t.verifiedTitle,description:t.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:t.verifyingTitle,description:t.verifyingDescription,pending:!0};case"authentication_required":return{title:t.authenticationRequiredTitle,description:t.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:t.identityProviderFailedTitle,description:t.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:t.proofNotAdmittedTitle,description:t.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:t.unavailableTitle,description:t.unavailableDescription,pending:!1};default:return{title:t.browserOnlyTitle,description:t.browserOnlyDescription,pending:!1}}}function p_(e){return e.state==="verified"||e.state==="browser_only"}function u_(e){return e.state==="authentication_required"||e.state==="identity_provider_failed"||e.state==="configuration_error"}function Uy(e){let t=Vc(e.copy),n=e.now??(()=>Date.now()),o=e.pageSize??r_,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],i=null,l={kind:"loading",phase:"initial"},c=null,d=e.activeConversationId,p=e.provider.getIdentityStatus(),f=gf(p),m=null,g=!1,h=!1,b=0,C=e.presentation,A=e.collapsible!==!1,S=e.collapsed===!0,E=e.railSide==="right",k=e.renderDom!==!1,D=new Map,z=null,Y=vE(),T=$=>{!k&&e.onAnnounce?e.onAnnounce($):Y.announce($)},W=()=>c!==null,L=`${r}-body`,w=F("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),x=()=>C==="rail"&&A,P,I=()=>{if(e.railBrand){if(!x()){w.classList.remove("persona-history-back--branded");return}if(P===void 0){let $=e.railBrand(!0);P=$?F("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},$):null}P&&(w.classList.add("persona-history-back--branded"),w.appendChild(P))}},J=()=>{let $=x(),me=C==="rail";w.setAttribute("data-persona-history-focus",$?"collapse":"close"),w.setAttribute("aria-label",$?S?t.expandLabel:t.collapseLabel:me?t.closeLabel:t.backLabel),$?(w.setAttribute("aria-expanded",S?"false":"true"),w.setAttribute("aria-controls",L),e.collapseShortcut?.aria&&w.setAttribute("aria-keyshortcuts",e.collapseShortcut.aria)):(w.removeAttribute("aria-expanded"),w.removeAttribute("aria-controls"),w.removeAttribute("aria-keyshortcuts")),w.replaceChildren(zs($?"panel-left":me?"x":"arrow-left")),I()};J(),w.addEventListener("click",()=>{x()?e.onToggleCollapse?.():e.onClose()});let _=F("h2",{className:"persona-history-title",text:t.viewTitle,attrs:{id:r}}),j=F("span",{className:"persona-history-scope-title"}),te=F("p",{className:"persona-history-scope"},F("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},zs("monitor",14)),j),K=F("div",{className:"persona-history-heading-group"},_),X=!1,oe,de=()=>{let $=C==="rail",me=$?e.renderRailHeader:void 0,Ne=null,ft=me!==void 0;if(me)try{Ne=me({collapsed:S,defaultTitle:t.viewTitle})}catch(pt){ft=!1,X||(X=!0,console.warn("[persona] history rail renderHeader threw",pt))}if(!ft&&$&&e.railBrand){if(oe===void 0){let pt=e.railBrand(!1);oe=pt?F("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},F("span",{className:"persona-history-brand-mark"},pt),F("span",{className:"persona-history-wordmark",text:t.viewTitle})):null}oe&&(ft=!0,Ne=oe)}_.classList.toggle("persona-history-sr-only",ft),K.replaceChildren(_),Ne&&K.appendChild(Ne)};de();let xe=F("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":t.newConversationLabel}});xe.appendChild(zs("plus")),xe.addEventListener("click",()=>{fo()});let Te=[w,xe].map($=>e.attachTooltip?.({anchor:$,text:()=>$.getAttribute("aria-label")??"",...$===w&&e.collapseShortcut?{hint:()=>x()?e.collapseShortcut.hint:""}:{}})),re=F("div",{className:"persona-history-topbar"}),N=null,ke=()=>{let $=C==="rail",me=$?E?"rail-right":"rail":"panel";me!==N&&(N=me,me==="rail"?re.append(K,w):re.append(w,K),$?xe.remove():re.appendChild(xe),Z.classList.toggle("persona-history-view--rail-right",me==="rail-right"))},ve=F("div",{className:"persona-history-scope-alert"}),tt=`${r}-scope`,xt=zs("plus",18),ht=F("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},xt,F("span",{text:t.newConversationLabel}));ht.addEventListener("click",()=>{fo()});let lt=F("div",{className:"persona-history-list-region"}),Ye=e.showDeleteAll!==!1,dt=!!e.provider.resetDevice,Pe=e.listActions??[],Se=Ye||dt||Pe.length>0?Vy({className:"persona-history-list-options",label:t.listOptionsLabel,focusKey:`menu:${Ui}`,open:!1,inert:!0,iconSize:16,onToggle:()=>Ve(Ui)}):null,U=F("h3",{className:"persona-history-conversations-title",text:t.conversationsTitle}),R=F("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Ui}},U,e.showScopeStatus?te:null,Se),G=F("div",{className:"persona-history-body",attrs:{id:L}},e.showScopeStatus?ve:null,ht,R,lt),ne=e.headerPlacement??"inline";ne==="external"&&re.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Z=F("div",{className:Jt("persona-history-view",`persona-history-view--${e.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":e.presentation}},Y.element,ne==="inline"?re:null,G),le=()=>{Z.classList.toggle("persona-history-view--rail-collapsed",S&&x())};le(),ke();let Me=($,me)=>{let Ne=`${r}-s${me}`,ft=F("div",{className:Jt("persona-history-nav",$.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":$.id,...$.title?{"aria-labelledby":Ne}:{"aria-label":$.id}}});$.title&&ft.appendChild(F("h3",{className:"persona-history-group-heading",text:$.title,attrs:{id:Ne}}));for(let pt of $.items){let An=pt.iconNode?.()??null,Ze=F("button",{className:Jt("persona-history-nav-item",An&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":pt.label,"data-persona-rail-item":pt.id}},An?F("span",{className:"persona-history-nav-icon"},An):null,F("span",{className:"persona-history-nav-label persona-history-truncate",text:pt.label}),pt.badge?F("span",{className:"persona-history-nav-badge",text:pt.badge}):null);Ze.addEventListener("click",()=>pt.onSelect()),ft.appendChild(Ze)}return ft},Ie=null,_e=null,ct=()=>{!Ie||!k||C!=="rail"||S===_e||(_e=S,e.railSections.forEach(($,me)=>{if(!$.render)return;let Ne=Ie[me],ft=$.title?Ne.firstElementChild:null,pt=null;try{pt=$.render(S)}catch(An){$.render=void 0,console.warn("[persona] history rail section threw",$.id,An)}Ne.replaceChildren(...ft?[ft]:[],...pt?[pt]:[]),Ne.hidden=!pt}))},Tt=()=>{let $=e.railSections;if(Z.classList.toggle("persona-history-view--has-nav",C==="rail"&&!!$?.some(me=>me.placement==="above-conversations")),!!$?.length){if(C!=="rail"){Ie?.forEach(me=>me.remove());return}Ie??=$.map(Me);for(let me of["above-conversations","below-conversations","footer"]){let Ne=me==="above-conversations"?R.parentNode===G?R:lt:null;$.forEach((ft,pt)=>{ft.placement===me&&G.insertBefore(Ie[pt],Ne)})}ct()}};Tt(),Yp(Z,"persona-history-view",wE);let qe=($,me)=>{let Ne=Z.ownerDocument.defaultView?.getComputedStyle(Z).getPropertyValue($),ft=Number.parseFloat(Ne??"");return Number.isFinite(ft)&&ft>=0?ft:me},nt=($,me)=>Z.ownerDocument.defaultView?.getComputedStyle(Z).getPropertyValue($).trim()||me,Ut=null,tn=()=>{Ut!==null&&(clearTimeout(Ut),Ut=null),Z.removeEventListener("animationend",tn),Z.classList.remove("persona-history-view--enter")};Z.addEventListener("animationend",tn),Ut=setTimeout(()=>{Ut=setTimeout(tn,qe("--persona-history-enter-ms",s_)+60)},0);let ee=null,Re=()=>{ee!==null&&(clearTimeout(ee),ee=null),re.classList.remove("persona-history-topbar--shell-enter")},Fe=()=>{Re(),re.classList.add("persona-history-topbar--shell-enter"),ee=setTimeout(Re,IE+60)};ne==="external"&&(ee=setTimeout(Re,IE+60));let yt=[],bt=null,Ee=()=>{if(bt)return bt;if(h||c_()||typeof Z.animate!="function")return tn(),null;let $=Z.ownerDocument.defaultView?.getComputedStyle(G).opacity||"1";tn(),Z.style.pointerEvents="none",je.style.pointerEvents="none";let me={duration:qe("--persona-history-exit-ms",i_),easing:nt("--persona-history-exit-easing",a_),fill:"forwards"},Ne=l_[C];return yt=[G.animate([{opacity:$,transform:"none"},{opacity:0,transform:`translateX(${Ne}px)`}],me)],bt=Promise.all(yt.map(d_)).then(()=>{}),bt},He=($,me)=>{$&&(me?$.setAttribute("aria-disabled","true"):$.removeAttribute("aria-disabled"))},je=re,It=null,wn=()=>{let $=e.slots?.header;if(!$)return;let me=`${C}|${gf(p)}|${c?`${c.kind}:${"conversationId"in c?c.conversationId:""}`:""}`;if(me===It)return;It=me;let Ne=$({identityStatus:p,pendingAction:c,copy:t,defaultRenderer:()=>re})??re;Ne!==je&&(je.replaceWith(Ne),je=Ne)},nn=null,Ot=()=>{if(!e.showScopeStatus)return;let $=gf(p);if($===nn)return;nn=$;let me=HE(p,t);j.textContent=me.title;let Ne=p_(p);if(te.hidden=!Ne,ve.replaceChildren(...Ne?[]:[F("span",{className:"persona-history-scope-alert-title",text:me.title})],F("span",{className:"persona-history-scope-description",text:me.description,attrs:{id:tt}})),ve.setAttribute("data-persona-history-scope-tone",Ne?"ambient":"attention"),Ne?te.setAttribute("aria-describedby",tt):te.removeAttribute("aria-describedby"),me.pending?ve.setAttribute("role","status"):ve.removeAttribute("role"),ve.setAttribute("data-persona-history-identity",p.state),te.setAttribute("data-persona-history-identity",p.state),u_(p)){let ft=F("button",{className:"persona-history-secondary persona-history-state-action",text:t.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});ft.addEventListener("click",()=>{W()||Be("refresh")}),ve.appendChild(ft)}},mt=$=>c?c.kind==="open"&&c.conversationId===$?"opening":c.kind==="delete"&&c.conversationId===$?"deleting":null:null,Ht=()=>{let $=document.activeElement;return!($ instanceof HTMLElement)||!Z.contains($)?null:$.getAttribute("data-persona-history-focus")},St=$=>{if(g&&m){g=!1;let me=Z.querySelector(`[data-persona-history-focus="${Uc(m)}"]`);if(me){me.focus();return}}$&&Z.querySelector(`[data-persona-history-focus="${$}"]`)?.focus()},Kt=()=>{if(!z)return null;let $=F("button",{className:"persona-history-secondary persona-history-state-action",text:t.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),me=z;return $.addEventListener("click",()=>{W()||me.retry()}),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:me.message}),$)},gn=()=>SE(s,n(),t,e.grouping).map(($,me)=>{let Ne=`${r}-g${me}`,ft=F("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Ne}});for(let pt of $.items){let An=()=>TE({conversation:pt,active:pt.id===d,pending:mt(pt.id),busy:W(),menuOpen:m===pt.id,error:D.get(pt.id)??null,avatar:e.rowAvatar,showDelete:e.showDelete!==!1,nowMs:n(),copy:t,onOpen:()=>{$e(pt.id)},onToggleMenu:()=>Ve(pt.id),onCloseMenu:mo=>ot(mo),onDelete:()=>{uo(pt.id)}}),Nt=e.slots?.conversation?.({conversation:pt,active:pt.id===d,pending:mt(pt.id),open:()=>$e(pt.id),requestDelete:()=>uo(pt.id),defaultRenderer:An})??An();ft.appendChild(Nt instanceof HTMLLIElement?Nt:F("li",{className:"persona-history-item"},Nt))}return F("div",{className:"persona-history-group",attrs:{"data-persona-history-group":$.key}},F("h3",{className:Jt("persona-history-group-heading",$.key==="recent"&&"persona-history-sr-only"),text:$.label,attrs:{id:Ne}}),ft)}),Zn=()=>{if(!i)return null;let $=c?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",me=F("button",{className:"persona-history-secondary persona-history-load-more",text:$?t.loadingMoreLabel:t.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...$?{"aria-busy":"true","aria-disabled":"true"}:{},...W()&&!$?{"aria-disabled":"true"}:{}}});return me.addEventListener("click",()=>{W()||Be("load-more")}),me},ss=()=>{let $=Ht(),me=[Kt()],Ne=s.length>0;if(Ne&&(me.push(...gn()),me.push(Zn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Ne)){let pt=l,An=pt.kind==="loading"?void 0:()=>Be("refresh"),Ze=pt.kind==="new_conversation_required"?()=>fo():void 0,Nt=()=>LE({state:pt,copy:t,identityStatus:p,busy:W(),...An?{onRetry:()=>{An()}}:{},...Ze?{onStartNew:()=>{Ze()}}:{}}),mo=e.slots?.state?.({state:pt,identityStatus:p,copy:t,...An?{retry:An}:{},...Ze?{startNewConversation:Ze}:{},defaultRenderer:Nt});me.push(mo??Nt())}lt.replaceChildren(...me.filter(pt=>!!pt)),St($)},jn=()=>{let $=l.kind==="loading"&&s.length===0,me=[],Ne=()=>me.length===0?Uc(Ui):`${Uc(Ui)}-${me.length}`;if(!$)for(let ft of Pe)me.push({label:ft.label,focusKey:Ne(),danger:ft.danger===!0,onSelect:()=>{ft.onSelect({conversations:[...s]})}});return Ye&&!(s.length===0&&(l.kind==="empty"||$))&&me.push({label:t.clearHistoryLabel,focusKey:Ne(),danger:!0,onSelect:()=>{eo()}}),dt&&!$&&me.push({label:t.resetIdentityLabel,focusKey:Ne(),danger:!0,onSelect:()=>{ze()}}),me},qs=()=>{if(He(ht,W()),He(xe,W()),Se){let $=jn(),me=l.kind==="loading"&&s.length===0;Se.hidden=$.length===0&&!me,He(Se,W()||$.length===0),Se.setAttribute("aria-expanded",m===Ui?"true":"false");let Ne=R.querySelector(".persona-history-menu");if(m!==Ui||$.length===0)Ne?.remove();else{let ft=$y({label:t.listOptionsLabel,items:$,onCloseMenu:pt=>ot(pt)});Ne?Ne.replaceWith(ft):R.appendChild(ft)}}R.hidden=C!=="rail"&&(!Se||Se.hidden)&&(!e.showScopeStatus||te.hidden)},oo,Tr=()=>{let $=e.onActiveConversationChange;if(!$)return;let me=s.find(ft=>ft.id===d)??null,Ne=me?`${me.id}\0${me.title}\0${me.starred?1:0}`:"";Ne!==oo&&(oo=Ne,$(me))},At=()=>{if(!h){if(Tr(),!k){e.onModelChange?.();return}wn(),Ot(),qs(),ss(),ct()}},ot=$=>{if(!m)return;let me=m;m=null,g=!1,At(),$?.restoreFocus&&Z.querySelector(`[data-persona-history-focus="menu:${me}"]`)?.focus()},Ve=$=>{if(m===$){ot({restoreFocus:!0});return}m=$,g=!0,At()},cn=$=>{if(!m)return;let me=$.target;me instanceof Node&&Z.contains(me)&&me.closest?.(`[data-persona-history-item="${m}"]`)||ot()};document.addEventListener("pointerdown",cn,!0);let wt=$=>{$.key!=="Escape"||!m||($.stopPropagation(),ot({restoreFocus:!0}))};Z.addEventListener("keydown",wt);async function Be($){if(h)return;let me=++b,Ne=$==="load-more"?i:null;if(!($==="load-more"&&!Ne)){c={kind:$==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:$},$!=="load-more"&&(D.clear(),z=null),ot(),At();try{let ft=await e.provider.list({limit:o,context:e.context,...Ne?{cursor:Ne}:{},...e.targetId?{targetId:e.targetId}:{}});if(h||me!==b)return;s=Ne?[...s,...ft.items]:ft.items,i=ft.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(ft){if(h||me!==b)return;l=kE(ft)}finally{!h&&me===b&&(c=null,At())}}}let ye=$=>{s=s.filter(me=>me.id!==$),D.delete($),d===$&&(d=null),s.length===0&&!i&&(l={kind:"empty"})};async function $e($){if(!(W()||h)){D.delete($),ot(),c={kind:"open",conversationId:$},At();try{if(await e.onSelect($),h)return;d=$}catch{if(h)return;D.set($,{message:t.openFailedLabel,retry:()=>{$e($)}})}finally{h||(c=null,At())}}}async function uo($){if(W()||h)return"cancelled";D.delete($),c={kind:"delete",conversationId:$},At();try{let me=await e.onRequestDeleteConversation($);return h||me==="deleted"&&(ye($),T(t.conversationRemovedNotice)),me}catch(me){return h||(Tp(me)&&me.code==="not_found"?ye($):D.set($,{message:t.deleteFailedLabel,retry:()=>{uo($)}})),"cancelled"}finally{h||(c=null,At())}}async function fo(){if(!(W()||h)){z=null,ot(),c={kind:"start-new"},At();try{if(await e.onStartNew(),h)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(h)return;z={message:t.errorDescription,retry:()=>{fo()}}}finally{h||(c=null,At())}}}async function eo(){if(W()||h)return"cancelled";z=null,ot(),c={kind:"clear"},At();try{let $=await e.onRequestClearHistory();return h||$==="cleared"&&(s=[],i=null,d=null,l={kind:"empty"},T(t.historyClearedNotice)),$}catch{return h||(z={message:t.errorDescription,retry:()=>{eo()}}),"cancelled"}finally{h||(c=null,At())}}let we={outcome:"cancelled"};async function ze(){if(W()||h||!e.onRequestResetIdentity)return we;z=null,ot(),c={kind:"reset"},At();try{let $=await e.onRequestResetIdentity();return h||$.outcome==="reset"&&(T($.remoteRevocationConfirmed?t.identityResetNotice:t.identityResetUnconfirmedNotice),c=null,await Be("refresh")),$}catch{return h||(z={message:t.errorDescription,retry:()=>{ze()}}),we}finally{!h&&c?.kind==="reset"&&(c=null,At())}}let Pn=e.provider.subscribeIdentityStatus($=>{if(h)return;let me=gf($),Ne=me!==f;p=$,f=me,At(),Ne&&$.state!=="verifying"&&T(HE($,t).title)}),Mt=e.provider.subscribeAvailability?.($=>{if(!h){if($){Be("refresh");return}s=[],i=null,l={kind:"error",reason:"unavailable",retryable:!1},At()}});return At(),Be("initial"),{element:Z,copy:t,getModel:()=>({conversations:s,activeConversationId:d,state:l,pendingAction:c,identityStatus:p,nextCursor:i}),operations:{refresh:async()=>{W()||await Be("refresh")},loadMore:async()=>{W()||await Be("load-more")},openConversation:$=>$e($),startNewConversation:()=>fo(),requestDeleteConversation:$=>uo($),requestClearConversationHistory:()=>eo(),requestResetHistoryIdentity:()=>ze()},setDomRenderEnabled:$=>{$!==k&&(k=$,$&&At())},refresh:()=>{Be("refresh")},setPresentation:$=>{if($===C)return;tn(),C=$,It=null;let me=$==="rail";Z.classList.toggle("persona-history-view--panel",!me),Z.classList.toggle("persona-history-view--rail",me),Z.setAttribute("data-persona-history-presentation",$),J(),le(),ke(),de(),Tt(),At()},setCollapsed:$=>{$!==S&&(S=$,le(),J(),de(),ct())},setRailSide:$=>{E=$==="right",ke()},getHeaderElement:()=>je,setHeaderPlacement:$=>{if($===ne)return;ne=$;let me=$==="external";if(re.classList.toggle("persona-history-topbar--shell",me),me){Fe(),je.remove();return}Re(),Z.insertBefore(je,G)},setActiveConversationId:$=>{d!==$&&(d=$,At())},applyConversationSummary:$=>{let me=s.findIndex(Ne=>Ne.id===$.id);me!==-1&&(s[me]=$,At())},removeConversationSummary:$=>{s.some(me=>me.id===$)&&(ye($),At())},setNewConversationRequired:$=>{$?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),At()},playExit:Ee,destroy:()=>{h=!0,b+=1,tn(),Re(),Te.forEach($=>$?.destroy()),je.remove(),yt.forEach($=>$.cancel()),yt=[],Pn(),Mt?.(),document.removeEventListener("pointerdown",cn,!0),Z.removeEventListener("keydown",wt),Y.destroy(),Z.remove(),Z.replaceChildren()}}}var r_,Ui,s_,IE,i_,a_,l_,c_,d_,RE=ie(()=>{"use strict";Ra();Ge();CE();xE();$c();Ny();Fy();EE();PE();zl();r_=25,Ui="persona:list-options",s_=180,IE=120,i_=160,a_="cubic-bezier(0.4, 0, 1, 1)",l_={panel:20,rail:12},c_=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,d_=e=>e.finished?e.finished.then(()=>{},()=>{}):Promise.resolve()});var zy=ie(()=>{"use strict";RE();$c()});function WE(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=F("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=F("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=F("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"}},F("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),F("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),F("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,i));for(let d of[s,i])d.style.minHeight="44px",d.style.minWidth="88px",d.style.padding="0 16px",d.style.borderRadius="var(--persona-radius-md, 0.5rem)",d.style.cursor="pointer",d.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",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=F("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(d=>{let p=!1,f=g=>{p||(p=!0,c.removeEventListener("keydown",m,!0),c.remove(),t?.focus(),d(g))};function m(g){if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),f(!1);return}if(g.key!=="Tab")return;let h=Array.from(l.querySelectorAll(f_));if(h.length===0)return;let b=h[0],C=h[h.length-1],A=document.activeElement;g.shiftKey&&(A===b||!l.contains(A))?(g.preventDefault(),C.focus()):!g.shiftKey&&A===C&&(g.preventDefault(),b.focus())}c.addEventListener("keydown",m,!0),c.addEventListener("pointerdown",g=>{g.target===c&&f(!1)}),s.addEventListener("click",()=>f(!1)),i.addEventListener("click",()=>f(!0)),e.host.appendChild(c),s.focus()})}var f_,BE=ie(()=>{"use strict";Ge();f_="button:not([disabled])"});var DE={};En(DE,{HISTORY_VIEW_COPY_DEFAULTS:()=>Fc,createHistoryView:()=>Uy,resolveHistoryViewCopy:()=>Vc,showHistoryConfirm:()=>WE});var _E=ie(()=>{"use strict";zy();BE();zy()});function VE(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],d=()=>{for(let k of c.splice(0))try{k()}catch(D){qy("renderHistoryView cleanup",D)}},p=(k,D)=>{for(let z of t){let Y=z[k];if(Y)try{let T=Y(D);if(T)return T}catch(T){qy(k,T)}}return null},f=()=>({presentation:e.getPresentation(),config:n}),m={header:k=>i?p("renderHistoryHeader",Object.freeze({...f(),returnSurface:e.getReturnSurface(),identityStatus:os(k.identityStatus),pendingAction:FE(k.pendingAction),copy:os(k.copy),actions:Object.freeze({close:b.close,startNewConversation:b.startNewConversation}),defaultRenderer:k.defaultRenderer})):null,conversation:k=>i?p("renderHistoryConversation",Object.freeze({...f(),conversation:NE(k.conversation),active:k.active,pending:k.pending,open:k.open,requestDelete:k.requestDelete,defaultRenderer:k.defaultRenderer})):null,state:k=>i?p("renderHistoryState",Object.freeze({...f(),state:os(k.state),identityStatus:os(k.identityStatus),copy:os(k.copy),...k.retry?{retry:k.retry}:{},...k.startNewConversation?{startNewConversation:k.startNewConversation}:{},defaultRenderer:k.defaultRenderer})):null},g=t.flatMap(k=>(k.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:z=>D.render(Object.freeze({collapsed:z,presentation:e.getPresentation(),actions:b}))}))),h=e.createView({slots:m,renderDom:!1,onModelChange:()=>E(),railSections:g}),b=Object.freeze({...h.operations,close:e.close}),C=()=>(i=!0,h.setDomRenderEnabled(!0),h.element),A=k=>Object.freeze({conversations:Object.freeze(k.conversations.map(NE)),activeConversationId:k.activeConversationId,state:os(k.state),pendingAction:FE(k.pendingAction),identityStatus:os(k.identityStatus),nextCursor:k.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:os(h.copy),actions:b,defaultRenderer:C,requestRender:()=>E(),onCleanup:D=>{c.push(D)}}),S=()=>{i=!1;let k=null;for(let z of t)if(z.renderHistoryView){try{k=z.renderHistoryView(A(h.getModel()))}catch(Y){qy("renderHistoryView",Y),k=null}if(k)break}let D=!k||k.contains(h.element);return i=D,h.setDomRenderEnabled(D),k??h.element};function E(){if(!(!s||o||r)){r=!0;try{d();let k=S();if(k===l)return;let D=l;l=k,e.onElementChanged(k,D)}finally{r=!1}}}return s=!0,E(),{view:h,get element(){return l??h.element},requestRender:E,dispose:()=>{o=!0,d()}}}var qy,os,NE,FE,$E=ie(()=>{"use strict";qy=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},os=e=>Object.freeze({...e}),NE=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),FE=e=>e?os(e):null});function y_(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=g_.get(e.code)??"unavailable";return new n(o,jy(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",jy("unavailable"))}function UE(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",jy("unsupported_scope"))},i=async(c,d)=>{s(c);try{return await d()}catch(p){throw y_(p,e.errors)}},l=c=>{let d=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){d||(d=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){d||(d=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let d=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(c,d){return i(d.context.scope,async()=>{let p=await n().getConversation(c,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),f=sx(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:$l([],f),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(c,d){return i(d.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,d){await i(d.context.scope,()=>n().deleteConversation(c,{scope:d.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var g_,h_,jy,zE=ie(()=>{"use strict";Mp();g_=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"]]),h_=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."]]),jy=e=>h_.get(e)??"Conversation history is unavailable right now."});var qE={};En(qE,{createHistoryShell:()=>b_});var b_,jE=ie(()=>{"use strict";Dy();$E();Ge();Pu();nr();zE();b_=e=>{let o=By(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",d=null,p=null,f=null,m=null,g=0,h=null,b=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,S=()=>e.historyFeatureEnabled()&&!!r&&!s,E=()=>{let B=e.session.getStatus();return e.isStreaming||B==="paused"||B==="resuming"},k=()=>{let B=e.config.features?.history?.scope;if(B)return B;let Q=e.config.getIdentityProof?"verified-user":"browser",fe=r?.capabilities.scopes;return!fe||fe.includes(Q)?Q:fe[0]??Q},D=()=>l?.scope??k(),z=()=>e.session.getClientSession()?.targetId??null,Y=B=>`${B.state}:${"reason"in B?B.reason:""}`,T=B=>{let Q=Y(B);Q!==m&&(m=Q,e.eventBus.emit("history:identityStatusChanged",{status:B,timestamp:Date.now()}))},W=null,L=null,w=()=>{if(!e.historyFeatureEnabled())return null;let B=e.getHistoryProviderFactory();if(B)return B();let Q=e.config.features?.history?.provider;return Q?typeof Q!="function"?Q:(W!==Q&&(W=Q,L=Q()),L):e.session.isClientTokenMode()?UE({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:fe=>e.session.bindActivatedSession(fe),getClient:()=>e.session.getClient()}):null},x=()=>{b?.(),b=null,C?.(),C=null,s=!1,r=w();let B={...e.historyInternals};r?B.historyProvider=r:delete B.historyProvider,e.historyInternals=B,e.session.setHistoryInternals(e.historyInternals),r&&(b=r.subscribeAvailability?.(Q=>{s=!Q,Q||Kn({restoreFocus:!1}),go()})??null,C=r.subscribeIdentityStatus(Q=>T(Q)),m=Y(r.getIdentityStatus()))},P=()=>{let B=e.config.features?.history?.presentation??"panel";if(B==="panel"||B==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let Q=e.artifactSplitRoot??e.container;return(Q.getBoundingClientRect().width||Q.clientWidth)>=720?"rail":"panel"},I=(B,Q)=>{Q?(B.setAttribute("aria-hidden","true"),B.setAttribute("inert","")):(B.removeAttribute("aria-hidden"),B.removeAttribute("inert"))},J="data-persona-history-suppressed",_=null,j=null,te=null,K=null,X=null,oe="",de=()=>e.header===X?oe:e.config.layout?.showHeader===!1?"none":"",xe=()=>e.historyPresentation==="panel"&&!!te&&K===te.element&&e.config.layout?.showHeader!==!1&&de()!=="none",Te=()=>{for(let B of Array.from(e.header.children))B!==_&&B.setAttribute(J,"")},re=()=>{for(let B of Array.from(e.container.querySelectorAll(`[${J}]`)))B.removeAttribute(J)},N=()=>{let B=te;if(!B)return;if(Array.from(e.header.children).some(Le=>Le!==_&&!Le.hasAttribute(J))){j&&j!==e.header&&(j.style.removeProperty("min-height"),j=null);let Le=e.header.offsetHeight;Le>0&&(e.header.style.minHeight=`${Le}px`,j=e.header)}_||(_=v("div","persona-history-header-host")),B.setHeaderPlacement("external");let fe=B.getHeaderElement();fe.parentNode!==_&&_.replaceChildren(fe),_.parentNode!==e.header&&e.header.appendChild(_),Te()},ke=()=>{j&&(j.style.removeProperty("min-height"),j=null),_&&(te?.setHeaderPlacement("inline"),_.remove(),_=null,re())},ve=null,tt=()=>{if(ve){if(e.body.style.display="none",I(e.body,!0),e.footer.hidden=!0,I(e.footer,!0),xe()){N(),e.header.style.display=de(),I(e.header,!1);return}ke(),e.header.style.display="none",I(e.header,!0)}};e.reapplyHistoryHostChrome=tt;let xt=B=>{let Q=e.body.style.display,fe=e.footer.hidden,Le=e.footer,Xe=e.header,dn=e.header.style.display;X=Xe,oe=dn,ve=()=>{ve=null,ke(),X=null,e.body.style.display=Q,I(e.body,!1),Le.hidden=fe,I(Le,!1),e.footer!==Le&&(e.footer.hidden=!1,I(e.footer,!1)),Xe.style.display=dn,I(Xe,!1),e.header!==Xe&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",I(e.header,!1))},e.footer.parentNode?.insertBefore(B,e.footer),tt()},ht=null,lt=null,Ye=null,dt=null,Pe=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Se=52,U=()=>e.config.features?.history?.rail?.collapsible!==!1,R=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",G=200,ne=400,Z=B=>Math.min(ne,Math.max(G,Math.round(B))),le=()=>e.config.features?.history?.rail?.resizable===!0,Me,Ie=()=>{if(Me===void 0&&(Me=null,e.config.persistState!==!1))try{let B=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));B&&(Me=B)}catch{}return Me},_e=()=>Z(Ie()??e.config.features?.history?.rail?.width??260),ct=B=>{if(Me=B,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(B))}catch{}},Tt=()=>U()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",qe=!1,nt=B=>{let Q=v("img");return Q.src=B,Q.alt="",Q.setAttribute("aria-hidden","true"),Q},Ut=()=>{let B=e.config.features?.history?.rail?.brand;if(!B)return;let Q=!1,fe;return Le=>{if(B.render)try{return B.render({collapsed:Le})??null}catch(Xe){return Q||(Q=!0,console.warn("[persona] history rail brand threw",Xe)),null}return fe===void 0&&(B.iconUrl?fe=nt(B.iconUrl):fe=B.icon?e.renderLucideIcon(B.icon,20):null),fe?fe.cloneNode(!0):null}},tn=()=>e.config.features?.history?.rail?.sections?.map(B=>{let Q=!1,fe=Le=>{Q||(Q=!0,console.warn("[persona] history rail section threw",B.id,Le))};return{id:B.id,title:B.title,placement:B.placement??"above-conversations",items:B.items.map(Le=>{let Xe;return{id:Le.id,label:Le.label,badge:Le.badge,iconNode:()=>{if(Xe!==void 0)return Xe;try{Le.renderIcon?Xe=Le.renderIcon()??null:Le.iconUrl?Xe=nt(Le.iconUrl):Xe=Le.icon?e.renderLucideIcon(Le.icon,20):null}catch(dn){fe(dn),Xe=null}return Xe},onSelect:()=>{try{Le.onSelect()}catch(dn){fe(dn)}}}})}})??[],ee=B=>{let Q=tn();for(let fe of B)Q.some(Le=>Le.id===fe.id)?console.warn("[persona] duplicate history rail section id",fe.id):Q.push(fe);return Q.length?Q:void 0},Re=null,Fe=()=>`${e.currentKeyPrefix()}rail-collapsed`,yt=()=>{if(Re===null&&(Re=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let B=window.localStorage.getItem(Fe());B&&(Re=B==="1")}catch{}return Re},bt=B=>{if(Re=B,e.config.persistState!==!1)try{window.localStorage.setItem(Fe(),B?"1":"0")}catch{}},Ee=()=>e.historyPresentation==="rail"&&U()&&!Tt()&&yt(),He=()=>{},je=()=>{if(Tt()){He();return}bt(!yt()),i?.view.setCollapsed(Ee()),e.applyRailChrome(),e.repinAnchoredMessage()},It=()=>{let B=e.config.features?.history?.rail?.collapseShortcut;return!B||!ku(B)?null:{combo:B,hint:Lu(B),aria:dc(B)}},wn=300,nn="var(--persona-history-overlay-margin,8px)",Ot=null,mt=null,Ht=0,St=null,Kt=null,gn=!1,Zn=0,ss=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,jn=()=>S()&&Tt()&&(e.historyPresentation??P())==="rail",qs=()=>e.historyVisible&&!qe,oo=()=>{Kt!==null&&clearTimeout(Kt),Kt=null},Tr=()=>{e.loadHistoryView().catch(()=>{})},At=()=>{oo(),qe&&(Kt=setTimeout(()=>{Kt=null,!(gn||!qe)&&(St?.contains(document.activeElement)||Kn({restoreFocus:!1}))},wn))},ot=(B,Q)=>{let fe=St?.getBoundingClientRect();if(!fe)return!1;let Le=Ot?.getBoundingClientRect(),Xe=Le?Math.min(Le.top,fe.top):fe.top;return B>=fe.left&&B<=fe.right&&Q>=Xe&&Q<=fe.bottom||!!Le&&B>=Le.left&&B<=Le.right&&Q>=Le.top&&Q<=Le.bottom},Ve=B=>{qe&&(gn=ot(B.clientX,B.clientY),gn?oo():Kt===null&&At())},cn=B=>{e.historyVisible||!jn()||(qe=!0,gt({invoker:Ot,keyboard:B?.keyboard===!0}).then(()=>{e.historyVisible?!gn&&document.activeElement!==Ot&&Kn():qe=!1}))},wt=()=>{let B=K?.querySelector('[data-persona-history-focus="collapse"]');B&&(B.setAttribute("aria-label",qe?o.expandLabel:o.collapseLabel),B.setAttribute("aria-expanded",qe?"false":"true"))},Be=()=>{bt(!1);let B=i;if(!qe||!B){gt({invoker:Ot});return}let Q=document.activeElement===Ot;qe=!1,An(),B.element.remove(),Nt(B.element),wt(),Q&&Vt(),e.repinAnchoredMessage(),go()},ye=()=>{bt(!0),Kn()};He=()=>{!e.historyVisible||qe?Be():ye()};let $e=()=>{let B=It(),Q=e.createHeaderIconButton({ariaLabel:o.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":A,...B?{"aria-keyshortcuts":B.aria}:{}}}),fe=Q.button;fe.addEventListener("mouseenter",()=>{gn=!0,oo(),!(ss()||Date.now()<Zn)&&cn()}),fe.addEventListener("mouseleave",()=>{gn=!1,Zn=0,At()}),fe.addEventListener("focus",()=>{e.historyVisible||Tr()}),fe.addEventListener("click",Le=>{S()&&(Le.detail!==0&&ss()&&!e.historyVisible?cn():Be())}),Ot=fe,mt=Q.wrapper},uo=()=>{if(mt&&!mt.isConnected&&(mt=null,Ot=null),!jn()){mt?.remove(),mt=null,Ot=null;return}Ot||$e();let B=mt,Q=Ot;if(!B||!Q)return;let fe=R()!=="right"?e.header.firstChild:null;(fe??e.header.lastChild)!==B&&e.header.insertBefore(B,fe),B.style.display=qs()||Ht>0?"none":"",Q.setAttribute("aria-label",o.expandLabel),Q.setAttribute("aria-expanded",e.historyVisible?"true":"false"),St&&e.applyRailChrome()},fo=B=>{if(!qe)return;let Q=B.target;Q instanceof Node&&(St?.contains(Q)||mt?.contains(Q)||Q instanceof Element&&Q.closest('.persona-dropdown-menu,[role="alertdialog"]')||Kn({restoreFocus:!1}))};document.addEventListener("pointerdown",fo,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",fo,!0),document.removeEventListener("pointermove",Ve),we?.(),oo()});let eo=null,we=null,ze=16,Pn=B=>{ct(Z(B)),e.applyRailChrome(),e.repinAnchoredMessage()},Mt=()=>{let B=v("div","persona-rail-resizer");return B.tabIndex=0,B.setAttribute("role","separator"),B.setAttribute("aria-orientation","vertical"),B.setAttribute("aria-valuemin",String(G)),B.setAttribute("aria-valuemax",String(ne)),B.addEventListener("pointerdown",Q=>{let fe=lt;if(!fe||Q.button!==0)return;Q.preventDefault(),we?.();let Le=Q.clientX,Xe=fe.getBoundingClientRect().width||_e(),dn=R()==="right"?-1:1,on=Xe,rn=e.mount.ownerDocument;fe.style.transition="none";let ut=Oe=>{on=Z(Xe+dn*(Oe.clientX-Le)),fe.style.flex=`0 0 ${on}px`,B.setAttribute("aria-valuenow",String(on))},Rt=()=>{we=null,rn.removeEventListener("pointermove",ut),rn.removeEventListener("pointerup",Rt),rn.removeEventListener("pointercancel",Rt),fe.style.removeProperty("transition");try{B.releasePointerCapture(Q.pointerId)}catch{}Pn(on)};we=Rt,rn.addEventListener("pointermove",ut),rn.addEventListener("pointerup",Rt),rn.addEventListener("pointercancel",Rt);try{B.setPointerCapture(Q.pointerId)}catch{}}),B.addEventListener("keydown",Q=>{let fe=R()==="right"?-ze:ze,Le=_e(),Xe=Q.key==="ArrowRight"?Le+fe:Q.key==="ArrowLeft"?Le-fe:Q.key==="Home"?G:Q.key==="End"?ne:null;Xe!==null&&(Q.preventDefault(),Pn(Xe))}),B},$=(B,Q)=>{if(!le()||Ee()){we?.(),eo?.remove();return}let fe=eo??Mt();eo=fe,fe.setAttribute("aria-label",o.resizeLabel),fe.setAttribute("aria-valuenow",String(_e())),fe.nextElementSibling!==Q&&B.insertBefore(fe,Q)};e.applyRailChrome=()=>{i?.view.setRailSide(R());let B=R()==="right",Q=St;if(Q){let rn=Ot?Ot.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;Q.style.top=`calc(${Math.max(0,Math.round(rn))}px + ${nn})`,Q.style.width=`${_e()}px`,Q.style.left=B?"":nn,Q.style.right=B?nn:""}let fe=lt,Le=ht,Xe=Ye;if(!fe||!Le||!Xe)return;fe.style.flex=`0 0 ${Ee()?Se:_e()}px`;let dn="1px solid var(--persona-divider,#e5e7eb)";fe.style.borderRight=B?"":dn,fe.style.borderLeft=B?dn:"";let on=B?Xe:fe;Le.firstElementChild!==on&&Le.append(on,B?fe:Xe),$(Le,B?fe:Xe)};let me=B=>{if(dt&&lt){dt.replaceWith(B),dt=null,e.applyRailChrome();return}let Q=v("div","persona-history-rail-shell");Q.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let fe=v("div","persona-history-rail-conversation");fe.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let Le=v("div","persona-history-rail-host");Le.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(Q,e.header.parentNode===e.container?e.header:e.body);for(let Xe of Pe())Xe?.parentNode===e.container&&fe.appendChild(Xe);Q.append(Le,fe),Le.appendChild(B),ht=Q,lt=Le,Ye=fe,e.applyRailChrome()},Ne=()=>{if(ht)return;let B=v("div","persona-history-rail-placeholder");B.style.cssText="flex:1 1 auto;min-height:0",dt=B,me(B),e.repinAnchoredMessage()},ft=()=>{dt&&(An(),e.repinAnchoredMessage())},pt=B=>{let Q=v("div","persona-history-rail-overlay");Q.style.cssText=`position:absolute;bottom:${nn};display:flex;overflow:hidden;z-index:${Ta-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))`,e.container.style.position="relative",e.container.appendChild(Q),Q.appendChild(B),document.addEventListener("pointermove",Ve),St=Q,e.applyRailChrome(),wt()},An=()=>{ve?.(),St&&(gn&&(Zn=Date.now()+150),document.removeEventListener("pointermove",Ve),St.remove(),St=null);let B=ht;if(B){we?.();for(let Q of Pe())Q&&B.contains(Q)&&e.container.insertBefore(Q,B);B.remove(),ht=null,lt=null,Ye=null,dt=null}},Ze=B=>{K=B,B.id=A,B.style.flex="1 1 auto",B.style.minHeight="0"},Nt=B=>{Ze(B),(e.historyPresentation!=="rail"||qe)&&ft(),e.historyPresentation!=="rail"?xt(B):qe?pt(B):me(B)},mo=()=>{if(uo(),as(),!e.historyVisible||!i)return;let B=P();if(B===e.historyPresentation)return;let Q=document.activeElement,fe=Q instanceof HTMLElement&&(i.element.contains(Q)||_?.contains(Q)===!0)?Q:null;An(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=B,i.view.setPresentation(B),i.view.setCollapsed(Ee()),i.requestRender(),i.element.isConnected||Nt(i.element),fe?.isConnected?fe.focus():Vt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),go()},ir=(B,Q)=>_?.querySelector(Q)??B.querySelector(Q),Vt=()=>{let B=i?.element??K;if(!B)return;let Q=ir(B,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(Q){Q.focus();return}let fe=ir(B,".persona-history-title")??B;fe.tabIndex=-1,fe.focus()},gt=async B=>{if(!S()||e.historyVisible)return;let Q=r;if(!Q)return;if(!qe&&jn()&&yt()){uo();return}zi();let fe=++g;c=B?.returnSurface??"conversation",d=B?.invoker??p;let Le=jn()&&!qe;Le&&(Ht+=1,uo(),Ne());let Xe;try{Xe=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),Le&&(Ht-=1,fe===g&&(ft(),uo()));return}if(Le&&(Ht-=1),fe!==g||e.historyVisible)return;l={scope:k()},e.historyPresentation=P(),e.historyVisible=!0;let dn=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",on=e.config.features?.history?.rowAvatar,rn=It(),ut=rn?{hint:rn.hint,aria:rn.aria}:null,Rt={provider:Q,context:l,targetId:z(),presentation:e.historyPresentation,collapsible:U(),collapsed:Ee(),railSide:R(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:Ut(),onToggleCollapse:je,...ut?{collapseShortcut:ut}:{},headerPlacement:dn,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:on===!1?!1:typeof on=="string"?on:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize!==void 0?{pageSize:e.config.features.history.pageSize}:{},onSelect:Oe=>Gn(Oe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Oe=>e.setActiveConversationSummary(Oe),attachTooltip:e.attachTooltip,onStartNew:()=>zo({focusComposer:!0}),onClose:()=>Kn(),onRequestDeleteConversation:Oe=>fn(Oe),onRequestClearHistory:()=>Ys(),...Q.resetDevice?{onRequestResetIdentity:()=>nl()}:{}};i=VE({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>Kn(),createView:({slots:Oe,renderDom:ji,onModelChange:ko,railSections:kr})=>(te=Xe.createHistoryView({...Rt,railSections:ee(kr),slots:Oe,renderDom:ji,onModelChange:ko,onAnnounce:e.announceHistory}),te),onElementChanged:(Oe,ji)=>{if(!ji?.isConnected)return Nt(Oe);Ze(Oe),ji.replaceWith(Oe),tt()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),B?.focus!==!1&&(e.historyPresentation!=="rail"||B?.keyboard===!0)&&Vt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),go(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},zi=()=>{},Kn=B=>{if(!e.historyVisible)return;g+=1;let Q=c,fe=d,Le=i,Xe=B?.restoreFocus!==!1;e.historyVisible=!1;let dn=!1,on=null,rn=()=>{if(!dn){if(dn=!0,zi=()=>{},on!==null&&clearTimeout(on),qe=!1,oo(),An(),Le?.dispose(),Le?.view.destroy(),Le?.element.remove(),i===Le&&(i=null,te=null,K=null,e.historyPresentation=null,l=null,d=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),go(),Xe){let Rt=fe??p;Rt?.isConnected?Rt.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:Q,timestamp:Date.now()})}},ut=Le&&Le.element===Le.view.element?Le.view.playExit():null;if(!ut){rn();return}zi=rn,on=setTimeout(rn,250),ut.then(rn)},js=B=>{if(!(B.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let Q=B.target;if(!(Q instanceof Node)||!(i.element.contains(Q)||qe&&mt?.contains(Q)===!0))return}B.preventDefault(),B.stopPropagation(),Kn()}};e.container.addEventListener("keydown",js),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",js));let ro=0,Kc=250,De=null,Dn=()=>{De&&clearTimeout(De),De=null};e.destroyCallbacks.push(Dn);let Zt=()=>{Dn();let B=e.conversationOpenPendingEl;B&&(e.conversationOpenTakeover=!0,B.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},In=()=>{ro+=1,Dn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),I(e.footer,!1),e.updateWelcome())},Gt=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},_n=(B,Q)=>F("div",{className:Jt("persona-conversation-loading-bubble",Q&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:B}}),Gc=()=>F("div",{className:"persona-conversation-loading-body"},_n("58%",!1),_n("72%",!0),_n("44%",!1)),is=B=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=B,B.hidden=!e.conversationOpenTakeover,e.body.insertBefore(B,e.messagesWrapper),Dn(),e.conversationOpenTakeover||(De=setTimeout(Zt,Kc)),I(e.footer,!0)},vf=()=>{let B={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:Gc},Q=null,fe=e.plugins.find(Le=>Le.renderLoadingIndicator);fe?.renderLoadingIndicator&&(Q=fe.renderLoadingIndicator(B)),Q===null&&e.config.loadingIndicator?.render&&(Q=e.config.loadingIndicator.render(B)),is(F("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},Q??Gc()))},Cf=B=>{let Q=()=>{Gn(B,{focusComposer:!0}).catch(()=>{})},fe=S()?()=>{In(),gt()}:void 0,Le=(rn,ut)=>{let Rt=F("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:rn});return Rt.addEventListener("click",ut),Rt},Xe=()=>F("div",{className:"persona-conversation-loading-error-body"},F("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),F("div",{className:"persona-conversation-loading-error-actions"},Le(o.openConversationRetryLabel,Q),fe?Le(o.openConversationBackLabel,fe):null)),dn=Object.freeze({conversationId:B,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:Q,...fe?{back:fe}:{},defaultRenderer:Xe}),on=null;for(let rn of e.plugins)if(rn.renderHistoryOpenError){try{on=rn.renderHistoryOpenError(dn)}catch(ut){console.warn("[persona] renderHistoryOpenError threw",ut),on=null}if(on)break}is(F("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},on??Xe())),Zt()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&I(e.footer,!0)});let Gn=async(B,{focusComposer:Q=!1}={})=>{let fe=D(),Le=!!i;i?.view.setActiveConversationId(B),In();let Xe=ro;vf(),e.historyVisible&&(e.historyPresentation==="panel"||qe)&&Kn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(B,{scope:fe})}catch(dn){throw Xe===ro&&Cf(B),dn}finally{e.suppressScrollSend=!1}Xe===ro&&(In(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Gt(),xn(),Le||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:B,title:e.activeConversationTitle,scope:fe,timestamp:Date.now()}),Q&&e.maybeFocusInput())},zo=async({focusComposer:B=!1}={})=>{In(),await e.session.startNewConversation({scope:D()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),xn();let Q=e.session.getActiveConversationId();i?.view.setActiveConversationId(Q),e.eventBus.emit("history:conversationStarted",{conversationId:Q,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||qe)&&Kn({restoreFocus:!1}),B&&e.maybeFocusInput()},Ks=async(B,Q)=>{let fe=await e.session.updateConversation(B,{...Q,...Q.title!==void 0?{title:Q.title.trim()}:{}});return i?.view.applyConversationSummary(fe),!i&&B===e.session.getActiveConversationId()&&e.setActiveConversationSummary(fe),fe},Yc=async B=>{let Q=D(),fe=e.session.getActiveConversationId()===B;await e.session.deleteConversation(B,{scope:Q}),i?.view.removeConversationSummary(B),fe&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),xn()),e.eventBus.emit("history:conversationDeleted",{conversationId:B,scope:Q,wasActive:fe,timestamp:Date.now()})},el=async B=>{let Q=B?.scope??D(),fe=B?.allTargets?null:B?.targetId??z(),Le=await e.session.clearConversationHistory({...fe?{targetId:fe}:{},scope:Q});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),xn(),e.eventBus.emit("history:cleared",{deleted:Le.deleted,scope:Q,targetId:fe,timestamp:Date.now()}),Le},tl=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let B=!1;try{B=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let Q=e.storageAdapter;Q?.clear&&e.runStorageMutation(()=>Q.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),xn(),Kn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(B?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:B,timestamp:Date.now()}),{remoteRevocationConfirmed:B}},qi=()=>e.artifactSplitRoot?e.panel:e.container,Gs=async B=>{let Q=await e.loadHistoryView().catch(()=>null);return typeof Q?.showHistoryConfirm=="function"?Q.showHistoryConfirm(B):window.confirm(`${B.title}
1161
+ `});function By(e){if(!e)return uf;let t={...uf};for(let n of UD){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var UD,uf,Dy=ie(()=>{"use strict";UD=["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"],uf={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 Vc(e){if(!e)return Fc;let t={...Fc};for(let[n,o]of Object.entries(e))typeof o=="string"&&o.length>0&&(t[n]=o);return t}function Mr(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n)}var Fc,$c=ie(()=>{"use strict";Dy();Fc={...uf,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function zD(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function Oy(e,t){let n=Date.parse(e);return Number.isFinite(n)?n:t}function qD(e,t){let n=Oy(e,t),o=zD(t);if(n>=o)return"today";if(n>=o-_y)return"yesterday";if(n>=o-7*_y)return"previous-7-days";if(n>=o-30*_y)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function jD(e,t,n,o){if(e==="today")return o.groupToday;if(e==="yesterday")return o.groupYesterday;if(e==="previous-7-days")return o.groupPrevious7Days;if(e==="previous-30-days")return o.groupPrevious30Days;let r=new Date(Oy(t,n));return Mr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function AE(e,t,n,o="time"){let r=e.filter(i=>i.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let i=e.filter(l=>!l.starred);return i.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:i}),s}for(let i of e){if(i.starred)continue;let l=qD(i.updatedAt,t),c=s[s.length-1];if(c&&c.key===l){c.items.push(i);continue}s.push({key:l,label:jD(l,i.updatedAt,t,n),items:[i]})}return s}function ME(e,t,n){let o=Math.max(0,t-Oy(e,t)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return Mr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return Mr(n.relativeHours,{value:s});let i=Math.floor(s/24);if(i<7)return Mr(n.relativeDays,{value:i});let l=Math.floor(i/7);return i<365?Mr(n.relativeWeeks,{value:l}):Mr(n.relativeYears,{value:Math.floor(i/365)})}function TE(e,t){return e===1?t.messageCountLabelOne:Mr(t.messageCountLabel,{count:e})}var _y,Ny=ie(()=>{"use strict";$c();_y=864e5});function zs(e,t=20){let n=document.createElementNS(ff,"svg");if(n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),e==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(ff,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=GD[e];if(o){let r=document.createElementNS(ff,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of KD[e]){let s=document.createElementNS(ff,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var ff,KD,GD,Fy=ie(()=>{"use strict";ff="http://www.w3.org/2000/svg",KD={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},GD={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function XD(e){let t=F("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return YD.test(e)?t.appendChild(F("img",{attrs:{src:e,alt:"",loading:"lazy"}})):t.textContent=e,t}function EE(e){let{conversation:t,copy:n,busy:o,pending:r}=e,s=o||r!==null,i=t.title.trim().length>0,l=t.starred?(()=>{let g=zs("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),F("span",{className:"persona-history-row-star"},g,F("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,c=F("div",{className:"persona-history-row-head"},F("span",{className:"persona-history-row-title persona-history-truncate",text:i?t.title:t.preview??""}),l,F("time",{className:"persona-history-row-time",attrs:{datetime:t.updatedAt},text:ME(t.updatedAt,e.nowMs,n)})),d=i&&t.preview?F("span",{className:"persona-history-row-preview persona-history-truncate",text:t.preview}):null,p=F("button",{className:Jt("persona-history-row",e.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":QD(t.id),"data-persona-history-conversation":t.id,...e.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},e.avatar?XD(e.avatar):null,F("div",{className:"persona-history-row-body"},c,d,F("span",{className:"persona-history-row-count persona-history-sr-only",text:TE(t.messageCount,n)})));p.addEventListener("click",()=>{s||e.onOpen()});let f=e.showDelete?Vy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${t.title}`,focusKey:JD(t.id),open:e.menuOpen,inert:s,onToggle:e.onToggleMenu}):null;return F("li",{className:Jt("persona-history-item",!e.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":t.id}},p,f,e.menuOpen&&e.showDelete?ZD(e):null,e.error?e_(e.error,n,t.id):null)}function ZD(e){let{conversation:t,copy:n}=e;return $y({label:`${n.rowActionsLabel}: ${t.title}`,items:[{label:n.deleteConversationLabel,focusKey:Uc(t.id),danger:!0,onSelect:e.onDelete}],onCloseMenu:e.onCloseMenu})}function Vy(e){let t=F("button",{className:Jt("persona-history-icon-button",e.className),attrs:{type:"button","aria-label":e.label,"aria-haspopup":"menu","aria-expanded":e.open?"true":"false","data-persona-history-focus":e.focusKey,...e.inert?{"aria-disabled":"true"}:{}}});t.appendChild(zs("ellipsis",e.iconSize));let n=()=>t.getAttribute("aria-disabled")==="true";return t.addEventListener("click",o=>{o.stopPropagation(),!n()&&e.onToggle()}),t.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||t.getAttribute("aria-expanded")==="true")&&e.onToggle())}),t}function $y(e){let t=F("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":e.label}});for(let n of e.items){let o=F("button",{className:Jt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{e.onCloseMenu(),n.onSelect()}),t.appendChild(o)}return t.addEventListener("keydown",n=>{let o=Array.from(t.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){e.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),t}function e_(e,t,n){let o=F("button",{className:"persona-history-secondary persona-history-state-action",text:t.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",e.retry),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:e.message}),o)}var YD,QD,JD,Uc,kE=ie(()=>{"use strict";Ge();Fy();Ny();YD=/^(https?:|\/|data:)/i;QD=e=>`row:${e}`,JD=e=>`menu:${e}`,Uc=e=>`menu-item:${e}`});function t_(e){switch(e){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return e;default:return"unknown"}}function LE(e){if(Tp(e)){if(e.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:e.retryAfterSeconds??0};let t=t_(e.code);return{kind:"error",reason:t,retryable:t!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function n_(e,t){switch(e.state){case"authentication_required":return{title:t.authenticationRequiredTitle,description:t.authenticationRequiredDescription};case"identity_provider_failed":return{title:t.identityProviderFailedTitle,description:t.identityProviderFailedDescription};case"configuration_error":return{title:t.proofNotAdmittedTitle,description:t.proofNotAdmittedDescription};default:return null}}function o_(e,t){switch(e){case"authentication_required":case"authentication_failed":return{title:t.authenticationRequiredTitle,description:t.authenticationRequiredDescription};case"identity_provider_failed":return{title:t.identityProviderFailedTitle,description:t.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:t.proofNotAdmittedTitle,description:t.proofNotAdmittedDescription};case"unavailable":return{title:t.unavailableTitle,description:t.unavailableDescription};default:return{title:t.errorTitle,description:t.errorDescription}}}function mf(e,t,n,o){let r=F("button",{className:"persona-history-secondary persona-history-state-action",text:e,attrs:{type:"button","data-persona-history-focus":t,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function zc(e,t,n,o,r){return F("div",{className:"persona-history-state",attrs:{"data-persona-history-state":e,...r?{role:"alert"}:{role:"status"}}},F("p",{className:"persona-history-state-title",text:t}),F("p",{className:"persona-history-state-description",text:n}),o)}function r_(e){let t=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>F("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},F("div",{className:"persona-history-skeleton-head"},F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:t[r]}}),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return F("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":e.loadingLabel}},...o)}function PE(e){let{state:t,copy:n,busy:o}=e;if(t.kind==="loading")return r_(n);if(t.kind==="empty"){let l=n_(e.identityStatus,n);return l?zc("identity",l.title,l.description,e.onRetry?mf(n.retryIdentityLabel,"state-retry",o,e.onRetry):null,!0):zc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(t.kind==="rate_limited"){let l=t.retryAfterSeconds>0?Mr(n.rateLimitedWaitDescription,{seconds:t.retryAfterSeconds}):n.rateLimitedDescription;return zc("rate_limited",n.rateLimitedTitle,l,e.onRetry?mf(n.retryLabel,"state-retry",o,e.onRetry):null,!1)}if(t.kind==="new_conversation_required")return zc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,e.onStartNew?mf(n.newConversationLabel,"state-retry",o,e.onStartNew):null,!0);let{title:r,description:s}=o_(t.reason,n),i=t.reason==="authentication_required"||t.reason==="authentication_failed"||t.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return zc("error",r,s,t.retryable&&e.onRetry?mf(i,"state-retry",o,e.onRetry):null,!0)}var IE=ie(()=>{"use strict";Ge();$c();zl()});function gf(e){return`${e.state}:${"reason"in e?e.reason:""}`}function RE(e,t){switch(e.state){case"verified":return{title:t.verifiedTitle,description:t.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:t.verifyingTitle,description:t.verifyingDescription,pending:!0};case"authentication_required":return{title:t.authenticationRequiredTitle,description:t.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:t.identityProviderFailedTitle,description:t.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:t.proofNotAdmittedTitle,description:t.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:t.unavailableTitle,description:t.unavailableDescription,pending:!1};default:return{title:t.browserOnlyTitle,description:t.browserOnlyDescription,pending:!1}}}function u_(e){return e.state==="verified"||e.state==="browser_only"}function f_(e){return e.state==="authentication_required"||e.state==="identity_provider_failed"||e.state==="configuration_error"}function Uy(e){let t=Vc(e.copy),n=e.now??(()=>Date.now()),o=e.pageSize??s_,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],i=null,l={kind:"loading",phase:"initial"},c=null,d=e.activeConversationId,p=e.provider.getIdentityStatus(),f=gf(p),m=null,g=!1,h=!1,b=0,C=e.presentation,A=e.collapsible!==!1,S=e.collapsed===!0,E=e.railSide==="right",k=e.renderDom!==!1,D=new Map,z=null,Y=CE(),T=$=>{!k&&e.onAnnounce?e.onAnnounce($):Y.announce($)},W=()=>c!==null,L=`${r}-body`,w=F("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),x=()=>C==="rail"&&A,P,I=()=>{if(e.railBrand){if(!x()){w.classList.remove("persona-history-back--branded");return}if(P===void 0){let $=e.railBrand(!0);P=$?F("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},$):null}P&&(w.classList.add("persona-history-back--branded"),w.appendChild(P))}},J=()=>{let $=x(),me=C==="rail";w.setAttribute("data-persona-history-focus",$?"collapse":"close"),w.setAttribute("aria-label",$?S?t.expandLabel:t.collapseLabel:me?t.closeLabel:t.backLabel),$?(w.setAttribute("aria-expanded",S?"false":"true"),w.setAttribute("aria-controls",L),e.collapseShortcut?.aria&&w.setAttribute("aria-keyshortcuts",e.collapseShortcut.aria)):(w.removeAttribute("aria-expanded"),w.removeAttribute("aria-controls"),w.removeAttribute("aria-keyshortcuts")),w.replaceChildren(zs($?"panel-left":me?"x":"arrow-left")),I()};J(),w.addEventListener("click",()=>{x()?e.onToggleCollapse?.():e.onClose()});let _=F("h2",{className:"persona-history-title",text:t.viewTitle,attrs:{id:r}}),j=F("span",{className:"persona-history-scope-title"}),te=F("p",{className:"persona-history-scope"},F("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},zs("monitor",14)),j),K=F("div",{className:"persona-history-heading-group"},_),X=!1,oe,de=()=>{let $=C==="rail",me=$?e.renderRailHeader:void 0,Ne=null,ft=me!==void 0;if(me)try{Ne=me({collapsed:S,defaultTitle:t.viewTitle})}catch(pt){ft=!1,X||(X=!0,console.warn("[persona] history rail renderHeader threw",pt))}if(!ft&&$&&e.railBrand){if(oe===void 0){let pt=e.railBrand(!1);oe=pt?F("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},F("span",{className:"persona-history-brand-mark"},pt),F("span",{className:"persona-history-wordmark",text:t.viewTitle})):null}oe&&(ft=!0,Ne=oe)}_.classList.toggle("persona-history-sr-only",ft),K.replaceChildren(_),Ne&&K.appendChild(Ne)};de();let xe=F("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":t.newConversationLabel}});xe.appendChild(zs("plus")),xe.addEventListener("click",()=>{fo()});let Te=[w,xe].map($=>e.attachTooltip?.({anchor:$,text:()=>$.getAttribute("aria-label")??"",...$===w&&e.collapseShortcut?{hint:()=>x()?e.collapseShortcut.hint:""}:{}})),re=F("div",{className:"persona-history-topbar"}),N=null,ke=()=>{let $=C==="rail",me=$?E?"rail-right":"rail":"panel";me!==N&&(N=me,me==="rail"?re.append(K,w):re.append(w,K),$?xe.remove():re.appendChild(xe),Z.classList.toggle("persona-history-view--rail-right",me==="rail-right"))},ve=F("div",{className:"persona-history-scope-alert"}),tt=`${r}-scope`,xt=zs("plus",18),ht=F("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},xt,F("span",{text:t.newConversationLabel}));ht.addEventListener("click",()=>{fo()});let lt=F("div",{className:"persona-history-list-region"}),Ye=e.showDeleteAll!==!1,dt=!!e.provider.resetDevice,Pe=e.listActions??[],Se=Ye||dt||Pe.length>0?Vy({className:"persona-history-list-options",label:t.listOptionsLabel,focusKey:`menu:${Ui}`,open:!1,inert:!0,iconSize:16,onToggle:()=>Ve(Ui)}):null,U=F("h3",{className:"persona-history-conversations-title",text:t.conversationsTitle}),R=F("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Ui}},U,e.showScopeStatus?te:null,Se),G=F("div",{className:"persona-history-body",attrs:{id:L}},e.showScopeStatus?ve:null,ht,R,lt),ne=e.headerPlacement??"inline";ne==="external"&&re.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Z=F("div",{className:Jt("persona-history-view",`persona-history-view--${e.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":e.presentation}},Y.element,ne==="inline"?re:null,G),le=()=>{Z.classList.toggle("persona-history-view--rail-collapsed",S&&x())};le(),ke();let Me=($,me)=>{let Ne=`${r}-s${me}`,ft=F("div",{className:Jt("persona-history-nav",$.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":$.id,...$.title?{"aria-labelledby":Ne}:{"aria-label":$.id}}});$.title&&ft.appendChild(F("h3",{className:"persona-history-group-heading",text:$.title,attrs:{id:Ne}}));for(let pt of $.items){let An=pt.iconNode?.()??null,Ze=F("button",{className:Jt("persona-history-nav-item",An&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":pt.label,"data-persona-rail-item":pt.id}},An?F("span",{className:"persona-history-nav-icon"},An):null,F("span",{className:"persona-history-nav-label persona-history-truncate",text:pt.label}),pt.badge?F("span",{className:"persona-history-nav-badge",text:pt.badge}):null);Ze.addEventListener("click",()=>pt.onSelect()),ft.appendChild(Ze)}return ft},Ie=null,_e=null,ct=()=>{!Ie||!k||C!=="rail"||S===_e||(_e=S,e.railSections.forEach(($,me)=>{if(!$.render)return;let Ne=Ie[me],ft=$.title?Ne.firstElementChild:null,pt=null;try{pt=$.render(S)}catch(An){$.render=void 0,console.warn("[persona] history rail section threw",$.id,An)}Ne.replaceChildren(...ft?[ft]:[],...pt?[pt]:[]),Ne.hidden=!pt}))},Tt=()=>{let $=e.railSections;if(Z.classList.toggle("persona-history-view--has-nav",C==="rail"&&!!$?.some(me=>me.placement==="above-conversations")),!!$?.length){if(C!=="rail"){Ie?.forEach(me=>me.remove());return}Ie??=$.map(Me);for(let me of["above-conversations","below-conversations","footer"]){let Ne=me==="above-conversations"?R.parentNode===G?R:lt:null;$.forEach((ft,pt)=>{ft.placement===me&&G.insertBefore(Ie[pt],Ne)})}ct()}};Tt(),Yp(Z,"persona-history-view",xE);let qe=($,me)=>{let Ne=Z.ownerDocument.defaultView?.getComputedStyle(Z).getPropertyValue($),ft=Number.parseFloat(Ne??"");return Number.isFinite(ft)&&ft>=0?ft:me},nt=($,me)=>Z.ownerDocument.defaultView?.getComputedStyle(Z).getPropertyValue($).trim()||me,Ut=null,tn=()=>{Ut!==null&&(clearTimeout(Ut),Ut=null),Z.removeEventListener("animationend",tn),Z.classList.remove("persona-history-view--enter")};Z.addEventListener("animationend",tn),Ut=setTimeout(()=>{Ut=setTimeout(tn,qe("--persona-history-enter-ms",i_)+60)},0);let ee=null,Re=()=>{ee!==null&&(clearTimeout(ee),ee=null),re.classList.remove("persona-history-topbar--shell-enter")},Fe=()=>{Re(),re.classList.add("persona-history-topbar--shell-enter"),ee=setTimeout(Re,HE+60)};ne==="external"&&(ee=setTimeout(Re,HE+60));let yt=[],bt=null,Ee=()=>{if(bt)return bt;if(h||d_()||typeof Z.animate!="function")return tn(),null;let $=Z.ownerDocument.defaultView?.getComputedStyle(G).opacity||"1";tn(),Z.style.pointerEvents="none",je.style.pointerEvents="none";let me={duration:qe("--persona-history-exit-ms",a_),easing:nt("--persona-history-exit-easing",l_),fill:"forwards"},Ne=c_[C];return yt=[G.animate([{opacity:$,transform:"none"},{opacity:0,transform:`translateX(${Ne}px)`}],me)],bt=Promise.all(yt.map(p_)).then(()=>{}),bt},He=($,me)=>{$&&(me?$.setAttribute("aria-disabled","true"):$.removeAttribute("aria-disabled"))},je=re,It=null,wn=()=>{let $=e.slots?.header;if(!$)return;let me=`${C}|${gf(p)}|${c?`${c.kind}:${"conversationId"in c?c.conversationId:""}`:""}`;if(me===It)return;It=me;let Ne=$({identityStatus:p,pendingAction:c,copy:t,defaultRenderer:()=>re})??re;Ne!==je&&(je.replaceWith(Ne),je=Ne)},nn=null,Ot=()=>{if(!e.showScopeStatus)return;let $=gf(p);if($===nn)return;nn=$;let me=RE(p,t);j.textContent=me.title;let Ne=u_(p);if(te.hidden=!Ne,ve.replaceChildren(...Ne?[]:[F("span",{className:"persona-history-scope-alert-title",text:me.title})],F("span",{className:"persona-history-scope-description",text:me.description,attrs:{id:tt}})),ve.setAttribute("data-persona-history-scope-tone",Ne?"ambient":"attention"),Ne?te.setAttribute("aria-describedby",tt):te.removeAttribute("aria-describedby"),me.pending?ve.setAttribute("role","status"):ve.removeAttribute("role"),ve.setAttribute("data-persona-history-identity",p.state),te.setAttribute("data-persona-history-identity",p.state),f_(p)){let ft=F("button",{className:"persona-history-secondary persona-history-state-action",text:t.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});ft.addEventListener("click",()=>{W()||Be("refresh")}),ve.appendChild(ft)}},mt=$=>c?c.kind==="open"&&c.conversationId===$?"opening":c.kind==="delete"&&c.conversationId===$?"deleting":null:null,Ht=()=>{let $=document.activeElement;return!($ instanceof HTMLElement)||!Z.contains($)?null:$.getAttribute("data-persona-history-focus")},St=$=>{if(g&&m){g=!1;let me=Z.querySelector(`[data-persona-history-focus="${Uc(m)}"]`);if(me){me.focus();return}}$&&Z.querySelector(`[data-persona-history-focus="${$}"]`)?.focus()},Kt=()=>{if(!z)return null;let $=F("button",{className:"persona-history-secondary persona-history-state-action",text:t.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),me=z;return $.addEventListener("click",()=>{W()||me.retry()}),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:me.message}),$)},gn=()=>AE(s,n(),t,e.grouping).map(($,me)=>{let Ne=`${r}-g${me}`,ft=F("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Ne}});for(let pt of $.items){let An=()=>EE({conversation:pt,active:pt.id===d,pending:mt(pt.id),busy:W(),menuOpen:m===pt.id,error:D.get(pt.id)??null,avatar:e.rowAvatar,showDelete:e.showDelete!==!1,nowMs:n(),copy:t,onOpen:()=>{$e(pt.id)},onToggleMenu:()=>Ve(pt.id),onCloseMenu:mo=>ot(mo),onDelete:()=>{uo(pt.id)}}),Nt=e.slots?.conversation?.({conversation:pt,active:pt.id===d,pending:mt(pt.id),open:()=>$e(pt.id),requestDelete:()=>uo(pt.id),defaultRenderer:An})??An();ft.appendChild(Nt instanceof HTMLLIElement?Nt:F("li",{className:"persona-history-item"},Nt))}return F("div",{className:"persona-history-group",attrs:{"data-persona-history-group":$.key}},F("h3",{className:Jt("persona-history-group-heading",$.key==="recent"&&"persona-history-sr-only"),text:$.label,attrs:{id:Ne}}),ft)}),Zn=()=>{if(!i)return null;let $=c?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",me=F("button",{className:"persona-history-secondary persona-history-load-more",text:$?t.loadingMoreLabel:t.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...$?{"aria-busy":"true","aria-disabled":"true"}:{},...W()&&!$?{"aria-disabled":"true"}:{}}});return me.addEventListener("click",()=>{W()||Be("load-more")}),me},ss=()=>{let $=Ht(),me=[Kt()],Ne=s.length>0;if(Ne&&(me.push(...gn()),me.push(Zn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Ne)){let pt=l,An=pt.kind==="loading"?void 0:()=>Be("refresh"),Ze=pt.kind==="new_conversation_required"?()=>fo():void 0,Nt=()=>PE({state:pt,copy:t,identityStatus:p,busy:W(),...An?{onRetry:()=>{An()}}:{},...Ze?{onStartNew:()=>{Ze()}}:{}}),mo=e.slots?.state?.({state:pt,identityStatus:p,copy:t,...An?{retry:An}:{},...Ze?{startNewConversation:Ze}:{},defaultRenderer:Nt});me.push(mo??Nt())}lt.replaceChildren(...me.filter(pt=>!!pt)),St($)},jn=()=>{let $=l.kind==="loading"&&s.length===0,me=[],Ne=()=>me.length===0?Uc(Ui):`${Uc(Ui)}-${me.length}`;if(!$)for(let ft of Pe)me.push({label:ft.label,focusKey:Ne(),danger:ft.danger===!0,onSelect:()=>{ft.onSelect({conversations:[...s]})}});return Ye&&!(s.length===0&&(l.kind==="empty"||$))&&me.push({label:t.clearHistoryLabel,focusKey:Ne(),danger:!0,onSelect:()=>{eo()}}),dt&&!$&&me.push({label:t.resetIdentityLabel,focusKey:Ne(),danger:!0,onSelect:()=>{ze()}}),me},qs=()=>{if(He(ht,W()),He(xe,W()),Se){let $=jn(),me=l.kind==="loading"&&s.length===0;Se.hidden=$.length===0&&!me,He(Se,W()||$.length===0),Se.setAttribute("aria-expanded",m===Ui?"true":"false");let Ne=R.querySelector(".persona-history-menu");if(m!==Ui||$.length===0)Ne?.remove();else{let ft=$y({label:t.listOptionsLabel,items:$,onCloseMenu:pt=>ot(pt)});Ne?Ne.replaceWith(ft):R.appendChild(ft)}}R.hidden=C!=="rail"&&(!Se||Se.hidden)&&(!e.showScopeStatus||te.hidden)},oo,Tr=()=>{let $=e.onActiveConversationChange;if(!$)return;let me=s.find(ft=>ft.id===d)??null,Ne=me?`${me.id}\0${me.title}\0${me.starred?1:0}`:"";Ne!==oo&&(oo=Ne,$(me))},At=()=>{if(!h){if(Tr(),!k){e.onModelChange?.();return}wn(),Ot(),qs(),ss(),ct()}},ot=$=>{if(!m)return;let me=m;m=null,g=!1,At(),$?.restoreFocus&&Z.querySelector(`[data-persona-history-focus="menu:${me}"]`)?.focus()},Ve=$=>{if(m===$){ot({restoreFocus:!0});return}m=$,g=!0,At()},cn=$=>{if(!m)return;let me=$.target;me instanceof Node&&Z.contains(me)&&me.closest?.(`[data-persona-history-item="${m}"]`)||ot()};document.addEventListener("pointerdown",cn,!0);let wt=$=>{$.key!=="Escape"||!m||($.stopPropagation(),ot({restoreFocus:!0}))};Z.addEventListener("keydown",wt);async function Be($){if(h)return;let me=++b,Ne=$==="load-more"?i:null;if(!($==="load-more"&&!Ne)){c={kind:$==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:$},$!=="load-more"&&(D.clear(),z=null),ot(),At();try{let ft=await e.provider.list({limit:o,context:e.context,...Ne?{cursor:Ne}:{},...e.targetId?{targetId:e.targetId}:{}});if(h||me!==b)return;s=Ne?[...s,...ft.items]:ft.items,i=ft.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(ft){if(h||me!==b)return;l=LE(ft)}finally{!h&&me===b&&(c=null,At())}}}let ye=$=>{s=s.filter(me=>me.id!==$),D.delete($),d===$&&(d=null),s.length===0&&!i&&(l={kind:"empty"})};async function $e($){if(!(W()||h)){D.delete($),ot(),c={kind:"open",conversationId:$},At();try{if(await e.onSelect($),h)return;d=$}catch{if(h)return;D.set($,{message:t.openFailedLabel,retry:()=>{$e($)}})}finally{h||(c=null,At())}}}async function uo($){if(W()||h)return"cancelled";D.delete($),c={kind:"delete",conversationId:$},At();try{let me=await e.onRequestDeleteConversation($);return h||me==="deleted"&&(ye($),T(t.conversationRemovedNotice)),me}catch(me){return h||(Tp(me)&&me.code==="not_found"?ye($):D.set($,{message:t.deleteFailedLabel,retry:()=>{uo($)}})),"cancelled"}finally{h||(c=null,At())}}async function fo(){if(!(W()||h)){z=null,ot(),c={kind:"start-new"},At();try{if(await e.onStartNew(),h)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(h)return;z={message:t.errorDescription,retry:()=>{fo()}}}finally{h||(c=null,At())}}}async function eo(){if(W()||h)return"cancelled";z=null,ot(),c={kind:"clear"},At();try{let $=await e.onRequestClearHistory();return h||$==="cleared"&&(s=[],i=null,d=null,l={kind:"empty"},T(t.historyClearedNotice)),$}catch{return h||(z={message:t.errorDescription,retry:()=>{eo()}}),"cancelled"}finally{h||(c=null,At())}}let we={outcome:"cancelled"};async function ze(){if(W()||h||!e.onRequestResetIdentity)return we;z=null,ot(),c={kind:"reset"},At();try{let $=await e.onRequestResetIdentity();return h||$.outcome==="reset"&&(T($.remoteRevocationConfirmed?t.identityResetNotice:t.identityResetUnconfirmedNotice),c=null,await Be("refresh")),$}catch{return h||(z={message:t.errorDescription,retry:()=>{ze()}}),we}finally{!h&&c?.kind==="reset"&&(c=null,At())}}let Pn=e.provider.subscribeIdentityStatus($=>{if(h)return;let me=gf($),Ne=me!==f;p=$,f=me,At(),Ne&&$.state!=="verifying"&&T(RE($,t).title)}),Mt=e.provider.subscribeAvailability?.($=>{if(!h){if($){Be("refresh");return}s=[],i=null,l={kind:"error",reason:"unavailable",retryable:!1},At()}});return At(),Be("initial"),{element:Z,copy:t,getModel:()=>({conversations:s,activeConversationId:d,state:l,pendingAction:c,identityStatus:p,nextCursor:i}),operations:{refresh:async()=>{W()||await Be("refresh")},loadMore:async()=>{W()||await Be("load-more")},openConversation:$=>$e($),startNewConversation:()=>fo(),requestDeleteConversation:$=>uo($),requestClearConversationHistory:()=>eo(),requestResetHistoryIdentity:()=>ze()},setDomRenderEnabled:$=>{$!==k&&(k=$,$&&At())},refresh:()=>{Be("refresh")},setPresentation:$=>{if($===C)return;tn(),C=$,It=null;let me=$==="rail";Z.classList.toggle("persona-history-view--panel",!me),Z.classList.toggle("persona-history-view--rail",me),Z.setAttribute("data-persona-history-presentation",$),J(),le(),ke(),de(),Tt(),At()},setCollapsed:$=>{$!==S&&(S=$,le(),J(),de(),ct())},setRailSide:$=>{E=$==="right",ke()},getHeaderElement:()=>je,setHeaderPlacement:$=>{if($===ne)return;ne=$;let me=$==="external";if(re.classList.toggle("persona-history-topbar--shell",me),me){Fe(),je.remove();return}Re(),Z.insertBefore(je,G)},setActiveConversationId:$=>{d!==$&&(d=$,At())},applyConversationSummary:$=>{let me=s.findIndex(Ne=>Ne.id===$.id);me!==-1&&(s[me]=$,At())},removeConversationSummary:$=>{s.some(me=>me.id===$)&&(ye($),At())},setNewConversationRequired:$=>{$?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),At()},playExit:Ee,destroy:()=>{h=!0,b+=1,tn(),Re(),Te.forEach($=>$?.destroy()),je.remove(),yt.forEach($=>$.cancel()),yt=[],Pn(),Mt?.(),document.removeEventListener("pointerdown",cn,!0),Z.removeEventListener("keydown",wt),Y.destroy(),Z.remove(),Z.replaceChildren()}}}var s_,Ui,i_,HE,a_,l_,c_,d_,p_,WE=ie(()=>{"use strict";Ra();Ge();wE();SE();$c();Ny();Fy();kE();IE();zl();s_=25,Ui="persona:list-options",i_=180,HE=120,a_=160,l_="cubic-bezier(0.4, 0, 1, 1)",c_={panel:20,rail:12},d_=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,p_=e=>e.finished?e.finished.then(()=>{},()=>{}):Promise.resolve()});var zy=ie(()=>{"use strict";WE();$c()});function BE(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=F("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=F("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=F("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"}},F("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),F("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),F("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,i));for(let d of[s,i])d.style.minHeight="44px",d.style.minWidth="88px",d.style.padding="0 16px",d.style.borderRadius="var(--persona-radius-md, 0.5rem)",d.style.cursor="pointer",d.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",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=F("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(d=>{let p=!1,f=g=>{p||(p=!0,c.removeEventListener("keydown",m,!0),c.remove(),t?.focus(),d(g))};function m(g){if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),f(!1);return}if(g.key!=="Tab")return;let h=Array.from(l.querySelectorAll(m_));if(h.length===0)return;let b=h[0],C=h[h.length-1],A=document.activeElement;g.shiftKey&&(A===b||!l.contains(A))?(g.preventDefault(),C.focus()):!g.shiftKey&&A===C&&(g.preventDefault(),b.focus())}c.addEventListener("keydown",m,!0),c.addEventListener("pointerdown",g=>{g.target===c&&f(!1)}),s.addEventListener("click",()=>f(!1)),i.addEventListener("click",()=>f(!0)),e.host.appendChild(c),s.focus()})}var m_,DE=ie(()=>{"use strict";Ge();m_="button:not([disabled])"});var _E={};En(_E,{HISTORY_VIEW_COPY_DEFAULTS:()=>Fc,createHistoryView:()=>Uy,resolveHistoryViewCopy:()=>Vc,showHistoryConfirm:()=>BE});var OE=ie(()=>{"use strict";zy();DE();zy()});function $E(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],d=()=>{for(let k of c.splice(0))try{k()}catch(D){qy("renderHistoryView cleanup",D)}},p=(k,D)=>{for(let z of t){let Y=z[k];if(Y)try{let T=Y(D);if(T)return T}catch(T){qy(k,T)}}return null},f=()=>({presentation:e.getPresentation(),config:n}),m={header:k=>i?p("renderHistoryHeader",Object.freeze({...f(),returnSurface:e.getReturnSurface(),identityStatus:os(k.identityStatus),pendingAction:VE(k.pendingAction),copy:os(k.copy),actions:Object.freeze({close:b.close,startNewConversation:b.startNewConversation}),defaultRenderer:k.defaultRenderer})):null,conversation:k=>i?p("renderHistoryConversation",Object.freeze({...f(),conversation:FE(k.conversation),active:k.active,pending:k.pending,open:k.open,requestDelete:k.requestDelete,defaultRenderer:k.defaultRenderer})):null,state:k=>i?p("renderHistoryState",Object.freeze({...f(),state:os(k.state),identityStatus:os(k.identityStatus),copy:os(k.copy),...k.retry?{retry:k.retry}:{},...k.startNewConversation?{startNewConversation:k.startNewConversation}:{},defaultRenderer:k.defaultRenderer})):null},g=t.flatMap(k=>(k.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:z=>D.render(Object.freeze({collapsed:z,presentation:e.getPresentation(),actions:b}))}))),h=e.createView({slots:m,renderDom:!1,onModelChange:()=>E(),railSections:g}),b=Object.freeze({...h.operations,close:e.close}),C=()=>(i=!0,h.setDomRenderEnabled(!0),h.element),A=k=>Object.freeze({conversations:Object.freeze(k.conversations.map(FE)),activeConversationId:k.activeConversationId,state:os(k.state),pendingAction:VE(k.pendingAction),identityStatus:os(k.identityStatus),nextCursor:k.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:os(h.copy),actions:b,defaultRenderer:C,requestRender:()=>E(),onCleanup:D=>{c.push(D)}}),S=()=>{i=!1;let k=null;for(let z of t)if(z.renderHistoryView){try{k=z.renderHistoryView(A(h.getModel()))}catch(Y){qy("renderHistoryView",Y),k=null}if(k)break}let D=!k||k.contains(h.element);return i=D,h.setDomRenderEnabled(D),k??h.element};function E(){if(!(!s||o||r)){r=!0;try{d();let k=S();if(k===l)return;let D=l;l=k,e.onElementChanged(k,D)}finally{r=!1}}}return s=!0,E(),{view:h,get element(){return l??h.element},requestRender:E,dispose:()=>{o=!0,d()}}}var qy,os,FE,VE,UE=ie(()=>{"use strict";qy=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},os=e=>Object.freeze({...e}),FE=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),VE=e=>e?os(e):null});function b_(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=h_.get(e.code)??"unavailable";return new n(o,jy(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",jy("unavailable"))}function zE(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",jy("unsupported_scope"))},i=async(c,d)=>{s(c);try{return await d()}catch(p){throw b_(p,e.errors)}},l=c=>{let d=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){d||(d=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){d||(d=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let d=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(c,d){return i(d.context.scope,async()=>{let p=await n().getConversation(c,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),f=ix(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:$l([],f),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(c,d){return i(d.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,d){await i(d.context.scope,()=>n().deleteConversation(c,{scope:d.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var h_,y_,jy,qE=ie(()=>{"use strict";Mp();h_=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"]]),y_=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."]]),jy=e=>y_.get(e)??"Conversation history is unavailable right now."});var jE={};En(jE,{createHistoryShell:()=>v_});var v_,KE=ie(()=>{"use strict";Dy();UE();Ge();Pu();nr();qE();v_=e=>{let o=By(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",d=null,p=null,f=null,m=null,g=0,h=null,b=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,S=()=>e.historyFeatureEnabled()&&!!r&&!s,E=()=>{let B=e.session.getStatus();return e.isStreaming||B==="paused"||B==="resuming"},k=()=>{let B=e.config.features?.history?.scope;if(B)return B;let Q=e.config.getIdentityProof?"verified-user":"browser",fe=r?.capabilities.scopes;return!fe||fe.includes(Q)?Q:fe[0]??Q},D=()=>l?.scope??k(),z=()=>e.session.getClientSession()?.targetId??null,Y=B=>`${B.state}:${"reason"in B?B.reason:""}`,T=B=>{let Q=Y(B);Q!==m&&(m=Q,e.eventBus.emit("history:identityStatusChanged",{status:B,timestamp:Date.now()}))},W=null,L=null,w=()=>{if(!e.historyFeatureEnabled())return null;let B=e.getHistoryProviderFactory();if(B)return B();let Q=e.config.features?.history?.provider;return Q?typeof Q!="function"?Q:(W!==Q&&(W=Q,L=Q()),L):e.session.isClientTokenMode()?zE({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:fe=>e.session.bindActivatedSession(fe),getClient:()=>e.session.getClient()}):null},x=()=>{b?.(),b=null,C?.(),C=null,s=!1,r=w();let B={...e.historyInternals};r?B.historyProvider=r:delete B.historyProvider,e.historyInternals=B,e.session.setHistoryInternals(e.historyInternals),r&&(b=r.subscribeAvailability?.(Q=>{s=!Q,Q||Kn({restoreFocus:!1}),go()})??null,C=r.subscribeIdentityStatus(Q=>T(Q)),m=Y(r.getIdentityStatus()))},P=()=>{let B=e.config.features?.history?.presentation??"panel";if(B==="panel"||B==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let Q=e.artifactSplitRoot??e.container;return(Q.getBoundingClientRect().width||Q.clientWidth)>=720?"rail":"panel"},I=(B,Q)=>{Q?(B.setAttribute("aria-hidden","true"),B.setAttribute("inert","")):(B.removeAttribute("aria-hidden"),B.removeAttribute("inert"))},J="data-persona-history-suppressed",_=null,j=null,te=null,K=null,X=null,oe="",de=()=>e.header===X?oe:e.config.layout?.showHeader===!1?"none":"",xe=()=>e.historyPresentation==="panel"&&!!te&&K===te.element&&e.config.layout?.showHeader!==!1&&de()!=="none",Te=()=>{for(let B of Array.from(e.header.children))B!==_&&B.setAttribute(J,"")},re=()=>{for(let B of Array.from(e.container.querySelectorAll(`[${J}]`)))B.removeAttribute(J)},N=()=>{let B=te;if(!B)return;if(Array.from(e.header.children).some(Le=>Le!==_&&!Le.hasAttribute(J))){j&&j!==e.header&&(j.style.removeProperty("min-height"),j=null);let Le=e.header.offsetHeight;Le>0&&(e.header.style.minHeight=`${Le}px`,j=e.header)}_||(_=v("div","persona-history-header-host")),B.setHeaderPlacement("external");let fe=B.getHeaderElement();fe.parentNode!==_&&_.replaceChildren(fe),_.parentNode!==e.header&&e.header.appendChild(_),Te()},ke=()=>{j&&(j.style.removeProperty("min-height"),j=null),_&&(te?.setHeaderPlacement("inline"),_.remove(),_=null,re())},ve=null,tt=()=>{if(ve){if(e.body.style.display="none",I(e.body,!0),e.footer.hidden=!0,I(e.footer,!0),xe()){N(),e.header.style.display=de(),I(e.header,!1);return}ke(),e.header.style.display="none",I(e.header,!0)}};e.reapplyHistoryHostChrome=tt;let xt=B=>{let Q=e.body.style.display,fe=e.footer.hidden,Le=e.footer,Xe=e.header,dn=e.header.style.display;X=Xe,oe=dn,ve=()=>{ve=null,ke(),X=null,e.body.style.display=Q,I(e.body,!1),Le.hidden=fe,I(Le,!1),e.footer!==Le&&(e.footer.hidden=!1,I(e.footer,!1)),Xe.style.display=dn,I(Xe,!1),e.header!==Xe&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",I(e.header,!1))},e.footer.parentNode?.insertBefore(B,e.footer),tt()},ht=null,lt=null,Ye=null,dt=null,Pe=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Se=52,U=()=>e.config.features?.history?.rail?.collapsible!==!1,R=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",G=200,ne=400,Z=B=>Math.min(ne,Math.max(G,Math.round(B))),le=()=>e.config.features?.history?.rail?.resizable===!0,Me,Ie=()=>{if(Me===void 0&&(Me=null,e.config.persistState!==!1))try{let B=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));B&&(Me=B)}catch{}return Me},_e=()=>Z(Ie()??e.config.features?.history?.rail?.width??260),ct=B=>{if(Me=B,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(B))}catch{}},Tt=()=>U()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",qe=!1,nt=B=>{let Q=v("img");return Q.src=B,Q.alt="",Q.setAttribute("aria-hidden","true"),Q},Ut=()=>{let B=e.config.features?.history?.rail?.brand;if(!B)return;let Q=!1,fe;return Le=>{if(B.render)try{return B.render({collapsed:Le})??null}catch(Xe){return Q||(Q=!0,console.warn("[persona] history rail brand threw",Xe)),null}return fe===void 0&&(B.iconUrl?fe=nt(B.iconUrl):fe=B.icon?e.renderLucideIcon(B.icon,20):null),fe?fe.cloneNode(!0):null}},tn=()=>e.config.features?.history?.rail?.sections?.map(B=>{let Q=!1,fe=Le=>{Q||(Q=!0,console.warn("[persona] history rail section threw",B.id,Le))};return{id:B.id,title:B.title,placement:B.placement??"above-conversations",items:B.items.map(Le=>{let Xe;return{id:Le.id,label:Le.label,badge:Le.badge,iconNode:()=>{if(Xe!==void 0)return Xe;try{Le.renderIcon?Xe=Le.renderIcon()??null:Le.iconUrl?Xe=nt(Le.iconUrl):Xe=Le.icon?e.renderLucideIcon(Le.icon,20):null}catch(dn){fe(dn),Xe=null}return Xe},onSelect:()=>{try{Le.onSelect()}catch(dn){fe(dn)}}}})}})??[],ee=B=>{let Q=tn();for(let fe of B)Q.some(Le=>Le.id===fe.id)?console.warn("[persona] duplicate history rail section id",fe.id):Q.push(fe);return Q.length?Q:void 0},Re=null,Fe=()=>`${e.currentKeyPrefix()}rail-collapsed`,yt=()=>{if(Re===null&&(Re=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let B=window.localStorage.getItem(Fe());B&&(Re=B==="1")}catch{}return Re},bt=B=>{if(Re=B,e.config.persistState!==!1)try{window.localStorage.setItem(Fe(),B?"1":"0")}catch{}},Ee=()=>e.historyPresentation==="rail"&&U()&&!Tt()&&yt(),He=()=>{},je=()=>{if(Tt()){He();return}bt(!yt()),i?.view.setCollapsed(Ee()),e.applyRailChrome(),e.repinAnchoredMessage()},It=()=>{let B=e.config.features?.history?.rail?.collapseShortcut;return!B||!ku(B)?null:{combo:B,hint:Lu(B),aria:dc(B)}},wn=300,nn="var(--persona-history-overlay-margin,8px)",Ot=null,mt=null,Ht=0,St=null,Kt=null,gn=!1,Zn=0,ss=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,jn=()=>S()&&Tt()&&(e.historyPresentation??P())==="rail",qs=()=>e.historyVisible&&!qe,oo=()=>{Kt!==null&&clearTimeout(Kt),Kt=null},Tr=()=>{e.loadHistoryView().catch(()=>{})},At=()=>{oo(),qe&&(Kt=setTimeout(()=>{Kt=null,!(gn||!qe)&&(St?.contains(document.activeElement)||Kn({restoreFocus:!1}))},wn))},ot=(B,Q)=>{let fe=St?.getBoundingClientRect();if(!fe)return!1;let Le=Ot?.getBoundingClientRect(),Xe=Le?Math.min(Le.top,fe.top):fe.top;return B>=fe.left&&B<=fe.right&&Q>=Xe&&Q<=fe.bottom||!!Le&&B>=Le.left&&B<=Le.right&&Q>=Le.top&&Q<=Le.bottom},Ve=B=>{qe&&(gn=ot(B.clientX,B.clientY),gn?oo():Kt===null&&At())},cn=B=>{e.historyVisible||!jn()||(qe=!0,gt({invoker:Ot,keyboard:B?.keyboard===!0}).then(()=>{e.historyVisible?!gn&&document.activeElement!==Ot&&Kn():qe=!1}))},wt=()=>{let B=K?.querySelector('[data-persona-history-focus="collapse"]');B&&(B.setAttribute("aria-label",qe?o.expandLabel:o.collapseLabel),B.setAttribute("aria-expanded",qe?"false":"true"))},Be=()=>{bt(!1);let B=i;if(!qe||!B){gt({invoker:Ot});return}let Q=document.activeElement===Ot;qe=!1,An(),B.element.remove(),Nt(B.element),wt(),Q&&Vt(),e.repinAnchoredMessage(),go()},ye=()=>{bt(!0),Kn()};He=()=>{!e.historyVisible||qe?Be():ye()};let $e=()=>{let B=It(),Q=e.createHeaderIconButton({ariaLabel:o.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":A,...B?{"aria-keyshortcuts":B.aria}:{}}}),fe=Q.button;fe.addEventListener("mouseenter",()=>{gn=!0,oo(),!(ss()||Date.now()<Zn)&&cn()}),fe.addEventListener("mouseleave",()=>{gn=!1,Zn=0,At()}),fe.addEventListener("focus",()=>{e.historyVisible||Tr()}),fe.addEventListener("click",Le=>{S()&&(Le.detail!==0&&ss()&&!e.historyVisible?cn():Be())}),Ot=fe,mt=Q.wrapper},uo=()=>{if(mt&&!mt.isConnected&&(mt=null,Ot=null),!jn()){mt?.remove(),mt=null,Ot=null;return}Ot||$e();let B=mt,Q=Ot;if(!B||!Q)return;let fe=R()!=="right"?e.header.firstChild:null;(fe??e.header.lastChild)!==B&&e.header.insertBefore(B,fe),B.style.display=qs()||Ht>0?"none":"",Q.setAttribute("aria-label",o.expandLabel),Q.setAttribute("aria-expanded",e.historyVisible?"true":"false"),St&&e.applyRailChrome()},fo=B=>{if(!qe)return;let Q=B.target;Q instanceof Node&&(St?.contains(Q)||mt?.contains(Q)||Q instanceof Element&&Q.closest('.persona-dropdown-menu,[role="alertdialog"]')||Kn({restoreFocus:!1}))};document.addEventListener("pointerdown",fo,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",fo,!0),document.removeEventListener("pointermove",Ve),we?.(),oo()});let eo=null,we=null,ze=16,Pn=B=>{ct(Z(B)),e.applyRailChrome(),e.repinAnchoredMessage()},Mt=()=>{let B=v("div","persona-rail-resizer");return B.tabIndex=0,B.setAttribute("role","separator"),B.setAttribute("aria-orientation","vertical"),B.setAttribute("aria-valuemin",String(G)),B.setAttribute("aria-valuemax",String(ne)),B.addEventListener("pointerdown",Q=>{let fe=lt;if(!fe||Q.button!==0)return;Q.preventDefault(),we?.();let Le=Q.clientX,Xe=fe.getBoundingClientRect().width||_e(),dn=R()==="right"?-1:1,on=Xe,rn=e.mount.ownerDocument;fe.style.transition="none";let ut=Oe=>{on=Z(Xe+dn*(Oe.clientX-Le)),fe.style.flex=`0 0 ${on}px`,B.setAttribute("aria-valuenow",String(on))},Rt=()=>{we=null,rn.removeEventListener("pointermove",ut),rn.removeEventListener("pointerup",Rt),rn.removeEventListener("pointercancel",Rt),fe.style.removeProperty("transition");try{B.releasePointerCapture(Q.pointerId)}catch{}Pn(on)};we=Rt,rn.addEventListener("pointermove",ut),rn.addEventListener("pointerup",Rt),rn.addEventListener("pointercancel",Rt);try{B.setPointerCapture(Q.pointerId)}catch{}}),B.addEventListener("keydown",Q=>{let fe=R()==="right"?-ze:ze,Le=_e(),Xe=Q.key==="ArrowRight"?Le+fe:Q.key==="ArrowLeft"?Le-fe:Q.key==="Home"?G:Q.key==="End"?ne:null;Xe!==null&&(Q.preventDefault(),Pn(Xe))}),B},$=(B,Q)=>{if(!le()||Ee()){we?.(),eo?.remove();return}let fe=eo??Mt();eo=fe,fe.setAttribute("aria-label",o.resizeLabel),fe.setAttribute("aria-valuenow",String(_e())),fe.nextElementSibling!==Q&&B.insertBefore(fe,Q)};e.applyRailChrome=()=>{i?.view.setRailSide(R());let B=R()==="right",Q=St;if(Q){let rn=Ot?Ot.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;Q.style.top=`calc(${Math.max(0,Math.round(rn))}px + ${nn})`,Q.style.width=`${_e()}px`,Q.style.left=B?"":nn,Q.style.right=B?nn:""}let fe=lt,Le=ht,Xe=Ye;if(!fe||!Le||!Xe)return;fe.style.flex=`0 0 ${Ee()?Se:_e()}px`;let dn="1px solid var(--persona-divider,#e5e7eb)";fe.style.borderRight=B?"":dn,fe.style.borderLeft=B?dn:"";let on=B?Xe:fe;Le.firstElementChild!==on&&Le.append(on,B?fe:Xe),$(Le,B?fe:Xe)};let me=B=>{if(dt&&lt){dt.replaceWith(B),dt=null,e.applyRailChrome();return}let Q=v("div","persona-history-rail-shell");Q.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let fe=v("div","persona-history-rail-conversation");fe.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let Le=v("div","persona-history-rail-host");Le.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(Q,e.header.parentNode===e.container?e.header:e.body);for(let Xe of Pe())Xe?.parentNode===e.container&&fe.appendChild(Xe);Q.append(Le,fe),Le.appendChild(B),ht=Q,lt=Le,Ye=fe,e.applyRailChrome()},Ne=()=>{if(ht)return;let B=v("div","persona-history-rail-placeholder");B.style.cssText="flex:1 1 auto;min-height:0",dt=B,me(B),e.repinAnchoredMessage()},ft=()=>{dt&&(An(),e.repinAnchoredMessage())},pt=B=>{let Q=v("div","persona-history-rail-overlay");Q.style.cssText=`position:absolute;bottom:${nn};display:flex;overflow:hidden;z-index:${Ta-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))`,e.container.style.position="relative",e.container.appendChild(Q),Q.appendChild(B),document.addEventListener("pointermove",Ve),St=Q,e.applyRailChrome(),wt()},An=()=>{ve?.(),St&&(gn&&(Zn=Date.now()+150),document.removeEventListener("pointermove",Ve),St.remove(),St=null);let B=ht;if(B){we?.();for(let Q of Pe())Q&&B.contains(Q)&&e.container.insertBefore(Q,B);B.remove(),ht=null,lt=null,Ye=null,dt=null}},Ze=B=>{K=B,B.id=A,B.style.flex="1 1 auto",B.style.minHeight="0"},Nt=B=>{Ze(B),(e.historyPresentation!=="rail"||qe)&&ft(),e.historyPresentation!=="rail"?xt(B):qe?pt(B):me(B)},mo=()=>{if(uo(),as(),!e.historyVisible||!i)return;let B=P();if(B===e.historyPresentation)return;let Q=document.activeElement,fe=Q instanceof HTMLElement&&(i.element.contains(Q)||_?.contains(Q)===!0)?Q:null;An(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=B,i.view.setPresentation(B),i.view.setCollapsed(Ee()),i.requestRender(),i.element.isConnected||Nt(i.element),fe?.isConnected?fe.focus():Vt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),go()},ir=(B,Q)=>_?.querySelector(Q)??B.querySelector(Q),Vt=()=>{let B=i?.element??K;if(!B)return;let Q=ir(B,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(Q){Q.focus();return}let fe=ir(B,".persona-history-title")??B;fe.tabIndex=-1,fe.focus()},gt=async B=>{if(!S()||e.historyVisible)return;let Q=r;if(!Q)return;if(!qe&&jn()&&yt()){uo();return}zi();let fe=++g;c=B?.returnSurface??"conversation",d=B?.invoker??p;let Le=jn()&&!qe;Le&&(Ht+=1,uo(),Ne());let Xe;try{Xe=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),Le&&(Ht-=1,fe===g&&(ft(),uo()));return}if(Le&&(Ht-=1),fe!==g||e.historyVisible)return;l={scope:k()},e.historyPresentation=P(),e.historyVisible=!0;let dn=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",on=e.config.features?.history?.rowAvatar,rn=It(),ut=rn?{hint:rn.hint,aria:rn.aria}:null,Rt={provider:Q,context:l,targetId:z(),presentation:e.historyPresentation,collapsible:U(),collapsed:Ee(),railSide:R(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:Ut(),onToggleCollapse:je,...ut?{collapseShortcut:ut}:{},headerPlacement:dn,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:on===!1?!1:typeof on=="string"?on:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize!==void 0?{pageSize:e.config.features.history.pageSize}:{},onSelect:Oe=>Gn(Oe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Oe=>e.setActiveConversationSummary(Oe),attachTooltip:e.attachTooltip,onStartNew:()=>zo({focusComposer:!0}),onClose:()=>Kn(),onRequestDeleteConversation:Oe=>fn(Oe),onRequestClearHistory:()=>Ys(),...Q.resetDevice?{onRequestResetIdentity:()=>nl()}:{}};i=$E({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>Kn(),createView:({slots:Oe,renderDom:ji,onModelChange:ko,railSections:kr})=>(te=Xe.createHistoryView({...Rt,railSections:ee(kr),slots:Oe,renderDom:ji,onModelChange:ko,onAnnounce:e.announceHistory}),te),onElementChanged:(Oe,ji)=>{if(!ji?.isConnected)return Nt(Oe);Ze(Oe),ji.replaceWith(Oe),tt()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),B?.focus!==!1&&(e.historyPresentation!=="rail"||B?.keyboard===!0)&&Vt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),go(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},zi=()=>{},Kn=B=>{if(!e.historyVisible)return;g+=1;let Q=c,fe=d,Le=i,Xe=B?.restoreFocus!==!1;e.historyVisible=!1;let dn=!1,on=null,rn=()=>{if(!dn){if(dn=!0,zi=()=>{},on!==null&&clearTimeout(on),qe=!1,oo(),An(),Le?.dispose(),Le?.view.destroy(),Le?.element.remove(),i===Le&&(i=null,te=null,K=null,e.historyPresentation=null,l=null,d=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),go(),Xe){let Rt=fe??p;Rt?.isConnected?Rt.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:Q,timestamp:Date.now()})}},ut=Le&&Le.element===Le.view.element?Le.view.playExit():null;if(!ut){rn();return}zi=rn,on=setTimeout(rn,250),ut.then(rn)},js=B=>{if(!(B.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let Q=B.target;if(!(Q instanceof Node)||!(i.element.contains(Q)||qe&&mt?.contains(Q)===!0))return}B.preventDefault(),B.stopPropagation(),Kn()}};e.container.addEventListener("keydown",js),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",js));let ro=0,Kc=250,De=null,Dn=()=>{De&&clearTimeout(De),De=null};e.destroyCallbacks.push(Dn);let Zt=()=>{Dn();let B=e.conversationOpenPendingEl;B&&(e.conversationOpenTakeover=!0,B.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},In=()=>{ro+=1,Dn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),I(e.footer,!1),e.updateWelcome())},Gt=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},_n=(B,Q)=>F("div",{className:Jt("persona-conversation-loading-bubble",Q&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:B}}),Gc=()=>F("div",{className:"persona-conversation-loading-body"},_n("58%",!1),_n("72%",!0),_n("44%",!1)),is=B=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=B,B.hidden=!e.conversationOpenTakeover,e.body.insertBefore(B,e.messagesWrapper),Dn(),e.conversationOpenTakeover||(De=setTimeout(Zt,Kc)),I(e.footer,!0)},vf=()=>{let B={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:Gc},Q=null,fe=e.plugins.find(Le=>Le.renderLoadingIndicator);fe?.renderLoadingIndicator&&(Q=fe.renderLoadingIndicator(B)),Q===null&&e.config.loadingIndicator?.render&&(Q=e.config.loadingIndicator.render(B)),is(F("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},Q??Gc()))},Cf=B=>{let Q=()=>{Gn(B,{focusComposer:!0}).catch(()=>{})},fe=S()?()=>{In(),gt()}:void 0,Le=(rn,ut)=>{let Rt=F("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:rn});return Rt.addEventListener("click",ut),Rt},Xe=()=>F("div",{className:"persona-conversation-loading-error-body"},F("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),F("div",{className:"persona-conversation-loading-error-actions"},Le(o.openConversationRetryLabel,Q),fe?Le(o.openConversationBackLabel,fe):null)),dn=Object.freeze({conversationId:B,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:Q,...fe?{back:fe}:{},defaultRenderer:Xe}),on=null;for(let rn of e.plugins)if(rn.renderHistoryOpenError){try{on=rn.renderHistoryOpenError(dn)}catch(ut){console.warn("[persona] renderHistoryOpenError threw",ut),on=null}if(on)break}is(F("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},on??Xe())),Zt()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&I(e.footer,!0)});let Gn=async(B,{focusComposer:Q=!1}={})=>{let fe=D(),Le=!!i;i?.view.setActiveConversationId(B),In();let Xe=ro;vf(),e.historyVisible&&(e.historyPresentation==="panel"||qe)&&Kn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(B,{scope:fe})}catch(dn){throw Xe===ro&&Cf(B),dn}finally{e.suppressScrollSend=!1}Xe===ro&&(In(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Gt(),xn(),Le||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:B,title:e.activeConversationTitle,scope:fe,timestamp:Date.now()}),Q&&e.maybeFocusInput())},zo=async({focusComposer:B=!1}={})=>{In(),await e.session.startNewConversation({scope:D()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),xn();let Q=e.session.getActiveConversationId();i?.view.setActiveConversationId(Q),e.eventBus.emit("history:conversationStarted",{conversationId:Q,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||qe)&&Kn({restoreFocus:!1}),B&&e.maybeFocusInput()},Ks=async(B,Q)=>{let fe=await e.session.updateConversation(B,{...Q,...Q.title!==void 0?{title:Q.title.trim()}:{}});return i?.view.applyConversationSummary(fe),!i&&B===e.session.getActiveConversationId()&&e.setActiveConversationSummary(fe),fe},Yc=async B=>{let Q=D(),fe=e.session.getActiveConversationId()===B;await e.session.deleteConversation(B,{scope:Q}),i?.view.removeConversationSummary(B),fe&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),xn()),e.eventBus.emit("history:conversationDeleted",{conversationId:B,scope:Q,wasActive:fe,timestamp:Date.now()})},el=async B=>{let Q=B?.scope??D(),fe=B?.allTargets?null:B?.targetId??z(),Le=await e.session.clearConversationHistory({...fe?{targetId:fe}:{},scope:Q});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),xn(),e.eventBus.emit("history:cleared",{deleted:Le.deleted,scope:Q,targetId:fe,timestamp:Date.now()}),Le},tl=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let B=!1;try{B=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let Q=e.storageAdapter;Q?.clear&&e.runStorageMutation(()=>Q.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),xn(),Kn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(B?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:B,timestamp:Date.now()}),{remoteRevocationConfirmed:B}},qi=()=>e.artifactSplitRoot?e.panel:e.container,Gs=async B=>{let Q=await e.loadHistoryView().catch(()=>null);return typeof Q?.showHistoryConfirm=="function"?Q.showHistoryConfirm(B):window.confirm(`${B.title}
1162
1162
 
1163
- ${B.description}`)},fn=async B=>await Gs({host:qi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Yc(B),"deleted"):"cancelled",Ys=async()=>{let B=D()==="verified-user";return await Gs({host:qi(),title:o.clearHistoryConfirmTitle,description:B?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await el(),"cleared"):"cancelled"},nl=async()=>{if(!await Gs({host:qi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:Q}=await tl();return{outcome:"reset",remoteRevocationConfirmed:Q}},Mn=v("button","persona-history-earlier");Mn.type="button",Mn.textContent=o.showEarlierMessagesLabel,Mn.setAttribute("data-persona-history-earlier",""),Object.assign(Mn.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 xn=()=>{if(!(S()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Mn.remove();return}Mn.textContent=o.showEarlierMessagesLabel,Mn.parentNode!==e.body&&e.body.insertBefore(Mn,e.body.firstChild)};Mn.addEventListener("click",()=>{let B=e.session.getActiveConversationId(),Q=e.historySessionState.nextMessageCursor;if(!B||!Q||Mn.disabled)return;Mn.disabled=!0;let fe=e.body.scrollHeight,Le=e.body.scrollTop;e.session.loadOlderMessages(B,Q,{scope:D()}).then(()=>{e.body.scrollTop=Le+(e.body.scrollHeight-fe),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Mn.disabled=!1,xn()})});let qo=()=>{let B=e.createHeaderIconButton({ariaLabel:o.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 B.button.addEventListener("click",Q=>{if(!(!S()||E())){if(e.historyVisible){Kn();return}gt({invoker:B.button,keyboard:Q.detail===0})}}),B},as=()=>{if(!S()){f?.remove(),p=null,f=null;return}if(f&&!f.isConnected&&(p=null,f=null),!p&&e.header){let Le=qo();p=Le.button,f=Le.wrapper;let Xe=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Xe?.parentNode&&e.header.contains(Xe)?Xe.parentNode.insertBefore(f,Xe):e.header.appendChild(f)}if(!p||!f)return;let B=jn()||e.historyVisible&&e.historyPresentation==="rail";if(f.style.display=B?"none":"",B){document.activeElement===p&&Vt();return}let Q=E();p.disabled=Q,p.setAttribute("aria-disabled",Q?"true":"false");let fe=Q?o.openHistoryBusyLabel:o.openHistoryLabel;p.setAttribute("aria-label",fe),(e.config.features?.history?.presentation??"panel")==="panel"?(p.removeAttribute("aria-expanded"),p.removeAttribute("aria-controls")):(p.setAttribute("aria-expanded",e.historyVisible?"true":"false"),p.setAttribute("aria-controls",A))},Er=!1,Xs=()=>{let B=e.panelElements.clearChatButton;if(B){if(S()){Er||(h=B.getAttribute("aria-label")??"",Er=!0),B.setAttribute("aria-label",o.newConversationLabel),B.removeAttribute("title");return}Er&&(Er=!1,h&&B.setAttribute("aria-label",h))}},go=()=>{o=By(e.config.features?.history?.copy),as(),uo(),Xs(),xn()};return e.historyChromeSync=go,x(),go(),e.destroyCallbacks.push(()=>{b?.(),C?.(),g+=1,zi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:S,historyScope:k,installHistoryProvider:x,syncHistoryChromeImpl:go,syncHistoryPresentation:mo,syncEarlierMessagesPill:xn,openHistory:gt,closeHistory:Kn,openHistoryConversation:Gn,startNewConversation:zo,updateHistoryConversation:Ks,deleteHistoryConversation:Yc,requestDeleteConversation:fn,clearConversationHistory:el,resetHistoryIdentity:tl,railCollapseShortcut:It,railCollapsible:U,railTriggerApplies:jn,railOverlayMode:Tt,toggleRailCollapsed:je,toggleRailPinned:()=>He(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return ht},get railHost(){return lt},get railColumn(){return Ye}}}});var Z_={};En(Z_,{createThemePreview:()=>g0});module.exports=Xk(Z_);var op=require("lucide");ao();er();Ge();ln();Ge();var Qd=require("lucide");ao();var pL=["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"],uL="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",fL="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",mL=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Jd=(e,t)=>{let n=v("div",["persona-message-bubble",e,...pL].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Zd=e=>{let t=v("button",e.expandable?uL:fL);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},Gm=(e,t,n)=>{e.innerHTML="";let o=Je(t?Qd.ChevronUp:Qd.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},ba=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=v("div","persona-flex persona-items-center");Gm(o,n.expanded,n.iconColor);let r=v("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},ep=e=>{let t=v("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?.();mL(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},tp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Gm(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"},np=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&Gm(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function rp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?zr:wi,...e?.future?.v5Defaults===!0?Ci.features?.[n]:{},...e?.features?.[n]}}}}function Es(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Pl(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 qr(e,t,n,o){if(Es(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,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let d=v("span","persona-activity-icon");d.dataset.activityIcon=c;let p={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},f=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,m=f?We(f,16,"currentColor",2):c==="pending"?Je(op.Circle,16,"currentColor",2):c==="awaiting-approval"?Je(op.Clock,16,"currentColor",2):We(p[c],16,"currentColor",2);m&&d.appendChild(m),r.querySelector(".persona-reasoning-header-icon")?.remove();let g=o==="tool"?"toolCallDisplay":"reasoningDisplay",h=n.features?.[g]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((h==="always"||h==="active"&&c!=="done")&&r.prepend(d),o==="tool"&&s){let S=v("span","persona-activity-duration");i&&s.startedAt&&S.setAttribute("data-tool-elapsed",String(s.startedAt));let E=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);S.textContent=E===void 0?"":Pl(E),r.appendChild(S)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function PC(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,d={}){let p=l==="tool"?i.toolCall:i.reasoning;if(!(!p||n.has(i.id))&&(!t.has(i.id)&&p.status!=="complete"&&p.chunks?.some(Boolean)&&(t.add(i.id),d.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&p.status==="complete"&&!o.has(i.id))){if(o.add(i.id),d.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},d.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function IC(e,t,n,o){let r=v("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=v("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=v("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),ba(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=v("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),qr(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}}Xm();function HC(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 no(e){return e?.type==="runtype"||e?.type==="custom"}var hL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function RC(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:hL()}catch{return!1}}ap();eg();var FC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,VC=e=>e.includes("|"),$C=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())},SL=e=>`| ${e.join(" | ")} |`,AL=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ML=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),UC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
1164
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!VC(r)||FC.test(r)||!FC.test(s))continue;let i=$C(r).length;if(i<1)continue;let l=AL(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let c=o+2;for(;c<t.length;c++){let d=t[c];if(d.trim()===""||!VC(d))break;let p=SL(ML($C(d),i));t[c]!==p&&(t[c]=p,n=!0)}o=c-1}return n?t.join(`
1165
- `):e};var zC="var(--persona-md-table-scroll-fade, 24px)",qC=new WeakSet;function KC(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 jC(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":zC),e.style.setProperty("--persona-fade-r",r<=1?"0px":zC)}function tg(e){qC.has(e)||(qC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&jC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(jC)}Si();Bn();var{setLoader:cO,load:pP,provide:dO,getSync:uP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Lw(),kw))});var ki=pP;var Pw=uP;Ai();Bn();var{setLoader:gO,load:xP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Ww(),Rw))});var Bw=xP;var SP="agent_",AP="flow_";function Dw(e){return e.startsWith(SP)?{kind:"agentId",agentId:e}:e.startsWith(AP)?{kind:"flowId",flowId:e}:null}function _w(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let d=Dw(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=Dw(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Cp(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Ow(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}pg();var MP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),TP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),EP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=MP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:TP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},ug=(e,t)=>{let n=[],o=[],r=[],s="",i,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of e){let d=EP(c);if(d){let f=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(f===void 0||f!==i)&&l(),o.length===0&&(s=c.createdAt,i=f),o.some(m=>m.toolCallId===d.call.toolCallId)||(o.push(d.call),r.push(d.result));continue}let p=t(c);p&&(l(),n.push(p))}return l(),n};Gr();wp();Bn();var{setLoader:MO,load:FP,provide:TO}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Xw(),Yw))});var Xr=FP;Mp();nr();var GP="https://api.runtype.com/v1/dispatch",kn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},ix=e=>"reason"in e?e.reason:void 0,YP="The identity proof was rejected",hg=(e,t)=>e instanceof kn&&e.code===t,yg=e=>e.voiceCaption?!1:!!(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),ax=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),lx=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function XP(e){switch(e){case"json":return sw;case"regex-json":return rw;case"xml":return iw;default:return ow}}var Ul=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#f=null;this.clientSession=null;this.#p=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#i=null;this.#T=!1;this.#b=!1;this.#S=!1;this.#y=null;this.#d=new Set;this.#u=new Set;this.webMcpBridge=null;this.#m=null;this.#_=null;this.#re=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.#e=t.apiUrl??GP,this.#t={"Content-Type":"application/json","X-Persona-Version":br,...t.headers},this.debug=!!t.debug,this.#n=t.streamParser??XP(t.parserType),this.#o=t.contextProviders??[],this.#a=t.requestMiddleware,this.#r=t.customFetch,this.#s=t.parseSSEEvent,this.#g=t.getHeaders,t.webmcp?.enabled===!0&&(this.#m=this.#A(t.webmcp))}#e;#t;#n;#o;#a;#r;#s;#g;#c;#f;#p;#l;#i;#T;#b;#S;#y;#d;#u;#m;#h;#A(t){return Bw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:XC,getToolDisplayTitle:cp,loadPolyfill:JC});return this.#h!==void 0&&o.setConfirmHandler(this.#h),this.webMcpBridge=o,o}).catch(n=>(this.#m=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#w(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#m||(this.#m=this.#A(this.config.webmcp)),this.#m)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#c=t}setWebMcpConfirmHandler(t){this.#h=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#w().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=_w(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#v(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||hp}#I(t){return`${this.#v()}/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 kn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#v()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":br,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let d=await Xr();n=await d.recoverFromUnauthorized(this.#D(),await d.readErrorCode(this.#D(),c),null,!0);continue}if(!c.ok)throw await(await Xr()).historyErrorFor(this.#D(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#p||t&&new Date<t.expiresAt||this.#l===t?null:(this.#l=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.#p)return this.#p;let t=this.#p=this.#$().then(n=>this.#p!==t?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===t&&(this.#p=null)});return t}#L(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#T}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#x(){if(!this.#T){this.#Y({state:"unavailable",reason:"history_disabled"}),this.#T=!0,!this.#b&&typeof console<"u"&&(this.#b=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#u])t(!1)}}getHistoryIdentityStatus(){return this.#y??this.#R()}subscribeHistoryIdentityStatus(t){return this.#d.add(t),()=>{this.#d.delete(t)}}subscribeHistoryAvailability(t){return this.#u.add(t),this.#T&&t(!1),()=>{this.#u.delete(t)}}#R(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#T?{state:"unavailable",reason:"history_disabled"}:this.#J():{state:"unavailable",reason:"ineligible_mode"}}#J(){let t=this.#y;return t?.state==="browser_only"?t:this.#G()}#G(){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"}}#Y(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&ix(n)===ix(t);if(this.#y=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#d])r(t)}}async#E(t){let n=this.#L()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#C(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...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 d=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(c),signal:t.signal});if(!d.ok){let f=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&f.error==="visitor_history_disabled"){if(this.#x(),l)throw new kn("history_disabled","Visitor history is disabled for this surface");return this.#E({...t,omitVisitorFields:!0})}throw d.status===403&&f.error==="durable_recovery_disabled"?new kn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&d.status===401&&f.error==="visitor_required"?new kn("visitor_required","Visitor credential no longer resolves"):l&&d.status===404?new kn("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${f.hint||f.error}`):d.status===403?new Error(`Origin not allowed: ${f.hint||f.error}`):new Error(f.error||"Failed to initialize session")}let p=await d.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{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#$(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#L()&&!n)return this.#W(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#E({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#k(r,t,!1)}catch(r){if(!hg(r,"not_found")&&!hg(r,"visitor_required")&&!hg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(t,!0)}return this.#W(t,!1)}async#W(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#B(t,n)):this.#B(t,n)}async#B(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#E({storedSessionId:o}),s=await this.#ee(r);return this.#k(s,t,n)}async#U(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#E({storedSessionId:n,identityProof:t}),s=this.#k(r,o,!1);return this.clientSession=s,this.#p=null,this.#l=!1,this.resetClientToolsFingerprint(),s}async#ee(t){if(!t.visitor?.token||this.#S||!this.#L()&&t.durableRecovery?.enabled!==!0)return t;this.#S=!0;try{return await this.#E({storedSessionId:t.sessionId})}catch{return t}finally{this.#S=!1}}#k(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}#z(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#l=!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.#L())throw new kn("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 kn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#E({conversationId:t,identityProof:o});return this.#z(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#E({});return this.#z(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#Y(this.#G())}clearClientSession(){this.clientSession=null,this.#p=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#i=null}#q(){return`${this.#v()}/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.#q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.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})}async#j(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 i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}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}}#_;#O(){let t=this;return this.#_??={get config(){return t.config},headers:this.#t,getHeaders:this.#g,debug:this.debug,clientApiBase:()=>t.#v(),getClientApiUrl:n=>t.#I(n),getWebMcpBridge:()=>t.#w(),sendWithClientToolsDiff:(n,o,r,s)=>t.#X(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#re;#D(){let t=this;return this.#re??={HistoryClientError:kn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#v(),setHistoryIdentityStatus:n=>t.#Y(n),browserOnlyStatus:()=>t.#J(),derivedBrowserOnly:()=>t.#G(),reinitWithProof:n=>t.#U(n),isHistoryCapable:()=>t.#L(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Xr()).listConversations(this.#D(),t)}async getConversation(t,n){return(await Xr()).getConversation(this.#D(),t,n)}async finalizeDisplayProjections(t,n){return(await Xr()).finalizeDisplayProjections(this.#D(),t,n)}async deleteConversation(t,n){return(await Xr()).deleteConversation(this.#D(),t,n)}async deleteAllConversations(t){return(await Xr()).deleteAllConversations(this.#D(),t)}async resetVisitor(){return(await Xr()).resetVisitor(this.#D())}async dispatch(t,n){return t.signal?.throwIfAborted(),ki().catch(()=>{}),this.isClientTokenMode()?this.#ce(t,n):this.isAgentMode()?this.#te(t,n):this.#se(t,n)}async#ce(t,n){let o=Ow();this.#f=o;let r=()=>this.#f===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,S=A.durableRecovery?.enabled===!0;if(S&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let E=await this.#E({...S||this.#L()?{conversationId:A.conversationId,durableResume:S}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&E.conversationId!==A.conversationId||S&&E.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#k(E,A.conversationId??null,!1),this.clientSession=l,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let d=await this.#V(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,f=this.#L(),m={sessionId:l.sessionId,messages:t.messages.filter(yg).map(A=>{let S=f?Vl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"},...t.voiceSpoken&&{voice:{spoken:!0}}},g=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#X(l.sessionId,d.clientTools,async S=>{i();let E=await this.#j(t.signal);i();let k={...m,sessionId:l.sessionId,...S,...E&&{identityProof:E}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...k,...E&&{identityProof:{provider:E.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(k),signal:t.signal})})},h=await g();if(i(),h.response.status===401){let A=await h.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),h=await g(),i())}let{response:b,commit:C}=h;if(!b.ok){let A=await b.json().catch(()=>({error:"Chat request failed"}));if(b.status===401&&A.error==="invalid_identity_proof"){let E=new kn("invalid_identity_proof",YP);throw s({type:"error",error:E}),E}if(b.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let E=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:E}),E}if(b.status===429){let E=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:E}),E}if(b.status===410&&A.error==="conversation_deleted"){let E=new kn("conversation_deleted","This conversation was deleted");throw s({type:"error",error:E}),E}let S=new Error(A.error||"Failed to send message");throw s({type:"error",error:S}),S}if(!b.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#ne(b.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof kn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#se(t,n){n({type:"status",status:"connecting"});let o=await this.#V(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#t};if(this.#g)try{let i=await this.#g();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#ne(s.body,n)}finally{n({type:"status",status:"idle"})}}async#te(t,n){n({type:"status",status:"connecting"});let o=await this.#P(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#t};if(this.#g)try{let i=await this.#g();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#ne(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.#ne(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await ki()).resolveApproval(this.#O(),t,n)}async#X(t,n,o,r){let s=!!(n&&n.length>0),i=s?QC(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,d=!s&&r?.emptyMeansReplace===!0&&this.#i===t,p=!1,f;for(let m=0;;m++){if(f=await o({...s&&(p||!c)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),f.status===409&&m===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#i=t:d&&(this.#i=null)}}}async resumeFlow(t,n,o){return(await ki()).resumeFlow(this.#O(),t,n,o)}#de(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#K(t){let n={};this.#o.length&&await Promise.all(this.#o.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.#de(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#N(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}#F(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#P(t,n){let o=this.#C().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=ug(ax(t),d=>yg(d)&&(d.role==="user"||d.role==="assistant"||d.role==="system")&&(!d.variant||d.variant==="assistant")?lx(d):null),s=this.#N(n),i={agent:this.#F(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...Fl(this.config),...await(await this.#w())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#K(t);return c&&(i.context=c),i}async#V(t,n){let o=ug(ax(t),d=>yg(d)?lx(d):null),r=this.#C(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,p]of Object.entries(r.targetPayload))d!=="messages"&&(s[d]=p);let i=[...Fl(this.config),...await(await this.#w())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#K(t);l&&(s.context=l);let c=this.#N(n);if(c&&(s.composerOptions=c),this.#a)try{let d=await this.#a({payload:{...s},config:this.config});if(d&&typeof d=="object"){let p=d;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",d)}return s}async#ne(t,n,o,r){let{streamResponse:s}=Pw()??await ki();return s({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#s,onSSEEvent:(i,l)=>this.#c?.(i,l)},t,n,o,r)}};zl();Bn();var{setLoader:AF,load:kI,provide:MF,getSync:LI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(aS(),iS))});var iu=kI;var qg=LI;Ai();Bn();var{setLoader:LF,load:_I,provide:PF,getSync:OI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(pS(),dS))});var Kg=_I;var uS=OI;Nl();Rs();Hl();Rs();Ig();var NI=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function FI(e){let t=e?.text?.trim()??"";return t?Kl(NI(e),t):""}function fS(e){let t=FI(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[vr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
1163
+ ${B.description}`)},fn=async B=>await Gs({host:qi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Yc(B),"deleted"):"cancelled",Ys=async()=>{let B=D()==="verified-user";return await Gs({host:qi(),title:o.clearHistoryConfirmTitle,description:B?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await el(),"cleared"):"cancelled"},nl=async()=>{if(!await Gs({host:qi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:Q}=await tl();return{outcome:"reset",remoteRevocationConfirmed:Q}},Mn=v("button","persona-history-earlier");Mn.type="button",Mn.textContent=o.showEarlierMessagesLabel,Mn.setAttribute("data-persona-history-earlier",""),Object.assign(Mn.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 xn=()=>{if(!(S()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Mn.remove();return}Mn.textContent=o.showEarlierMessagesLabel,Mn.parentNode!==e.body&&e.body.insertBefore(Mn,e.body.firstChild)};Mn.addEventListener("click",()=>{let B=e.session.getActiveConversationId(),Q=e.historySessionState.nextMessageCursor;if(!B||!Q||Mn.disabled)return;Mn.disabled=!0;let fe=e.body.scrollHeight,Le=e.body.scrollTop;e.session.loadOlderMessages(B,Q,{scope:D()}).then(()=>{e.body.scrollTop=Le+(e.body.scrollHeight-fe),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Mn.disabled=!1,xn()})});let qo=()=>{let B=e.createHeaderIconButton({ariaLabel:o.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 B.button.addEventListener("click",Q=>{if(!(!S()||E())){if(e.historyVisible){Kn();return}gt({invoker:B.button,keyboard:Q.detail===0})}}),B},as=()=>{if(!S()){f?.remove(),p=null,f=null;return}if(f&&!f.isConnected&&(p=null,f=null),!p&&e.header){let Le=qo();p=Le.button,f=Le.wrapper;let Xe=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Xe?.parentNode&&e.header.contains(Xe)?Xe.parentNode.insertBefore(f,Xe):e.header.appendChild(f)}if(!p||!f)return;let B=jn()||e.historyVisible&&e.historyPresentation==="rail";if(f.style.display=B?"none":"",B){document.activeElement===p&&Vt();return}let Q=E();p.disabled=Q,p.setAttribute("aria-disabled",Q?"true":"false");let fe=Q?o.openHistoryBusyLabel:o.openHistoryLabel;p.setAttribute("aria-label",fe),(e.config.features?.history?.presentation??"panel")==="panel"?(p.removeAttribute("aria-expanded"),p.removeAttribute("aria-controls")):(p.setAttribute("aria-expanded",e.historyVisible?"true":"false"),p.setAttribute("aria-controls",A))},Er=!1,Xs=()=>{let B=e.panelElements.clearChatButton;if(B){if(S()){Er||(h=B.getAttribute("aria-label")??"",Er=!0),B.setAttribute("aria-label",o.newConversationLabel),B.removeAttribute("title");return}Er&&(Er=!1,h&&B.setAttribute("aria-label",h))}},go=()=>{o=By(e.config.features?.history?.copy),as(),uo(),Xs(),xn()};return e.historyChromeSync=go,x(),go(),e.destroyCallbacks.push(()=>{b?.(),C?.(),g+=1,zi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:S,historyScope:k,installHistoryProvider:x,syncHistoryChromeImpl:go,syncHistoryPresentation:mo,syncEarlierMessagesPill:xn,openHistory:gt,closeHistory:Kn,openHistoryConversation:Gn,startNewConversation:zo,updateHistoryConversation:Ks,deleteHistoryConversation:Yc,requestDeleteConversation:fn,clearConversationHistory:el,resetHistoryIdentity:tl,railCollapseShortcut:It,railCollapsible:U,railTriggerApplies:jn,railOverlayMode:Tt,toggleRailCollapsed:je,toggleRailPinned:()=>He(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return ht},get railHost(){return lt},get railColumn(){return Ye}}}});var e1={};En(e1,{createThemePreview:()=>h0});module.exports=Qk(e1);var op=require("lucide");ao();er();Ge();ln();Ge();var Qd=require("lucide");ao();var uL=["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"],fL="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",mL="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",gL=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Jd=(e,t)=>{let n=v("div",["persona-message-bubble",e,...uL].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Zd=e=>{let t=v("button",e.expandable?fL:mL);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},Gm=(e,t,n)=>{e.innerHTML="";let o=Je(t?Qd.ChevronUp:Qd.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},ba=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=v("div","persona-flex persona-items-center");Gm(o,n.expanded,n.iconColor);let r=v("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},ep=e=>{let t=v("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?.();gL(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},tp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Gm(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"},np=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&Gm(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function rp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?zr:wi,...e?.future?.v5Defaults===!0?Ci.features?.[n]:{},...e?.features?.[n]}}}}function Es(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Pl(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 qr(e,t,n,o){if(Es(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,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let d=v("span","persona-activity-icon");d.dataset.activityIcon=c;let p={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},f=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,m=f?We(f,16,"currentColor",2):c==="pending"?Je(op.Circle,16,"currentColor",2):c==="awaiting-approval"?Je(op.Clock,16,"currentColor",2):We(p[c],16,"currentColor",2);m&&d.appendChild(m),r.querySelector(".persona-reasoning-header-icon")?.remove();let g=o==="tool"?"toolCallDisplay":"reasoningDisplay",h=n.features?.[g]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((h==="always"||h==="active"&&c!=="done")&&r.prepend(d),o==="tool"&&s){let S=v("span","persona-activity-duration");i&&s.startedAt&&S.setAttribute("data-tool-elapsed",String(s.startedAt));let E=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);S.textContent=E===void 0?"":Pl(E),r.appendChild(S)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function PC(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,d={}){let p=l==="tool"?i.toolCall:i.reasoning;if(!(!p||n.has(i.id))&&(!t.has(i.id)&&p.status!=="complete"&&p.chunks?.some(Boolean)&&(t.add(i.id),d.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&p.status==="complete"&&!o.has(i.id))){if(o.add(i.id),d.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},d.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function IC(e,t,n,o){let r=v("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=v("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=v("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),ba(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=v("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),qr(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}}Xm();function HC(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 no(e){return e?.type==="runtype"||e?.type==="custom"}var yL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function RC(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:yL()}catch{return!1}}ap();eg();var FC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,VC=e=>e.includes("|"),$C=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())},AL=e=>`| ${e.join(" | ")} |`,ML=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,TL=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),UC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
1164
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!VC(r)||FC.test(r)||!FC.test(s))continue;let i=$C(r).length;if(i<1)continue;let l=ML(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let c=o+2;for(;c<t.length;c++){let d=t[c];if(d.trim()===""||!VC(d))break;let p=AL(TL($C(d),i));t[c]!==p&&(t[c]=p,n=!0)}o=c-1}return n?t.join(`
1165
+ `):e};var zC="var(--persona-md-table-scroll-fade, 24px)",qC=new WeakSet;function KC(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 jC(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":zC),e.style.setProperty("--persona-fade-r",r<=1?"0px":zC)}function tg(e){qC.has(e)||(qC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&jC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(jC)}Si();Bn();var{setLoader:dO,load:uP,provide:pO,getSync:fP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Lw(),kw))});var ki=uP;var Pw=fP;Ai();Bn();var{setLoader:hO,load:SP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Bw(),Ww))});var Dw=SP;var AP="agent_",MP="flow_";function _w(e){return e.startsWith(AP)?{kind:"agentId",agentId:e}:e.startsWith(MP)?{kind:"flowId",flowId:e}:null}function Ow(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let d=_w(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=_w(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Cp(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Nw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}pg();var TP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),EP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=TP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:EP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},ug=(e,t)=>{let n=[],o=[],r=[],s="",i,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of e){let d=kP(c);if(d){let f=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(f===void 0||f!==i)&&l(),o.length===0&&(s=c.createdAt,i=f),o.some(m=>m.toolCallId===d.call.toolCallId)||(o.push(d.call),r.push(d.result));continue}let p=t(c);p&&(l(),n.push(p))}return l(),n};Gr();wp();Bn();var{setLoader:TO,load:VP,provide:EO}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Qw(),Xw))});var Xr=VP;Mp();nr();var YP="https://api.runtype.com/v1/dispatch",kn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},ax=e=>"reason"in e?e.reason:void 0,XP="The identity proof was rejected",hg=(e,t)=>e instanceof kn&&e.code===t,yg=e=>e.voiceCaption?!1:!!(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),lx=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),cx=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function QP(e){switch(e){case"json":return sw;case"regex-json":return rw;case"xml":return iw;default:return ow}}var Ul=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#f=null;this.clientSession=null;this.#p=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#i=null;this.#T=!1;this.#b=!1;this.#S=!1;this.#y=null;this.#d=new Set;this.#u=new Set;this.webMcpBridge=null;this.#m=null;this.#_=null;this.#re=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.#e=t.apiUrl??YP,this.#t={"Content-Type":"application/json","X-Persona-Version":br,...t.headers},this.debug=!!t.debug,this.#n=t.streamParser??QP(t.parserType),this.#o=t.contextProviders??[],this.#a=t.requestMiddleware,this.#r=t.customFetch,this.#s=t.parseSSEEvent,this.#g=t.getHeaders,t.webmcp?.enabled===!0&&(this.#m=this.#A(t.webmcp))}#e;#t;#n;#o;#a;#r;#s;#g;#c;#f;#p;#l;#i;#T;#b;#S;#y;#d;#u;#m;#h;#A(t){return Dw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:XC,getToolDisplayTitle:cp,loadPolyfill:JC});return this.#h!==void 0&&o.setConfirmHandler(this.#h),this.webMcpBridge=o,o}).catch(n=>(this.#m=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#w(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#m||(this.#m=this.#A(this.config.webmcp)),this.#m)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#c=t}setWebMcpConfirmHandler(t){this.#h=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#w().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ow(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#v(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||hp}#I(t){return`${this.#v()}/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 kn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#v()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":br,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let d=await Xr();n=await d.recoverFromUnauthorized(this.#D(),await d.readErrorCode(this.#D(),c),null,!0);continue}if(!c.ok)throw await(await Xr()).historyErrorFor(this.#D(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#p||t&&new Date<t.expiresAt||this.#l===t?null:(this.#l=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.#p)return this.#p;let t=this.#p=this.#$().then(n=>this.#p!==t?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===t&&(this.#p=null)});return t}#L(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#T}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#x(){if(!this.#T){this.#Y({state:"unavailable",reason:"history_disabled"}),this.#T=!0,!this.#b&&typeof console<"u"&&(this.#b=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#u])t(!1)}}getHistoryIdentityStatus(){return this.#y??this.#R()}subscribeHistoryIdentityStatus(t){return this.#d.add(t),()=>{this.#d.delete(t)}}subscribeHistoryAvailability(t){return this.#u.add(t),this.#T&&t(!1),()=>{this.#u.delete(t)}}#R(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#T?{state:"unavailable",reason:"history_disabled"}:this.#J():{state:"unavailable",reason:"ineligible_mode"}}#J(){let t=this.#y;return t?.state==="browser_only"?t:this.#G()}#G(){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"}}#Y(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&ax(n)===ax(t);if(this.#y=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#d])r(t)}}async#E(t){let n=this.#L()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#C(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...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 d=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(c),signal:t.signal});if(!d.ok){let f=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&f.error==="visitor_history_disabled"){if(this.#x(),l)throw new kn("history_disabled","Visitor history is disabled for this surface");return this.#E({...t,omitVisitorFields:!0})}throw d.status===403&&f.error==="durable_recovery_disabled"?new kn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&d.status===401&&f.error==="visitor_required"?new kn("visitor_required","Visitor credential no longer resolves"):l&&d.status===404?new kn("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${f.hint||f.error}`):d.status===403?new Error(`Origin not allowed: ${f.hint||f.error}`):new Error(f.error||"Failed to initialize session")}let p=await d.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{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#$(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#L()&&!n)return this.#W(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#E({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#k(r,t,!1)}catch(r){if(!hg(r,"not_found")&&!hg(r,"visitor_required")&&!hg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(t,!0)}return this.#W(t,!1)}async#W(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#B(t,n)):this.#B(t,n)}async#B(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#E({storedSessionId:o}),s=await this.#ee(r);return this.#k(s,t,n)}async#U(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#E({storedSessionId:n,identityProof:t}),s=this.#k(r,o,!1);return this.clientSession=s,this.#p=null,this.#l=!1,this.resetClientToolsFingerprint(),s}async#ee(t){if(!t.visitor?.token||this.#S||!this.#L()&&t.durableRecovery?.enabled!==!0)return t;this.#S=!0;try{return await this.#E({storedSessionId:t.sessionId})}catch{return t}finally{this.#S=!1}}#k(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}#z(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#l=!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.#L())throw new kn("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 kn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#E({conversationId:t,identityProof:o});return this.#z(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#E({});return this.#z(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#Y(this.#G())}clearClientSession(){this.clientSession=null,this.#p=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#i=null}#q(){return`${this.#v()}/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.#q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.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})}async#j(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 i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}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}}#_;#O(){let t=this;return this.#_??={get config(){return t.config},headers:this.#t,getHeaders:this.#g,debug:this.debug,clientApiBase:()=>t.#v(),getClientApiUrl:n=>t.#I(n),getWebMcpBridge:()=>t.#w(),sendWithClientToolsDiff:(n,o,r,s)=>t.#X(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#re;#D(){let t=this;return this.#re??={HistoryClientError:kn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#v(),setHistoryIdentityStatus:n=>t.#Y(n),browserOnlyStatus:()=>t.#J(),derivedBrowserOnly:()=>t.#G(),reinitWithProof:n=>t.#U(n),isHistoryCapable:()=>t.#L(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Xr()).listConversations(this.#D(),t)}async getConversation(t,n){return(await Xr()).getConversation(this.#D(),t,n)}async finalizeDisplayProjections(t,n){return(await Xr()).finalizeDisplayProjections(this.#D(),t,n)}async deleteConversation(t,n){return(await Xr()).deleteConversation(this.#D(),t,n)}async deleteAllConversations(t){return(await Xr()).deleteAllConversations(this.#D(),t)}async resetVisitor(){return(await Xr()).resetVisitor(this.#D())}async dispatch(t,n){return t.signal?.throwIfAborted(),ki().catch(()=>{}),this.isClientTokenMode()?this.#ce(t,n):this.isAgentMode()?this.#te(t,n):this.#se(t,n)}async#ce(t,n){let o=Nw();this.#f=o;let r=()=>this.#f===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,S=A.durableRecovery?.enabled===!0;if(S&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let E=await this.#E({...S||this.#L()?{conversationId:A.conversationId,durableResume:S}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&E.conversationId!==A.conversationId||S&&E.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#k(E,A.conversationId??null,!1),this.clientSession=l,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let d=await this.#V(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,f=this.#L(),m={sessionId:l.sessionId,messages:t.messages.filter(yg).map(A=>{let S=f?Vl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"},...t.voiceSpoken&&{voice:{spoken:!0}}},g=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#X(l.sessionId,d.clientTools,async S=>{i();let E=await this.#j(t.signal);i();let k={...m,sessionId:l.sessionId,...S,...E&&{identityProof:E}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...k,...E&&{identityProof:{provider:E.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(k),signal:t.signal})})},h=await g();if(i(),h.response.status===401){let A=await h.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),h=await g(),i())}let{response:b,commit:C}=h;if(!b.ok){let A=await b.json().catch(()=>({error:"Chat request failed"}));if(b.status===401&&A.error==="invalid_identity_proof"){let E=new kn("invalid_identity_proof",XP);throw s({type:"error",error:E}),E}if(b.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let E=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:E}),E}if(b.status===429){let E=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:E}),E}if(b.status===410&&A.error==="conversation_deleted"){let E=new kn("conversation_deleted","This conversation was deleted");throw s({type:"error",error:E}),E}let S=new Error(A.error||"Failed to send message");throw s({type:"error",error:S}),S}if(!b.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#ne(b.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof kn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#se(t,n){n({type:"status",status:"connecting"});let o=await this.#V(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#t};if(this.#g)try{let i=await this.#g();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#ne(s.body,n)}finally{n({type:"status",status:"idle"})}}async#te(t,n){n({type:"status",status:"connecting"});let o=await this.#P(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#t};if(this.#g)try{let i=await this.#g();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#ne(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.#ne(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await ki()).resolveApproval(this.#O(),t,n)}async#X(t,n,o,r){let s=!!(n&&n.length>0),i=s?QC(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,d=!s&&r?.emptyMeansReplace===!0&&this.#i===t,p=!1,f;for(let m=0;;m++){if(f=await o({...s&&(p||!c)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),f.status===409&&m===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#i=t:d&&(this.#i=null)}}}async resumeFlow(t,n,o){return(await ki()).resumeFlow(this.#O(),t,n,o)}#de(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#K(t){let n={};this.#o.length&&await Promise.all(this.#o.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.#de(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#N(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}#F(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#P(t,n){let o=this.#C().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=ug(lx(t),d=>yg(d)&&(d.role==="user"||d.role==="assistant"||d.role==="system")&&(!d.variant||d.variant==="assistant")?cx(d):null),s=this.#N(n),i={agent:this.#F(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...Fl(this.config),...await(await this.#w())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#K(t);return c&&(i.context=c),i}async#V(t,n){let o=ug(lx(t),d=>yg(d)?cx(d):null),r=this.#C(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,p]of Object.entries(r.targetPayload))d!=="messages"&&(s[d]=p);let i=[...Fl(this.config),...await(await this.#w())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#K(t);l&&(s.context=l);let c=this.#N(n);if(c&&(s.composerOptions=c),this.#a)try{let d=await this.#a({payload:{...s},config:this.config});if(d&&typeof d=="object"){let p=d;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",d)}return s}async#ne(t,n,o,r){let{streamResponse:s}=Pw()??await ki();return s({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#s,onSSEEvent:(i,l)=>this.#c?.(i,l)},t,n,o,r)}};zl();Bn();var{setLoader:MF,load:LI,provide:TF,getSync:PI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(lS(),aS))});var iu=LI;var qg=PI;Ai();Bn();var{setLoader:PF,load:OI,provide:IF,getSync:NI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(uS(),pS))});var Kg=OI;var fS=NI;Nl();Rs();Hl();Rs();Ig();var FI=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function VI(e){let t=e?.text?.trim()??"";return t?Kl(FI(e),t):""}function mS(e){let t=VI(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[vr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
1166
1166
 
1167
- `)}:{}}function lu(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function mS(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 Gg(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 gS(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 Gg(e,n.id)?n.id:null}return null}function Yg(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}zl();Mp();function Xg(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 ec=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 i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xg(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.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 cu=class{#e=null;#t=null;#n="idle";#o=new Set;#a=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#t===t?this.#n:"idle"}activeMessageId(){return this.#t}onChange(t){return this.#o.add(t),()=>this.#o.delete(t)}toggle(t,n){if(this.#t===t){if(this.#n==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#s(t,"paused")):this.stop();return}if(this.#n==="paused"){this.#e?.resume(),this.#s(t,"playing");return}if(this.#n==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#a;this.#e?.stop(),this.#s(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#a)return;if(!r){this.#s(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#a&&this.#s(t,"playing")},onEnd:()=>{o===this.#a&&this.#s(null,"idle")},onError:()=>{o===this.#a&&this.#s(null,"idle")}})}catch{o===this.#a&&this.#s(null,"idle")}}stop(){this.#a++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(t,n){this.#t=n==="idle"?null:t,this.#n=n;for(let o of this.#o)o(this.#t,this.#n)}};var tc=class{#e;#t=!1;start(t){this.#e=t,this.#t=!1}cancel(){this.#t=!0}accepts(t){return!this.#t&&(!t||!this.#e||t===this.#e)}};Bn();var{setLoader:a2,load:AH,getSync:MH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(_S(),DS))});var oc=AH,OS=MH;function sh(e){if(!e)return"";let t=TH(e);return NS(t!==null?t:e)}function TH(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 NS(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
1167
+ `)}:{}}function lu(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function gS(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 Gg(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 hS(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 Gg(e,n.id)?n.id:null}return null}function Yg(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}zl();Mp();function Xg(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 ec=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 i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xg(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.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 cu=class{#e=null;#t=null;#n="idle";#o=new Set;#a=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#t===t?this.#n:"idle"}activeMessageId(){return this.#t}onChange(t){return this.#o.add(t),()=>this.#o.delete(t)}toggle(t,n){if(this.#t===t){if(this.#n==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#s(t,"paused")):this.stop();return}if(this.#n==="paused"){this.#e?.resume(),this.#s(t,"playing");return}if(this.#n==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#a;this.#e?.stop(),this.#s(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#a)return;if(!r){this.#s(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#a&&this.#s(t,"playing")},onEnd:()=>{o===this.#a&&this.#s(null,"idle")},onError:()=>{o===this.#a&&this.#s(null,"idle")}})}catch{o===this.#a&&this.#s(null,"idle")}}stop(){this.#a++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(t,n){this.#t=n==="idle"?null:t,this.#n=n;for(let o of this.#o)o(this.#t,this.#n)}};var tc=class{#e;#t=!1;start(t){this.#e=t,this.#t=!1}cancel(){this.#t=!0}accepts(t){return!this.#t&&(!t||!this.#e||t===this.#e)}};Bn();var{setLoader:l2,load:MH,getSync:TH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(OS(),_S))});var oc=MH,NS=TH;function sh(e){if(!e)return"";let t=EH(e);return FS(t!==null?t:e)}function EH(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 FS(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
1168
1168
  `),t=t.replace(/\n{2,}/g,`
1169
- `),t.trim()}var zS=null;var ih=()=>zS?zS():Promise.resolve().then(()=>(US(),$S));Bn();var{setLoader:y2,load:IH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(jS(),qS))});var KS=IH;var HH=["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 RH(e,t){return HH.some(n=>e[n]!==t[n])}var Cr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function ah(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}
1169
+ `),t.trim()}var qS=null;var ih=()=>qS?qS():Promise.resolve().then(()=>(zS(),US));Bn();var{setLoader:b2,load:HH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(KS(),jS))});var GS=HH;var RH=["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 WH(e,t){return RH.some(n=>e[n]!==t[n])}var Cr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function ah(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}
1170
1170
 
1171
- _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#n=Date.now();this.clientSession=null;this.agentExecution=null;this.#o=null;this.#a=null;this.#r=!1;this.#s=null;this.#g=null;this.#c=null;this.artifacts=new Map;this.#f=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#l=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#i=null;this.#T=null;this.#b=0;this.#S=0;this.#y=!1;this.#d="disconnected";this.#u=null;this.#m=null;this.#h=null;this.#A=0;this.#w=!1;this.#C=null;this.#v=!1;this.#I=null;this.#L=new Map;this.#x=null;this.#R=new Map;this.#J=null;this.#G=null;this.#Y=!1;this.#E=null;this.#$=null;this.#W=!1;this.#B=null;this.#k=null;this.#z=null;this.#q=new tc;this.#j=Promise.resolve();this.#_=null;this.#O=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new cu(()=>this.#re());this.#Ze=null;this.#me=0;this.handleEvent=t=>{let n=this.#O,o=!1;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id),o=!0)),t.type==="message"){this.upsertMessage(t.message),o&&n.onUpdate?.(),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#t),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#a=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Kg().catch(()=>{});let r=t.message.toolCall,s=!!r?.name&&(Ca(r.name)||r.name===Yr&&Hs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#et(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.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#We();return}if(this.#Z(t.status),t.status==="connecting")this.#H(!0);else if(t.status==="idle"||t.status==="error"){this.#Ue()||this.#Pe(),this.webMcpResolveControllers.size===0&&(this.#H(!1),this.abortController=null,this.#Ke(),this.#qe());let r=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":r||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#Z("error"),this.#Pe(),this.webMcpResolveControllers.size===0&&(this.#H(!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.#rt(t)};this.historyInternals=this.#de(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#Q()})),this.messages=this.#ge(this.messages),this.client=new Ul(t,this.historyInternals),this.#Ae(),this.#Ve();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#f=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#be(),this.callbacks.onStatusChanged(this.status),this.#ee(),this.#U()}#e;#t;#n;#o;#a;#r;#s;#g;#c;#f;#p;#l;#i;#T;#b;#S;#y;#d;#u;#m;#h;#A;#w;#C;#v;#I;#L;#x;#R;#J;#G;#Y;#E;#$;#W;#B;#U(){this.config.voiceRecognition?.provider&&oc().catch(()=>{})}#ee(){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||ih().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 RC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#y}getVoiceStatus(){return this.#d}getVoiceNotice(){return this.#i?.takeNotice?.()??null}getVoiceDisclosure(){return this.#i?.getDisclosure?.()??null}getVoiceLevel(){return this.#i?.onLevel?this.#S:null}getVoiceInterruptionMode(){return this.#i?.getInterruptionMode?this.#i.getInterruptionMode():"none"}stopVoicePlayback(){this.#i?.stopPlayback&&(this.#q.cancel(),this.#_?.cancel(),this.#i.stopPlayback())}isBargeInActive(){return this.#i?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#i?.deactivateBargeIn&&await this.#i.deactivateBargeIn()}#k;#z;#q;#j;#_;#O;#re(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ec.isSupported()?new ec({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,i=t.browserFallback!==!1;if(o&&r&&s)return ih().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(d,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):d});if(i&&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.#j,r=++this.#b;this.#T=oc().then(async s=>{await o,r===this.#b&&this.#D(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#b&&(this.#T=null)})}catch(n){console.error("Failed to setup voice:",n)}}#D(t,n){this.#i=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#i,generation:()=>o.#b,get keyed(){return o.#_},set keyed(r){o.#_=r},get pendingUser(){return o.#k},set pendingUser(r){o.#k=r},get pendingAssistant(){return o.#z},set pendingAssistant(r){o.#z=r},turns:()=>o.#q,busy:()=>o.#ce(),setStreaming:r=>o.#H(r),setDelegation:r=>{o.#O=r},setLevel:r=>{o.#S=r},setStatus:r=>{o.#d=r,o.#y=r==="listening"},settlePending:r=>o.#te(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#i&&this.#T&&await this.#T,!this.#i){console.error("Voice not configured");return}if(this.#y)await this.#i.stopListening();else{this.stopSpeaking();try{await this.#i.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!no(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#b,n=()=>{let o=this.#i;!o?.prewarm||t!==this.#b||this.#y||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#i&&this.#T){this.#T.then(n,()=>{});return}n()}#ce(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#i!==null;if(this.#b++,this.#T=null,this.#i){let n=this.#i;this.#i=null,this.#j=this.#se(n)}this.#y=!1,this.#d="disconnected",this.#te(!0),this.#_?.settle(),this.#_=null,this.#q=new tc,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#se(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#te(t){let n=t?this.#k:null,o=this.#z;!n&&!o||(o&&this.#q.cancel(),t&&(this.#k=null),this.#z=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.#H(!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,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};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.#G=this.historyInternals.getStoredConversationRevision?.()??null,this.#Y=!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.#X(t,n)}#X(t,n=!this.messages.length){if(this.#w||!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.#Q()};this.#le(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.#de(t),this.client.setHistoryInternals(this.historyInternals),this.#Ae()}destroy(){this.cleanupVoice(),this.#E?.(),this.#E=null,this.#$=null}#de(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Ie(o),n?.(o)}}}get#K(){return this.historyInternals.historyProvider??null}#N(){let t=this.#K;if(!t)throw new Cr("history_unavailable","No conversation history provider is installed");return t}#F(t){let n=this.#N(),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 Li("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#u,conversationRevision:this.#m,nextMessageCursor:this.#h,recovery:this.#C,sendBlocked:this.#v}}getActiveConversationId(){return this.#u}#P(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#V(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#I;t&&await t.catch(()=>{});let n=this.#x;n&&await n.catch(()=>{})}#ne(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Cr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#N().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#F(t?.scope)})}async openConversation(t,n){let o=this.#N();this.#ne();let r=this.#F(n?.scope);await this.awaitHistorySettled();let s=++this.#A,i=await o.getPage(t,{context:r});if(s!==this.#A)throw new Cr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#A)throw l.discard(),new Cr("superseded","A later selection won");this.#w=!0;try{await this.#Ee(l)}finally{this.#w=!1}this.#u=l.conversationId||t,this.#m=l.conversationRevision||i.conversationRevision||null,this.#h=i.nextCursor,this.#C=null,this.#v=!1,this.#he();for(let c of i.messages)this.#R.set(c.id,c.content);return this.#Se(),this.hydrateMessages(i.messages),this.#P(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#N(),s=this.#F(o?.scope),i=n??this.#h;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#L.get(l);if(c)return c;let d=this.#Ce(r,t,i,s).finally(()=>{this.#L.delete(l)});return this.#L.set(l,d),d}async#Ce(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#u&&this.#u!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=$l(this.messages,i.messages);this.messages=this.#ge(l.map(c=>this.#Me(c))),this.#h=i.nextCursor;for(let c of i.messages)this.#R.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#P(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#N(),o=this.#F(t?.scope);await this.awaitHistorySettled();let r=++this.#A,s=await n.prepareStartNew({context:o});if(r!==this.#A)throw s.discard(),new Cr("superseded","A later action won");await this.#ie(s)}async#ie(t){this.#oe(),await this.#Ee(t),this.#u=t.conversationId||null,this.#m=t.conversationRevision||null,this.#h=null,this.#C=null,this.#v=!1,this.#Se(),this.#P()}async deleteConversation(t,n){let o=this.#N(),r=this.#F(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#u&&await this.#we(r)}async updateConversation(t,n,o){let r=this.#N();if(!r.update)throw new Cr("history_unavailable","This history provider cannot update conversations");let s=this.#F(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#K?.update=="function"}async clearConversationHistory(t){let n=this.#N(),o=this.#F(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#we(o),r}async resetHistoryDevice(){let t=this.#N();if(!t.resetDevice)throw new Cr("history_unavailable","This history provider cannot reset the device");this.#A+=1,this.#x=null;try{return await t.resetDevice()}finally{this.#oe(),this.#u=null,this.#m=null,this.#h=null,this.#C=null,this.#v=!1,this.#P()}}async#we(t){this.#A+=1,this.#x=null,this.#oe(),this.#u=null,this.#m=null,this.#h=null,this.#v=!0,this.#C=null,this.#P(),await this.#xe(t)}async#xe(t){let n=this.#K;if(!n){this.#v=!1,this.#P();return}try{let o=await n.prepareStartNew({context:t});await this.#ie(o)}catch{this.#v=!0,this.#C="new_conversation_required",this.#P(),this.#V("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Te(){if(!(this.#C!=="new_conversation_required"||!this.#K)&&(this.#C=null,await this.#xe(this.#F()),this.#C==="new_conversation_required"))throw new Cr("new_conversation_required","A new conversation is required before sending")}async#Ee(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.#u=t.conversationId,this.#m=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#w||this.#X(t)}#Se(){this.#u?this.config.setStoredConversationId?.(this.#u):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#m),this.historyInternals.setStoredMessageCursor?.(this.#h)}#he(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#R.clear(),this.#pe(null)}#oe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.messages=[],this.#he(),this.#L.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#H(!1),this.#Z("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Ie(t){this.#A+=1,this.#x=null,this.#v=!0,this.#oe(),this.#u=t.conversationId,this.#m=null,this.#h=null,this.#C=null,this.#P(),this.#V("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#I=Promise.resolve().then(()=>{this.#v=!1,this.#I=null,this.#P()})}#Ae(){let t=this.historyInternals.visitorStore??null;t!==this.#$&&(this.#E?.(),this.#E=null,this.#$=t,t&&(this.#E=t.subscribe(n=>this.#ke(n))))}#ke(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#A+=1,this.#x=null,this.#W=!0,this.#B=null;let n=this.messages.length>0;n||this.#u!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#oe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#L.clear(),this.#pe(null)),this.#u=null,this.#m=null,this.#h=null,this.#C=null,this.#P(),n&&this.#V("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#ae(){return this.#W?(this.#B||(this.#B=this.#M().finally(()=>{this.#B=null})),this.#B):Promise.resolve()}async#M(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(t){let n=this.#K,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#u;if(!n||!o)return Promise.resolve();let r=this.#F(t?.scope);this.#v=!0,this.#P();let s=this.#ue(n,o,r).finally(()=>{this.#v=this.#C!==null,this.#I===s&&(this.#I=null),this.#P()});return this.#I=s,s}async#ue(t,n,o){this.#u=n;let r=this.clientSession?.conversationRevision??this.#m??null,s=this.#Y?this.#G:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#Y=!1,this.#h=this.historyInternals.getStoredMessageCursor?.()??this.#h,await this.replayPendingProjections(),r&&s&&r===s){this.#m=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(f=>f.id)),c=this.messages.some(f=>l.has(f.id)),d=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(f=>this.#Me(f));else{let f=this.#o?this.#a:null,m=this.messages.filter(g=>l.has(g.id)||g.id===f?!0:d!==void 0&&g.createdAt<d);p=$l(m,i.messages).map(g=>this.#Me(g))}this.#h=i.nextCursor,this.#m=i.conversationRevision||r||null,this.#R.clear();for(let f of i.messages)this.#R.set(f.id,f.content);this.#Se(),this.messages=this.#ge(p),this.callbacks.onMessagesChanged([...this.messages])}#fe(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#pe(t){this.#J=t,this.historyInternals.setPendingDisplayProjections?.(t)}#De(){return this.historyInternals.getPendingDisplayProjections?.()??this.#J}#_e(t){if(this.#fe())for(let n of t){let o=Vl(n);o!==void 0&&this.#R.set(n.id,o)}}#qe(){if(!this.#fe())return;let t=this.#u;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Vl(o);r!==void 0&&this.#R.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#pe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Oe(t,n))}#Oe(t,n){let r=(this.#x??Promise.resolve()).catch(()=>{}).then(()=>this.#Ne(t,n,!1)).finally(()=>{this.#x===r&&(this.#x=null)});this.#x=r}async#Ne(t,n,o){if(this.#u!==t)return;let r=n.filter(s=>this.#R.get(s.id)!==s.displayContent);if(r.length===0){this.#He(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#R.set(i.id,i.displayContent);this.#u===t&&s&&(this.#m=s),this.#He(t,n)}catch(s){if(!o&&this.#je(s)){await this.#Ne(t,r,!0);return}if(s instanceof kn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#He(t,n);return}this.#V("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#je(t){return t instanceof kn?t.code==="request_failed":t instanceof Error}#He(t,n){let o=this.#De();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#pe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#fe())return;let t=this.#De();if(!t)return;if(this.#u&&t.conversationId!==this.#u){this.#pe(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.#pe(null);return}this.#Oe(t.conversationId,n),await this.#x?.catch(()=>{})}#Ke(){this.#u&&(this.#m=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Fe(){await this.awaitHistorySettled(),await this.#ae(),this.#C==="new_conversation_required"&&await this.#Te()}static#Ge(t){return t instanceof kn&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#_e(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt,voiceSpoken:s?.voiceSpoken},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#_e([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,voiceSpoken:s?.voiceSpoken},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#A+=1,this.#x=null,this.#oe(),this.#u=null,this.#m=null,this.#h=null,this.#w=!0;try{let r=this.#K;if(r){let s=await r.prepareStartNew({context:this.#F()});await this.#ie(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#v=!0,this.#C="new_conversation_required",this.#P(),this.#V("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#w=!1}return this.#le(o),this.#H(!0),this.#V("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=HC(this.config,o),s=RH(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#$e();return}this.#ye(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ul(this.config,this.historyInternals),i&&this.#$e(),this.#Ve(),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:i,createdAt:l,sequence:c,streaming:d=!1,voiceProcessing:p,voiceCaption:f,rawContent:m}=t,h={id:i??(n==="user"?Cp():n==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#Q(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...f&&{voiceCaption:f},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:d,sequence:p,streaming:f=!1,voiceProcessing:m,rawContent:g}=o,b={id:c??(r==="user"?Cp():r==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:p??this.#Q(),streaming:f,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...m!==void 0&&{voiceProcessing:m},...g!==void 0&&{rawContent:g}};n.push(b)}return this.messages=this.#ge([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1171
+ _Details: ${n.message}_`:o}var YS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#n=Date.now();this.clientSession=null;this.agentExecution=null;this.#o=null;this.#a=null;this.#r=!1;this.#s=null;this.#g=null;this.#c=null;this.artifacts=new Map;this.#f=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#l=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#i=null;this.#T=null;this.#b=0;this.#S=0;this.#y=!1;this.#d="disconnected";this.#u=null;this.#m=null;this.#h=null;this.#A=0;this.#w=!1;this.#C=null;this.#v=!1;this.#I=null;this.#L=new Map;this.#x=null;this.#R=new Map;this.#J=null;this.#G=null;this.#Y=!1;this.#E=null;this.#$=null;this.#W=!1;this.#B=null;this.#k=null;this.#z=null;this.#q=new tc;this.#j=Promise.resolve();this.#_=null;this.#O=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new cu(()=>this.#re());this.#Ze=null;this.#me=0;this.handleEvent=t=>{let n=this.#O,o=!1;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id),o=!0)),t.type==="message"){this.upsertMessage(t.message),o&&n.onUpdate?.(),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#t),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#a=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Kg().catch(()=>{});let r=t.message.toolCall,s=!!r?.name&&(Ca(r.name)||r.name===Yr&&Hs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#et(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.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#We();return}if(this.#Z(t.status),t.status==="connecting")this.#H(!0);else if(t.status==="idle"||t.status==="error"){this.#Ue()||this.#Pe(),this.webMcpResolveControllers.size===0&&(this.#H(!1),this.abortController=null,this.#Ke(),this.#qe());let r=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":r||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#Z("error"),this.#Pe(),this.webMcpResolveControllers.size===0&&(this.#H(!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.#rt(t)};this.historyInternals=this.#de(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#Q()})),this.messages=this.#ge(this.messages),this.client=new Ul(t,this.historyInternals),this.#Ae(),this.#Ve();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#f=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#be(),this.callbacks.onStatusChanged(this.status),this.#ee(),this.#U()}#e;#t;#n;#o;#a;#r;#s;#g;#c;#f;#p;#l;#i;#T;#b;#S;#y;#d;#u;#m;#h;#A;#w;#C;#v;#I;#L;#x;#R;#J;#G;#Y;#E;#$;#W;#B;#U(){this.config.voiceRecognition?.provider&&oc().catch(()=>{})}#ee(){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||ih().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 RC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#y}getVoiceStatus(){return this.#d}getVoiceNotice(){return this.#i?.takeNotice?.()??null}getVoiceDisclosure(){return this.#i?.getDisclosure?.()??null}getVoiceLevel(){return this.#i?.onLevel?this.#S:null}getVoiceInterruptionMode(){return this.#i?.getInterruptionMode?this.#i.getInterruptionMode():"none"}stopVoicePlayback(){this.#i?.stopPlayback&&(this.#q.cancel(),this.#_?.cancel(),this.#i.stopPlayback())}isBargeInActive(){return this.#i?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#i?.deactivateBargeIn&&await this.#i.deactivateBargeIn()}#k;#z;#q;#j;#_;#O;#re(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ec.isSupported()?new ec({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,i=t.browserFallback!==!1;if(o&&r&&s)return ih().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(d,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):d});if(i&&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.#j,r=++this.#b;this.#T=oc().then(async s=>{await o,r===this.#b&&this.#D(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#b&&(this.#T=null)})}catch(n){console.error("Failed to setup voice:",n)}}#D(t,n){this.#i=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#i,generation:()=>o.#b,get keyed(){return o.#_},set keyed(r){o.#_=r},get pendingUser(){return o.#k},set pendingUser(r){o.#k=r},get pendingAssistant(){return o.#z},set pendingAssistant(r){o.#z=r},turns:()=>o.#q,busy:()=>o.#ce(),setStreaming:r=>o.#H(r),setDelegation:r=>{o.#O=r},setLevel:r=>{o.#S=r},setStatus:r=>{o.#d=r,o.#y=r==="listening"},settlePending:r=>o.#te(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#i&&this.#T&&await this.#T,!this.#i){console.error("Voice not configured");return}if(this.#y)await this.#i.stopListening();else{this.stopSpeaking();try{await this.#i.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!no(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#b,n=()=>{let o=this.#i;!o?.prewarm||t!==this.#b||this.#y||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#i&&this.#T){this.#T.then(n,()=>{});return}n()}#ce(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#i!==null;if(this.#b++,this.#T=null,this.#i){let n=this.#i;this.#i=null,this.#j=this.#se(n)}this.#y=!1,this.#d="disconnected",this.#te(!0),this.#_?.settle(),this.#_=null,this.#q=new tc,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#se(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#te(t){let n=t?this.#k:null,o=this.#z;!n&&!o||(o&&this.#q.cancel(),t&&(this.#k=null),this.#z=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.#H(!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,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};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.#G=this.historyInternals.getStoredConversationRevision?.()??null,this.#Y=!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.#X(t,n)}#X(t,n=!this.messages.length){if(this.#w||!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.#Q()};this.#le(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.#de(t),this.client.setHistoryInternals(this.historyInternals),this.#Ae()}destroy(){this.cleanupVoice(),this.#E?.(),this.#E=null,this.#$=null}#de(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Ie(o),n?.(o)}}}get#K(){return this.historyInternals.historyProvider??null}#N(){let t=this.#K;if(!t)throw new Cr("history_unavailable","No conversation history provider is installed");return t}#F(t){let n=this.#N(),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 Li("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#u,conversationRevision:this.#m,nextMessageCursor:this.#h,recovery:this.#C,sendBlocked:this.#v}}getActiveConversationId(){return this.#u}#P(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#V(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#I;t&&await t.catch(()=>{});let n=this.#x;n&&await n.catch(()=>{})}#ne(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Cr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#N().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#F(t?.scope)})}async openConversation(t,n){let o=this.#N();this.#ne();let r=this.#F(n?.scope);await this.awaitHistorySettled();let s=++this.#A,i=await o.getPage(t,{context:r});if(s!==this.#A)throw new Cr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#A)throw l.discard(),new Cr("superseded","A later selection won");this.#w=!0;try{await this.#Ee(l)}finally{this.#w=!1}this.#u=l.conversationId||t,this.#m=l.conversationRevision||i.conversationRevision||null,this.#h=i.nextCursor,this.#C=null,this.#v=!1,this.#he();for(let c of i.messages)this.#R.set(c.id,c.content);return this.#Se(),this.hydrateMessages(i.messages),this.#P(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#N(),s=this.#F(o?.scope),i=n??this.#h;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#L.get(l);if(c)return c;let d=this.#Ce(r,t,i,s).finally(()=>{this.#L.delete(l)});return this.#L.set(l,d),d}async#Ce(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#u&&this.#u!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=$l(this.messages,i.messages);this.messages=this.#ge(l.map(c=>this.#Me(c))),this.#h=i.nextCursor;for(let c of i.messages)this.#R.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#P(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#N(),o=this.#F(t?.scope);await this.awaitHistorySettled();let r=++this.#A,s=await n.prepareStartNew({context:o});if(r!==this.#A)throw s.discard(),new Cr("superseded","A later action won");await this.#ie(s)}async#ie(t){this.#oe(),await this.#Ee(t),this.#u=t.conversationId||null,this.#m=t.conversationRevision||null,this.#h=null,this.#C=null,this.#v=!1,this.#Se(),this.#P()}async deleteConversation(t,n){let o=this.#N(),r=this.#F(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#u&&await this.#we(r)}async updateConversation(t,n,o){let r=this.#N();if(!r.update)throw new Cr("history_unavailable","This history provider cannot update conversations");let s=this.#F(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#K?.update=="function"}async clearConversationHistory(t){let n=this.#N(),o=this.#F(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#we(o),r}async resetHistoryDevice(){let t=this.#N();if(!t.resetDevice)throw new Cr("history_unavailable","This history provider cannot reset the device");this.#A+=1,this.#x=null;try{return await t.resetDevice()}finally{this.#oe(),this.#u=null,this.#m=null,this.#h=null,this.#C=null,this.#v=!1,this.#P()}}async#we(t){this.#A+=1,this.#x=null,this.#oe(),this.#u=null,this.#m=null,this.#h=null,this.#v=!0,this.#C=null,this.#P(),await this.#xe(t)}async#xe(t){let n=this.#K;if(!n){this.#v=!1,this.#P();return}try{let o=await n.prepareStartNew({context:t});await this.#ie(o)}catch{this.#v=!0,this.#C="new_conversation_required",this.#P(),this.#V("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Te(){if(!(this.#C!=="new_conversation_required"||!this.#K)&&(this.#C=null,await this.#xe(this.#F()),this.#C==="new_conversation_required"))throw new Cr("new_conversation_required","A new conversation is required before sending")}async#Ee(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.#u=t.conversationId,this.#m=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#w||this.#X(t)}#Se(){this.#u?this.config.setStoredConversationId?.(this.#u):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#m),this.historyInternals.setStoredMessageCursor?.(this.#h)}#he(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#R.clear(),this.#pe(null)}#oe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.messages=[],this.#he(),this.#L.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#H(!1),this.#Z("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Ie(t){this.#A+=1,this.#x=null,this.#v=!0,this.#oe(),this.#u=t.conversationId,this.#m=null,this.#h=null,this.#C=null,this.#P(),this.#V("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#I=Promise.resolve().then(()=>{this.#v=!1,this.#I=null,this.#P()})}#Ae(){let t=this.historyInternals.visitorStore??null;t!==this.#$&&(this.#E?.(),this.#E=null,this.#$=t,t&&(this.#E=t.subscribe(n=>this.#ke(n))))}#ke(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#A+=1,this.#x=null,this.#W=!0,this.#B=null;let n=this.messages.length>0;n||this.#u!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#oe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#L.clear(),this.#pe(null)),this.#u=null,this.#m=null,this.#h=null,this.#C=null,this.#P(),n&&this.#V("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#ae(){return this.#W?(this.#B||(this.#B=this.#M().finally(()=>{this.#B=null})),this.#B):Promise.resolve()}async#M(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(t){let n=this.#K,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#u;if(!n||!o)return Promise.resolve();let r=this.#F(t?.scope);this.#v=!0,this.#P();let s=this.#ue(n,o,r).finally(()=>{this.#v=this.#C!==null,this.#I===s&&(this.#I=null),this.#P()});return this.#I=s,s}async#ue(t,n,o){this.#u=n;let r=this.clientSession?.conversationRevision??this.#m??null,s=this.#Y?this.#G:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#Y=!1,this.#h=this.historyInternals.getStoredMessageCursor?.()??this.#h,await this.replayPendingProjections(),r&&s&&r===s){this.#m=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(f=>f.id)),c=this.messages.some(f=>l.has(f.id)),d=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(f=>this.#Me(f));else{let f=this.#o?this.#a:null,m=this.messages.filter(g=>l.has(g.id)||g.id===f?!0:d!==void 0&&g.createdAt<d);p=$l(m,i.messages).map(g=>this.#Me(g))}this.#h=i.nextCursor,this.#m=i.conversationRevision||r||null,this.#R.clear();for(let f of i.messages)this.#R.set(f.id,f.content);this.#Se(),this.messages=this.#ge(p),this.callbacks.onMessagesChanged([...this.messages])}#fe(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#pe(t){this.#J=t,this.historyInternals.setPendingDisplayProjections?.(t)}#De(){return this.historyInternals.getPendingDisplayProjections?.()??this.#J}#_e(t){if(this.#fe())for(let n of t){let o=Vl(n);o!==void 0&&this.#R.set(n.id,o)}}#qe(){if(!this.#fe())return;let t=this.#u;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Vl(o);r!==void 0&&this.#R.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#pe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Oe(t,n))}#Oe(t,n){let r=(this.#x??Promise.resolve()).catch(()=>{}).then(()=>this.#Ne(t,n,!1)).finally(()=>{this.#x===r&&(this.#x=null)});this.#x=r}async#Ne(t,n,o){if(this.#u!==t)return;let r=n.filter(s=>this.#R.get(s.id)!==s.displayContent);if(r.length===0){this.#He(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#R.set(i.id,i.displayContent);this.#u===t&&s&&(this.#m=s),this.#He(t,n)}catch(s){if(!o&&this.#je(s)){await this.#Ne(t,r,!0);return}if(s instanceof kn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#He(t,n);return}this.#V("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#je(t){return t instanceof kn?t.code==="request_failed":t instanceof Error}#He(t,n){let o=this.#De();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#pe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#fe())return;let t=this.#De();if(!t)return;if(this.#u&&t.conversationId!==this.#u){this.#pe(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.#pe(null);return}this.#Oe(t.conversationId,n),await this.#x?.catch(()=>{})}#Ke(){this.#u&&(this.#m=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Fe(){await this.awaitHistorySettled(),await this.#ae(),this.#C==="new_conversation_required"&&await this.#Te()}static#Ge(t){return t instanceof kn&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#_e(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt,voiceSpoken:s?.voiceSpoken},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#_e([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,voiceSpoken:s?.voiceSpoken},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#A+=1,this.#x=null,this.#oe(),this.#u=null,this.#m=null,this.#h=null,this.#w=!0;try{let r=this.#K;if(r){let s=await r.prepareStartNew({context:this.#F()});await this.#ie(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#v=!0,this.#C="new_conversation_required",this.#P(),this.#V("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#w=!1}return this.#le(o),this.#H(!0),this.#V("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=HC(this.config,o),s=WH(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#$e();return}this.#ye(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ul(this.config,this.historyInternals),i&&this.#$e(),this.#Ve(),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:i,createdAt:l,sequence:c,streaming:d=!1,voiceProcessing:p,voiceCaption:f,rawContent:m}=t,h={id:i??(n==="user"?Cp():n==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#Q(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...f&&{voiceCaption:f},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:d,sequence:p,streaming:f=!1,voiceProcessing:m,rawContent:g}=o,b={id:c??(r==="user"?Cp():r==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:p??this.#Q(),streaming:f,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...m!==void 0&&{voiceProcessing:m},...g!==void 0&&{rawContent:g}};n.push(b)}return this.messages=this.#ge([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1172
1172
 
1173
1173
  `),i=[s,n].filter(Boolean).join(`
1174
1174
 
1175
- `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let d=[];s&&d.push(vr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(c){let d=[];i&&d.push(vr(i)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=i);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.#O&&!n?.voiceTurn&&(this.#O.failed=!0,this.#O=null),(this.#I||this.#x||this.#v||this.#W)&&await this.#Fe(),this.stopSpeaking(),this.abortController?.abort(),this.#ye(),this.#me++,this.#ve();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(g=>g.id===s&&g.role==="user"):void 0,l=i?.id??Cp(),c=Ea();this.#a=null;let d=n?.contentParts&&xp(n.contentParts)?La:"",p={id:l,role:"user",content:o||d,createdAt:new Date().toISOString(),sequence:this.#Q(),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??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#le(p),this.#H(!0);let f=new AbortController;if(this.abortController=f,n?.mentions){let g=this.messages.find(h=>h.id===l)??p;if(await this.#Qe(g,o,n.mentions.finalize),f.signal.aborted||this.abortController!==f)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let g=this.messages.find(b=>b.id===l)??p,h=fS({quote:n.quote,text:g.llmContent??g.content,contentParts:g.contentParts});h.contentParts&&(g.contentParts=h.contentParts),h.llmContent!==void 0&&(g.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(g.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let m=i?[...this.messages.filter(g=>g!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(m,f,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt,voiceSpoken:!!n?.voiceTurn})}catch(g){if(this.status==="resuming"||this.#r)return;this.#O&&(this.#O.failed=!0);let h=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));if(!h){let b=ah(g,this.config.errorMessage);if(b){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.#Q()};this.#le(C)}}this.#Z("idle"),this.#H(!1),this.abortController=null,h||(g instanceof Error?this.callbacks.onError?.(g):this.callbacks.onError?.(new Error(String(g))))}}resubmitFrom(t,n){let o=mS(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let d=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.#Je(s.options):r.composerOptions,f=s?s.contentSegments:r.contentSegments,m=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...f?.length?{contentSegments:[...f]}:{},...p?{composerOptions:p}:{},...m?{quote:m}:{},...d&&Object.keys(d).length>0?{replayFields:d}:{},viaVoice:g===!0}),!0}#Je(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.#I||this.#x||this.#v||this.#W)&&await this.#Fe(),this.abortController?.abort(),this.#ve();let t=Ea();this.#a=null,this.#H(!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.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=ah(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#Q()};this.#le(l)}}this.#Z("idle"),this.#H(!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.#a=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#H(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#t;this.#t=s;try{this.handleEvent(i)}finally{this.#t=l}},n?.assistantMessageId,n?.seedContent),this.#Be(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#Be(s),this.#Z("error"),this.webMcpResolveControllers.size===0&&(this.#H(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#Ve(){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.#l}`,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")}#Ze;#me;#Le(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#H(s),appendMessage:s=>this.#le(s),nextSequence:()=>this.#Q(),settleApprovalPausedToolCall:s=>this.#ze(s),resumeAfter:s=>this.#o?.executionId===s?this.#o.lastEventId:void 0},o=uS();if(o)return t(o,n);let r=this.#me;return Kg().then(s=>r===this.#me?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#Le((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Le((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Le((n,o)=>n.resolveWebMcpToolCall(o,t))}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}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#p;queueMicrotask(()=>{s===this.#p&&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))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#p;queueMicrotask(()=>{if(t===this.#p)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(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.#Le((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#ye(){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.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#H(!1),this.#Z("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.messages=[],this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H(!1),this.#Z("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#f}selectArtifact(t){this.#f=t,this.#be()}clearArtifacts(){this.#Re()}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.#f=n,this.#be(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=ks(this.config.features?.artifacts,t),r=Il(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(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#$e(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ks(this.config.features?.artifacts,n),s=Il(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])}#Re(){this.artifacts.size===0&&this.#f===null||(this.artifacts.clear(),this.#f=null,this.#be())}#be(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#f})}#rt(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.#f=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.#be()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ge(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#Q()}))),this.#H(!1),this.#Z("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.#f=n,this.#be()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#a||this.agentExecution?.status!=="running")return;let o=this.#o===null;this.#o={executionId:n,lastEventId:t,assistantMessageId:this.#a,status:"running"},this.#dt(o)}#it(){return this.#o!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ue()}#Ue(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#We(){this.#r||!this.#o||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#o}),this.#H(!0),this.#Z("resuming"),this.#at().then(t=>{this.#r&&this.#o&&t.begin()}))}#at(){return this.#s?Promise.resolve(this.#s):(this.#g||(this.#g=KS().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#s=n,n}),this.#g.catch(()=>{this.#g=null})),this.#g)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#o,clearResumable:()=>t.#Pe(),getStatus:()=>t.status,setStatus:n=>t.#Z(n),setStreaming:n=>t.#H(n),setReconnecting:n=>{t.#r=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.#le(n),nextSequence:()=>t.#Q(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>ah(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#s?.wake();return}this.#We()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=Ea(),this.#le({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#Q()})),this.#a=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#o={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#We()}#ct(){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}#ve(){this.#r=!1,this.#s?.teardown(),this.#Pe()}#Pe(){this.#c&&(clearTimeout(this.#c),this.#c=null);let t=this.#o!==null;this.#o=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#o);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#o)},500))}}getResumableHandle(){return this.#o}#Z(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#H(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#Be(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=sh(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Xg(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=sh(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()}#Be(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#ze(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#ze(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#le(t){let n=this.#Me(t);this.messages=this.#ge([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#Me(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#le(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let f=r.approval,m=n.approval;i.approval={...f,...m,executionId:m.executionId||f.executionId,toolName:m.toolName||f.toolName,description:m.description||f.description,toolType:m.toolType??f.toolType,reason:m.reason??f.reason,parameters:m.parameters??f.parameters,toolCallId:m.toolCallId??f.toolCallId}}let c=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(c&&GS(c)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let f=`${d}:${p}`,m=this.webMcpInflightKeys.has(f),g=this.webMcpResolvedKeys.has(f),h=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&GS(h)&&r.toolCall?.status==="complete";(m||g||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#ge(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#Me(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#Q()}}#Q(){return this.#n++}#ge(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 i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Ge();var Vo=require("lucide");ao();ln();Rs();var WH={add:e=>tx(e)},BH=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,yu={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function DH(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function _H(e){return e==="application/pdf"?Vo.FileText:e.startsWith("text/")?Vo.FileText:e.includes("word")?Vo.FileText:e.includes("excel")||e.includes("spreadsheet")?Vo.FileSpreadsheet:e==="application/json"?Vo.FileCode:Vo.File}var rc=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#n=!1;this.config={allowedTypes:t.allowedTypes??yu.allowedTypes,maxFileSize:t.maxFileSize??yu.maxFileSize,maxFiles:t.maxFiles??yu.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#t;#n;#o(){return typeof this.config.adapter?.add=="function"}#a(){return this.#o()?this.config.adapter:WH}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#f(n)}this.#i()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:yu.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.#n)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=nx(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:DH(),file:o,previewUrl:Sp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#o()?"uploading":"processing",progress:this.#o()?0:void 0};this.attachments.push(s),this.#f(s),n.push(s)}this.#i(),this.#c(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#t.set(t.id,n);let o=()=>this.#n||n.signal.aborted||this.#t.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#a().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=BH(s),this.#p(t),this.#c())}});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.#t.get(t.id)===n&&this.#t.delete(t.id)}this.#p(t),this.#c()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#n||(n.status=this.#o()?"uploading":"processing",n.progress=this.#o()?0:void 0,n.error=void 0,this.#p(n),this.#c(),this.#r(n))}#s(t){let n=this.#t.get(t);n&&(this.#t.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.#s(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#g(o.contentPart),this.#i(),this.#c()}#g(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.#s(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#i(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let t of this.#t.values())t.abort();this.#t.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#f(t){if(!this.#e)return;let n=Sp(t.file),o=v("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=v("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=v("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 f=_H(t.file.type),m=Je(f,20,"var(--persona-muted, #6b7280)",1.5);m&&p.appendChild(m);let g=v("span");g.textContent=ox(t.file.type,t.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",p.appendChild(g),o.appendChild(p)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let i=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=We("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let d=Je(Vo.X,10,"var(--persona-text-inverse, #ffffff)",2);d?c.appendChild(d):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#l(o,t)}#p(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#l(n,t)}#l(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)}%`:""}}#i(){this.#e&&(this.#e.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 YS=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),OH=(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 XS(){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",i=()=>{let p=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(f=>Object.freeze({...f}))),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=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let p=l();for(let f of[...t])try{f(p)}catch(m){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",m)}},d=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,d())},setAttachments:p=>{OH(e.attachments,p)||(e.attachments=[...p],d())},setMentionRefs:p=>{YS(e.mentionRefs,p)||(e.mentionRefs=[...p],d())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,d())},setActiveModeIds:p=>{YS(e.activeModeIds,p)||(e.activeModeIds=[...p],d())},setQuote:p=>{let f=e.quote;f?.text===p?.text&&f?.messageId===p?.messageId&&f?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,d())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,d())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,d())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,d())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,d())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,d())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Ge();var wo=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},QS=(e,t)=>{let n=v("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function JS(e,t={}){let n=wo(e,"[data-persona-composer-form]"),o=wo(e,"[data-persona-composer-input]");if(!n||!o){let A=`[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(A);return typeof console<"u"&&console.warn(A),null}let r={header:wo(e,"[data-persona-composer-header]"),body:wo(e,"[data-persona-composer-body]"),actionsStart:wo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:wo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:wo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:wo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:wo(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=QS("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,S,E,k)=>{if(A)return A;s.add(C);let D=QS(S,E);return k.appendChild(D),D},d=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),f=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),m=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),g=[],h=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,b=wo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:d,actionsEnd:p,suggestions:f,status:m,attachmentInput:b,attachmentPreviews:wo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:wo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:wo(e,"[data-persona-composer-submit]")??void 0,micButton:wo(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,S,E)=>{C.addEventListener(A,S,E),g.push({target:C,type:A,handler:S,options:E})},removeListener:(C,A,S,E)=>{C.removeEventListener(A,S,E),g=g.filter(k=>!h(k,{target:C,type:A,handler:S}))},destroy:()=>{for(let C of g)C.target.removeEventListener(C.type,C.handler,C.options);g=[]}}}Ge();ln();Pa();Ws();Ra();Ge();ln();Ws();var NH='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',FH=["--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"],lh="data-persona-menu-focus",VH=new Set(["ArrowDown","ArrowUp","Home","End"]);function ZS(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(NH)??e}var $H=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function eA(e){let t=e.label,n=!1,o=v("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Mo} ${rr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{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 J=We("plus",Co,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],d=-1,p=!1,f=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},m=()=>{let I=f();for(let J of c){let _=!!I&&ZS(J)===I;J.toggleAttribute(lh,_&&p)}},g=()=>c.filter(I=>I.isConnected||s.contains(I)).map(ZS).filter(I=>!$H(I)),h=(I,J)=>{I.forEach((_,j)=>{_.setAttribute("tabindex",j===J?"0":"-1")})},b=I=>{let J=g();if(J.length===0)return;let _=(I%J.length+J.length)%J.length;d=_,h(J,_),J[_].focus(),m()},C=()=>o.ownerDocument??document,A=null,S=null,E=null,k=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},D=()=>{S&&(s.removeEventListener("focusin",S),S=null),E&&(s.removeEventListener("pointerdown",E,!0),E=null)},z=null,Y=()=>(z||(z=Bs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),k()}})),z),T=()=>z?.isOpen===!0,W=(I=!1)=>{if(T()){z?.close(),r.setAttribute("aria-expanded","false"),k(),D(),d=-1,p=!1;for(let J of c)J.removeAttribute(lh);I&&r.focus()}},L=(I=0,J=!1)=>{if(n||T())return;p=J,Bp(r,s,FH),Y().open(),r.setAttribute("aria-expanded","true");let _=g();h(_,-1),b(I<0?_.length-1:I),A=j=>{let te=typeof j.composedPath=="function"?j.composedPath():[];te.includes(s)||te.includes(o)||W()},C().addEventListener("focusin",A,!0),S=()=>m(),s.addEventListener("focusin",S),E=()=>{p=!1},s.addEventListener("pointerdown",E,!0)},w=I=>{I.preventDefault(),I.stopPropagation(),T()?W(!0):L(0)},x=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),p=!0,T()?b(0):L(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),p=!0,T()?b(-1):L(-1,!0))},P=I=>{switch(VH.has(I.key)&&(p=!0),I.key){case"ArrowDown":I.preventDefault(),b(d+1);return;case"ArrowUp":I.preventDefault(),b(d-1);return;case"Home":I.preventDefault(),b(0);return;case"End":I.preventDefault(),b(g().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),W(!0);return;case"Tab":W(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",x),s.addEventListener("keydown",P),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let _ of c)I.includes(_)||_.removeAttribute(lh);if(c=[...I],!T())return;let J=g();h(J,Math.min(d,J.length-1)),m()},isOpen:T,open:()=>L(0),close:W,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:i,destroy:()=>{n=!0,k(),D(),r.removeEventListener("click",w),r.removeEventListener("keydown",x),s.removeEventListener("keydown",P),z?.destroy(),z=null,o.remove(),s.remove(),c=[]}}}var wr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},tA="data-persona-composer-action",ch="data-persona-composer-disable-when-streaming",UH="core:overflow",zH=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function qH(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=v("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 dh(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 nA=(e,t)=>{!e||typeof console>"u"||console.warn(t)},jH=(e,t)=>t.includes(":")?t:`${e}:${t}`;function KH(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){nA(t,`[Persona] composer action "${l.id}" is already contributed by ${oA(c)}; the ${oA(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 i=(l,c,d)=>{let p=d?jH(d,l.id):l.id,f=l.order??wr.custom;l.placement==="end"&&f>=wr.send&&(nA(t,`[Persona] composer action "${p}" ordered at ${f} would render after send; clamped to ${wr.send-1}.`),f=wr.send-1),s({id:p,placement:l.placement,presentation:l.presentation??"bar",order:f,sequence:r++,source:c,pluginId:d,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(d){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,d);continue}for(let d of c??[])i(d,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var oA=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",rA=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,GH=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function YH(e,t){if(!e||e==="always")return!0;let n=GH(t);return e==="when-text"?n:!n}var _s=e=>e.kind==="custom",ph=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,XH=e=>{let t=ph(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},QH='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function JH(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(QH)||o.childNodes.forEach(n)};return n(e),t.trim()}var ZH=e=>JH(e).length===0;function sA(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(w,x)=>{let P=w.button;if(!P)return;P.setAttribute("role","menuitem"),P.setAttribute("tabindex","-1"),P.className="persona-composer-overflow-menu__item";for(let _ of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])P.style[_]="";P.style.lineHeight="1",x.tooltipText?P.setAttribute("title",x.tooltipText):P.removeAttribute("title"),P.replaceChildren();let I=v("span","persona-composer-overflow-menu__icon");if(x.iconName){let _=We(x.iconName,16,"currentColor",1.5);_&&I.appendChild(_)}let J=v("span","persona-composer-overflow-menu__label");J.textContent=x.shortLabel??x.label,P.append(I,J)},i=(w,x)=>{let P=w.button;if(!P)return;if(P.setAttribute("aria-label",x.label),x.pressed===void 0?P.removeAttribute("aria-pressed"):P.setAttribute("aria-pressed",x.pressed?"true":"false"),P.toggleAttribute(ch,x.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,x);return}P.removeAttribute("role"),P.removeAttribute("tabindex"),P.removeAttribute("title");let I=r(),J=!!x.shortLabel;if(P.className=Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Mo,rr,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),P.style.width=I&&!J?I:"",P.style.height=I??"",P.style.minWidth=I&&!J?I:"",P.style.minHeight=I??"",P.style.fontSize=J?"":"18px",P.style.lineHeight="1",P.style.color=x.iconColor??"",P.style.backgroundColor=x.backgroundColor??"",P.replaceChildren(),x.iconName){let _=We(x.iconName,Co,"currentColor",1.5);_&&P.appendChild(_)}if(J){let _=v("span","persona-composer-action-button__label");_.textContent=x.shortLabel,P.appendChild(_)}else P.firstChild||(P.textContent=x.label);w.tooltip?.destroy(),w.tooltip=$n({anchor:P,trigger:w.element,text:()=>x.tooltipText??x.label,enabled:!!x.tooltipText})},l=(w,x)=>{let P=w.action,I=F("button",{attrs:{type:"button"}}),J=I;if(x==="bar"){let te=v("div","persona-send-button-wrapper");te.appendChild(I),J=te}J.setAttribute(tA,w.id);let _={resolved:w,element:J,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:x},j=te=>{if(te.preventDefault(),te.stopPropagation(),_.busy||I.disabled)return;let K=_.resolved.action;_.mode==="menu"&&g?.close(!0);let X;try{X=K.onSelect(e.actionContext,te)}catch(oe){e.reportError(oe,{actionId:_.resolved.id});return}!X||typeof X.then!="function"||(_.busy=!0,I.setAttribute("aria-busy","true"),X.catch(oe=>{e.reportError(oe,{actionId:_.resolved.id})}).finally(()=>{_.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",j),_.detach=()=>I.removeEventListener("click",j),i(_,P),_},c=w=>{let x=w.action,P;try{P=x.render({...e.actionContext,id:w.id,action:x})}catch(I){return e.reportError(I,{actionId:w.id}),null}return P?.element?(P.element.setAttribute(tA,w.id),P.element.toggleAttribute(ch,x.disableWhenStreaming===!0),{resolved:w,element:P.element,owned:!0,managed:!0,destroy:P.destroy,busy:!1,visible:!0,mode:"bar"}):null},d=(w,x)=>{if(w.builtIn){let I=w.builtIn.element;return I?{resolved:w,element:I,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let P=w.action;return P?_s(P)?c(w):l(w,x):null},p=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(x){e.reportError(x,{actionId:w.resolved.id})}w.element.remove()}},f=(w,x)=>{for(let P=0;P<x.length;P++){let I=x[P];if(!I.managed)continue;let J=null;for(let _=P+1;_<x.length;_++){let j=x[_];if(!j.managed&&j.element.parentElement===w){J=j.element;break}}J?(I.element.parentElement!==w||I.element.nextSibling!==J)&&w.insertBefore(I.element,J):w.lastChild!==I.element&&w.appendChild(I.element)}},m=(w,x)=>{if(w.button){w.button.disabled=x;return}if(!w.owned)return;let P=w.element;P.toggleAttribute("data-disabled",x),P.setAttribute("aria-disabled",x?"true":"false");let I=P instanceof HTMLButtonElement||P instanceof HTMLSelectElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement?P:P.querySelector("button, select, input, textarea");I&&(I.disabled=x)},g=null,h=null,b=null,C=0,A=()=>{let w=e.getOverflow?.();return w?.enabled===!0?w:void 0},S=()=>(g?g.setLabel(e.getOverflowLabel?.()??"More actions"):g=eA({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),E=w=>{h!==w&&(b?.disconnect(),h=w,C=dh(w),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(x=>{let I=x[x.length-1]?.contentRect?.width??dh(w);I!==C&&(C=I,W())}),b.observe(w)))},k=(w,x)=>{let P=qH(w.collapseAutoActionsBelow,x);if(P===null)return!1;let I=C||dh(x);return I>0&&I<P},D=(w,x,P)=>{if(!x)return"bar";if(w.resolved.builtIn){let J=zH(w.resolved.id);return J&&x.includeBuiltIns?.includes(J)?"menu":"bar"}let I=w.resolved.presentation;return I==="overflow"||I==="auto"&&P?"menu":"bar"},z=w=>{let x=w.menuSlot;if(!x)return;if(!ZH(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let P=XH(w.element);if(!P){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==P&&(w.menuLabel.textContent=P),w.menuLabel.parentElement!==x&&x.appendChild(w.menuLabel)},Y=(w,x)=>{if(w.mode===x)return w;let P=w.resolved.action;if(P&&!_s(P)){p(w),t.delete(w.resolved.id);let I=l(w.resolved,x);return t.set(w.resolved.id,I),I}if(x==="menu"){let I=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[wg]:""}});I.appendChild(w.element),bx(ph(w.element)),w.menuSlot=I;let J=_=>{let j=ph(w.element);if(j.disabled)return;let te=_.target===j||j.contains(_.target);g?.close(!0),te||j.click()};I.addEventListener("click",J,!0),w.detachMenuSlot=()=>I.removeEventListener("click",J,!0),w.managed=!0,z(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=x,w},T=(w,x)=>{let P=x.map(I=>I.menuSlot??I.element);for(P.forEach((I,J)=>{let _=w.children[J];_!==I&&(_?w.insertBefore(I,_):w.appendChild(I))});w.children.length>P.length;)w.lastElementChild?.remove()},W=()=>{if(o)return;let w=e.getBindings();if(!w)return;let x=e.getState(),P=x.phase==="streaming",I=A();I&&E(w.footer);let J=I?k(I,w.footer):!1,_={start:[],end:[]},j=[];for(let te of n){let K=t.get(te.id);if(!K)continue;let X=te.action,oe=X?rA(X.visible,x,!0)&&YH(X.visibility,x):!0;if(K.visible!==oe&&(K.visible=oe,!oe&&K.managed&&(K.menuSlot??K.element).remove()),!!oe){if(K=Y(K,D(K,I,J)),X){let de=rA(X.disabled,x,!1)||X.disableWhenStreaming===!0&&P;m(K,de),!_s(X)&&X.pressed!==void 0&&K.button?.setAttribute("aria-pressed",X.pressed?"true":"false")}K.mode==="menu"?(z(K),j.push(K)):_[te.placement].push(K)}}if(j.length>0){let te=S();T(te.panel,j),te.setItems(j.map(de=>de.menuSlot??de.element)),te.applyButtonSize();let K=Number.isFinite(I?.order)?I?.order:wr.overflow,X=_.start.findIndex(de=>de.resolved.order>K),oe={resolved:{id:UH,placement:"start",presentation:"bar",order:K,sequence:-1,source:"core"},element:te.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};_.start.splice(X<0?_.start.length:X,0,oe)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));f(w.actionsStart,_.start),f(w.actionsEnd,_.end)};return{resolve:()=>{if(o)return;let w=KH(e.collect()),x=new Set(w.map(P=>P.id));for(let[P,I]of t)x.has(P)||(p(I),t.delete(P));for(let P of w){let I=t.get(P.id);if(!I){let te=d(P,"bar");te&&t.set(P.id,te);continue}let J=I.resolved.action,_=P.action;if(!!J!=!!_||J&&_&&_s(J)!==_s(_)||J&&_&&_s(J)&&_s(_)&&J.render!==_.render){p(I),t.delete(P.id);let te=d(P,I.mode);te&&t.set(P.id,te);continue}I.resolved=P,P.builtIn?(I.managed=P.builtIn.managed===!0||I.mode==="menu",P.builtIn.element&&I.mode==="bar"&&(I.element=P.builtIn.element)):_&&!_s(_)?i(I,_):_&&I.element.toggleAttribute(ch,_.disableWhenStreaming===!0)}n=w,W()},sync:W,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,b?.disconnect(),b=null,h=null;for(let w of t.values())p(w);t.clear(),g?.destroy(),g=null,n=[]}}}}Ra();Ge();ln();Ws();var eR="core:model",tR=700,iA=16,nR=["--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"],aA=()=>{let e=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function lA(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let d=e.getSelectedModelId();return c.find(p=>p.id===d)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),d="",p=()=>{let b=e.getModels(),C=b.map(A=>`${A.id}:${A.label}`).join("|");C!==d&&(d=C,c.replaceChildren(...b.map(A=>{let S=F("option",{attrs:{value:A.id}});return S.textContent=A.label,S}))),c.value=r(b)?.id??""};p(),o=p;let f=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",f);let m=b=>b.stopPropagation();c.addEventListener("click",m);let{wrapper:g,chevron:h}=aA();return g.append(c,h),{element:g,destroy:()=>{o===p&&(o=null),c.removeEventListener("change",f),c.removeEventListener("click",m)}}},i=()=>{let c=F("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"}}),d=v("span","persona-composer-model-picker-label"),p=v("span","persona-composer-model-picker-suffix");c.append(d,p);let f=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),m=new Map,g="",h=null,b=()=>h?.isOpen===!0,C=(x=!1)=>{b()&&(h?.close(),c.setAttribute("aria-expanded","false"),x&&c.focus())},A=x=>{let P=[...m.values()];if(P.length===0)return;let I=(x%P.length+P.length)%P.length;P[I].focus()},S=x=>{if(b())return;h||(h=Bs({anchor:c,content:f,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Bp(c,f,nR),h.open(),c.setAttribute("aria-expanded","true");let I=[...m.keys()].indexOf(r(e.getModels())?.id??"");A(x??(I>=0?I:0))},E=x=>{C(!0),e.onSelect(x)},k=x=>{x.preventDefault(),x.stopPropagation();let P=x.currentTarget.getAttribute("data-persona-model-option");P&&E(P)},D=x=>{let P=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":x.id}});if(x.icon){let te=We(x.icon,iA,"currentColor",1.5);if(te){let K=v("span","persona-composer-model-option-icon");K.appendChild(te),P.appendChild(K)}}let I=v("span","persona-composer-model-option-body"),J=v("span","persona-composer-model-option-label");if(J.textContent=x.label,I.appendChild(J),x.description){let te=v("span","persona-composer-model-option-description");te.textContent=x.description,I.appendChild(te)}P.appendChild(I);let _=v("span","persona-composer-model-option-check");_.setAttribute("aria-hidden","true");let j=We("check",iA,"currentColor",2);return j&&_.appendChild(j),P.appendChild(_),P.addEventListener("click",k),P},z=()=>{let x=e.getModels(),P=x.map(_=>`${_.id}:${_.label}:${_.icon??""}:${_.description??""}`).join("|");if(P!==g){g=P;for(let _ of m.values())_.removeEventListener("click",k);m.clear(),f.replaceChildren(...x.map(_=>{let j=D(_);return m.set(_.id,j),j}))}let I=r(x);for(let[_,j]of m)j.setAttribute("aria-selected",String(_===I?.id));d.textContent=I?.label??"";let J=e.getSuffix?.()??"";p.textContent=J,c.setAttribute("aria-label",[t,[I?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};z(),o=z;let Y=x=>{x.preventDefault(),x.stopPropagation(),b()?C(!0):S()},T=x=>{if(x.key==="ArrowDown"){x.preventDefault(),b()?A(0):S(0);return}x.key==="ArrowUp"&&(x.preventDefault(),b()?A(-1):S(-1))},W=x=>{let P=[...m.values()],I=P.indexOf(x.target?.closest?.(".persona-composer-model-option"));switch(x.key){case"ArrowDown":x.preventDefault(),A(I+1);return;case"ArrowUp":x.preventDefault(),A(I-1);return;case"Home":x.preventDefault(),A(0);return;case"End":x.preventDefault(),A(P.length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",Y),c.addEventListener("keydown",T),f.addEventListener("keydown",W);let{wrapper:L,chevron:w}=aA();return L.append(c,w),{element:L,destroy:()=>{o===z&&(o=null),c.removeEventListener("click",Y),c.removeEventListener("keydown",T),f.removeEventListener("keydown",W);for(let x of m.values())x.removeEventListener("click",k);m.clear(),h?.destroy(),h=null,f.remove()}}};return{action:{id:eR,kind:"custom",placement:"end",order:tR,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ge();ln();zp();var oR=":scope > [data-persona-composer-mode]";function cA(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=d=>{let p=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":d.id}});if(d.iconName){let h=v("span","persona-mention-chip-icon"),b=We(d.iconName,12,"currentColor",1.5);b&&h.appendChild(b),p.appendChild(h)}let f=v("span","persona-mention-chip-label");f.textContent=d.shortLabel??d.label,p.appendChild(f);let m=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${d.label}`}}),g=We("x",12,"currentColor",2);return g?m.appendChild(g):m.textContent="\xD7",m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),e.onRemove(d.id)}),p.appendChild(m),p},i=()=>Array.from(t.querySelectorAll(oR)),l=d=>{d.setAttribute("data-persona-chip-exit",""),d.setAttribute("aria-hidden","true"),d.style.pointerEvents="none";let p=()=>{d.remove(),Ha(t)},f=t.ownerDocument.defaultView,m=typeof f?.getComputedStyle=="function"?f.getComputedStyle(d).animationName:"";if(!m||m==="none"){p();return}d.addEventListener("animationend",p,{once:!0}),d.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let d of i())d.remove()};return{element:t,render:(d,p)=>{if(o)return;let f=p.filter(b=>d.includes(b.id)),m=f.map(b=>`${b.id}:${b.shortLabel??b.label}`).join("|");if(m===n)return;n=m;let g=new Map;for(let b of i()){let C=b.getAttribute("data-persona-composer-mode");C&&f.some(S=>S.id===C)&&!b.hasAttribute("data-persona-chip-exit")?g.set(C,b):b.hasAttribute("data-persona-chip-exit")||l(b)}let h=t.firstChild;for(let b of f){let C=g.get(b.id);C||(C=s(b),r.has(b.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(b.id),C!==h&&t.insertBefore(C,h),h=C.nextSibling}Ha(t)},destroy:()=>{o=!0,c(),Ha(t)}}}Ge();ln();var dA=e=>`core:mode:${e}`;var uh=e=>Math.min(300+e,499),pA=e=>`core:mode-group:${e}`;function bu(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function rR(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function uA(e,t){return e?.length?e.filter(n=>!bu(n.groupId,t)&&!rR(n.groupId,t)):[]}var sR=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function fA(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(sR(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function vu(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function mA(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function gA(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var iR=16;function hA(e){let t=null;return{action:{id:pA(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=d=>{d.preventDefault(),d.stopPropagation();let f=d.currentTarget.getAttribute("data-persona-composer-mode");!f||e.getActiveIds().includes(f)&&e.getGroup()?.selection==="single"||e.onSelect(f)},l=d=>{let p=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":d.id,"aria-label":d.label}});if(d.iconName){let m=We(d.iconName,iR,"currentColor",1.5);m&&p.appendChild(m)}let f=v("span","persona-composer-segmented-label");return f.textContent=d.shortLabel??d.label,p.appendChild(f),p.addEventListener("click",i),p},c=()=>{let d=e.getGroup();d?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",d.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let p=e.getModes(),f=p.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(f!==s){s=f;for(let h of r.values())h.removeEventListener("click",i);r.clear();let g=p.map(h=>{let b=l(h);return r.set(h.id,b),b});o.replaceChildren(...g)}let m=e.getActiveIds();for(let[g,h]of r)h.setAttribute("aria-pressed",String(m.includes(g)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let d of r.values())d.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}zp();Ge();ln();function yA(e){let t=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let f=v("div","persona-composer-quote-source");f.textContent=s.sourceLabel,l.appendChild(f)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=lu(s.text),l.appendChild(c);let d=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=We("x",12,"currentColor",2);p?d.appendChild(p):d.textContent="\xD7",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,d)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Ge();ln();function bA(e){let t=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,d)=>{let p=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),f=We(i,12,"currentColor",2);return f?p.appendChild(f):p.textContent=l,p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),d()}),p},s=i=>{let l=lu(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=F("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,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()}}}Ge();function vA(e){let t=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=F("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=v("div","persona-message-edit-actions"),s=(l,c,d,p)=>{let f=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[d]:""},text:l});return f.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),p()}),f},i=()=>{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",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),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 CA(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 wA(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),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}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function xA(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 SA(e){return e.wrapped||e.text.includes(`
1176
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function AA(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function MA(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 i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}Jp();Wp();function fh(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 EA(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var aR=e=>typeof e?.then=="function";function TA(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 kA(e,t,n){let o;try{o=e(fh(t),{signal:n})}catch(r){return{status:"error",error:r}}return aR(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:TA(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):TA(t,o)}Wg();Ug();Eg();Rs();var Cu=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),wu={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"};er();er();var Su="16px",Au="transparent",lR=(()=>{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})(),sc={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:lR,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"}},xu={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"}},To={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:Um,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Su,canvasBackground:Au,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"}}},cR=sc.colors.gray,dR={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},pR={...sc,colors:{...sc.colors,gray:cR}},uR={...sc,colors:{...sc.colors,gray:dR},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var fR=xu,mR={...xu,colors:{...xu.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...xu.typography,fontSize:"14px",lineHeight:"1.5"}};var gh=To,gR={...To,launcher:wu,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:{...To.input,borderRadius:"palette.radius.full"},introCard:{...To.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...To.suggestion.chip,fontWeight:"400"},card:{...To.suggestion.card,fontWeight:"400"},list:{...To.suggestion.list,fontWeight:"400"}},panel:{...To.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...To.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:{...To.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...To.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:{...To.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...To.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)"}};var hR=e=>Ts({future:e}),hh=e=>hR(e)==="v5"?{palette:uR,semantic:mR,components:gR}:{palette:pR,semantic:fR,components:gh};function zn(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."))?zn(e,o):o}function PA(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=zn(e,i);c!==void 0&&(t[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yR(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 IA(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]=IA(s,r):n[o]=r}return n}function bR(e,t){return t?IA(e,t):e}function _a(e,t={}){let n=hh(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:bR(o.components,e?.components)},s=e?.components?.activity;for(let d of["toolBubble","reasoningBubble"])for(let p of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[p]!==void 0&&(r.components[d][p]=s[p]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let d=yR(r);if(!d.valid)throw new Error(`Theme validation failed: ${d.errors.map(p=>p.message).join(", ")}`)}if(t.plugins)for(let d of t.plugins)r=d.transform(r);return r}var mh=e=>e.trim()==="0"?"0px":e,LA="--persona-",vR=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let d=c.endsWith("%"),p=parseFloat(d?c.slice(0,-1):c);return d?p/100*255:p}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},CR=.179,Un=(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[LA+s],r!==void 0)break;r!==void 0&&(e[LA+n]=r)}};function HA(e){let t=PA(e),n={};for(let[N,ke]of Object.entries(t)){let ve=N.replace(/\./g,"-");n[`--persona-${ve}`]=ke.value}Un(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"],Un(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"]]),Un(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"]}`,Un(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"]??Su,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Au,Un(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"]]),Un(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=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"],Un(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"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],Un(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 c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let d=n["--persona-components-history-railHeader-border"];d&&(n["--persona-history-rail-header-border"]=d);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[N,ke]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ve=n[`--persona-components-history-overlay-${N}`];ve&&(n[`--persona-history-overlay-${ke}`]=ve)}for(let[N,ke]of[["background","bg"],["borderRadius","radius"]]){let ve=n[`--persona-components-history-menu-${N}`];ve&&(n[`--persona-history-menu-${ke}`]=ve)}let f=e.components?.history?.motion;if(f){let N=tt=>{if(tt===void 0)return;let xt=String(tt).trim();return/^\d+(\.\d+)?$/.test(xt)?`${xt}ms`:xt},ke=N(f.enterDurationMs);ke!==void 0&&(n["--persona-history-enter-ms"]=ke);let ve=N(f.exitDurationMs);ve!==void 0&&(n["--persona-history-exit-ms"]=ve),f.enterEasing&&(n["--persona-history-enter-easing"]=f.enterEasing),f.exitEasing&&(n["--persona-history-exit-easing"]=f.exitEasing)}let m=n["--persona-components-history-dangerForeground"];m&&(n["--persona-history-danger-fg"]=m),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 N of["scrim","shadow"]){let ke=n[`--persona-components-history-confirm-${N}`];ke&&(n[`--persona-history-confirm-${N}`]=ke)}for(let[N,ke]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ve=n[`--persona-components-tooltip-${N}`];ve&&(n[`--persona-tooltip-${ke}`]=ve)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,ke]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ve=n[`--persona-components-messageActions-${N}`];ve&&(n[`--persona-message-action-${ke}`]=ve)}Un(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let g=n["--persona-components-introCard-background"],h=n["--persona-components-introCard-shadow"],b=(!g||g==="transparent"||g==="none")&&(!h||h==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=b&&C==="1.5rem"?"1.5rem 0":C,Un(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"]]),Un(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 A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let S=n["--persona-components-markdown-heading-h1-fontWeight"];S&&(n["--persona-md-h1-weight"]=S);let E=n["--persona-components-markdown-heading-h2-fontSize"];E&&(n["--persona-md-h2-size"]=E);let k=n["--persona-components-markdown-heading-h2-fontWeight"];k&&(n["--persona-md-h2-weight"]=k);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),Un(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"]]),Un(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Un(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Un(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Un(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 z=[["container","surface"],["surface","surface"],["border","border"]];for(let[N,ke]of z){let ve=n[`--persona-components-collapsibleWidget-${N}`]??n[`--persona-${ke}`];ve!==void 0&&(n[`--persona-cw-${N}`]=ve,n[`--cw-${N}`]=ve)}Un(n,[["message-border","components-message-border","border"]]),Un(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 Y=e.components,T=Y?.iconButton;T&&(T.background&&(n["--persona-icon-btn-bg"]=T.background),T.border&&(n["--persona-icon-btn-border"]=T.border),T.color&&(n["--persona-icon-btn-color"]=T.color),T.padding&&(n["--persona-icon-btn-padding"]=T.padding),T.borderRadius&&(n["--persona-icon-btn-radius"]=T.borderRadius),T.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=T.hoverBackground),T.hoverColor&&(n["--persona-icon-btn-hover-color"]=T.hoverColor),T.activeBackground&&(n["--persona-icon-btn-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-icon-btn-active-border"]=T.activeBorder));let W=Y?.labelButton;W&&(W.background&&(n["--persona-label-btn-bg"]=W.background),W.border&&(n["--persona-label-btn-border"]=W.border),W.color&&(n["--persona-label-btn-color"]=W.color),W.padding&&(n["--persona-label-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-label-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-label-btn-hover-bg"]=W.hoverBackground),W.fontSize&&(n["--persona-label-btn-font-size"]=W.fontSize),W.gap&&(n["--persona-label-btn-gap"]=W.gap));let L=Y?.toggleGroup;L&&(L.gap&&(n["--persona-toggle-group-gap"]=L.gap),L.borderRadius&&(n["--persona-toggle-group-radius"]=L.borderRadius));let w=Y?.artifact;if(w?.toolbar){let N=w.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=mh(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=mh(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(e,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=mh(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(w?.tab){let N=w.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(w?.pane){let N=w.pane;if(N.toolbarBackground){let ke=zn(e,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ke}}if(w?.card){let N=w.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(w?.inline){let N=w.inline;N.background&&(n["--persona-artifact-inline-bg"]=zn(e,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(e,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(e,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(e,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(e,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let x=Y?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=zn(e,x.background)??x.background));let P=n["--persona-surface"],I=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",_=n["--persona-palette-colors-gray-200"]??"#e5e7eb",j=n["--persona-palette-colors-gray-300"]??"#d1d5db",te=!I||I===P,K=vR(P??n["--persona-background"]),X=te&&K!==void 0&&K<CR,oe=X?"rgba(255, 255, 255, 0.08)":J,de=X?"rgba(255, 255, 255, 0.12)":_,xe=X?"rgba(255, 255, 255, 0.16)":j,Te=te?oe:I,re=te?de:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Te,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??re,te&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??xe),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Te,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Te,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Te,n}Vd();var wR=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),RA=(e,t)=>{if(!t||!wR(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ac(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Ts(t)==="v5"?"400px":"420px"}}}},xR={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"}}},ic={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)"}}}},yh=xR,SR={...yh,colors:{...yh.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"}}},AR=ic,MR={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:{...ic.components,button:{...ic.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:{...ic.components?.eventStream,badge:{...ic.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"}}}}},TR=e=>Ts({future:e})==="v5"?{palette:SR,components:MR}:{palette:yh,components:AR},WA=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bh=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",ER=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":bh()},ac=e=>ER(e),kR=(e,t={})=>_a(e,t),LR=(e,t={})=>{let n=TR(t.future),o=Zo(n.components,e??{})??{};return _a({...o,palette:{...o.palette,colors:Ts(t)==="v5"?Zo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Jr=e=>{let t=ac(e),n=WA(e?.theme),o=Cu(e)==="circle"?wu:{...gh.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Zo({components:{launcher:o}},n),s=WA(e?.darkTheme);return RA(t==="dark"?LR(Zo(r??{},s??{}),{future:e?.future}):kR(r,{future:e?.future}),e)},PR=e=>HA(e),lc=(e,t)=>{let n=Jr(t),o=PR(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ac(t)),e.setAttribute("data-persona-defaults",Ts(t))},Mu=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(bh())});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(bh());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())}};Vd();var rs=require("lucide");ln();ao();Ge();var Os=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Tu="24px",vh=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",cc=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},BA=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);Pa();zd();Pu();var NA=require("idiomorph"),Iu=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;NA.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 i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var FA=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var wh={index:-1,draft:""};function VA(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){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(!i)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 $A(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 UA(){return new Map}function zA(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function qA(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function jA(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}Sh();nr();hc();Bn();var{setLoader:n$,load:sW}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(gM(),mM))});var hM=sW;nr();function Lh(e,t=Jn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var bc=0,Ns=null;function Ph(e=document){if(bc++,bc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ns={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,bc=Math.max(0,bc-1),bc===0&&Ns)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ns.originalOverflow,n.style.position=Ns.originalPosition,n.style.top=Ns.originalTop,n.style.width=Ns.originalWidth,o.scrollTo(0,Ns.scrollY),Ns=null}}}ha();var vc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},un=e=>(e?.launcher?.mountMode??"floating")==="docked",Cc=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",$o=e=>{let t=e?.launcher?.dock,n=Ur(e).dockWidth?t?.width:zn(Jr(e),"components.panel.width");return{side:t?.side??vc.side,width:n??vc.width,animate:t?.animate??vc.animate,reveal:t?.reveal??vc.reveal,maxHeight:t?.maxHeight??vc.maxHeight}};Ge();Ge();var bM=require("lucide");ln();ao();var Ih=e=>e==="followUp"?"follow-up":e,Hh=(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"}},yM=new WeakSet,iW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aW=e=>{iW()||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"})})},Rh=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:d,session:p,getTextarea:f,eventTarget:m,submitPrompt:g}=e,h=o==="followUp",b=t.behavior,C=()=>{if(p.isStreaming())return;let E={suggestion:{...t},surface:o,source:r,behavior:b},k=m.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:E,bubbles:!0,composed:!0,cancelable:!0}));if(h&&m.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!k)return;for(let z of c)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let D=f();if(b==="fill"){D.value=t.prompt,D.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),D.focus();return}if(g){g(t.prompt);return}D.value="",p.sendMessage(t.prompt)},A=()=>{let E=v("button",`persona-suggestion persona-suggestion--${s}`);if(E.type="button",E.disabled=i,E.dataset.suggestionId=t.id,E.dataset.emphasis=t.emphasis,E.dataset.behavior=b,s==="chip"&&(d?.fontWeight&&(E.style.fontWeight=d.fontWeight),d?.paddingX&&(E.style.paddingLeft=d.paddingX,E.style.paddingRight=d.paddingX),d?.paddingY&&(E.style.paddingTop=d.paddingY,E.style.paddingBottom=d.paddingY)),t.icon){let D=We(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);D&&(D.classList.add("persona-suggestion__icon"),t.iconColor&&(D.style.color=t.iconColor),E.appendChild(D))}let k=v("span","persona-suggestion__copy");if(k.appendChild(F("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&k.appendChild(F("span",{className:"persona-suggestion__description",text:t.description})),E.appendChild(k),s!=="chip"){let D=Je(bM.ArrowRight,16,"currentColor",1.8);D&&(D.classList.add("persona-suggestion__arrow"),E.appendChild(D))}return E.addEventListener("click",C),E},S=null;for(let E of c)if(E.renderSuggestion&&(S=E.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),S))break;return S??=A(),S.dataset.suggestionId||=t.id,S.dataset.behavior||=b,S.dataset.emphasis||=t.emphasis,S instanceof HTMLButtonElement||S.setAttribute("aria-disabled",i?"true":"false"),S},wc=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{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 f=getComputedStyle(e).direction==="rtl",m=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),g=4,h=m<=g,b=m>=p-g,C=f?!b:!h,A=f?!h:!b;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,f,m,g,h,b)=>{e.replaceChildren(),t.length=0,n.length=0;let C=b?.source??"config",A=b?.surface??(C==="config"?"starter":"followUp"),S=A==="followUp",E=b?.variant??"chip",k=b?.behavior??"send",D=b?.overflow??"wrap",z=b?.config??{},Y=b?.plugins??[],T=typeof b?.maxItems=="number"?Math.max(0,Math.floor(b.maxItems)):void 0,W=S?"followUps":"starters";!yM.has(z)&&z.debug===!0&&E!=="chip"&&z.suggestions?.[W]?.overflow!==void 0&&(yM.add(z),console.info(`[persona] suggestions.${W}.overflow applies to the "chip" variant only; the "${E}" variant manages its own stacking.`));let L=_=>_.map(Hh).filter(j=>j!==null).map(j=>({...j,behavior:j.behavior??k})),w=L(p??[]);Y.forEach(_=>{_.transformSuggestions&&(w=L(_.transformSuggestions({suggestions:w.map(j=>({...j})),surface:A,source:C,config:z})))});let x=T===void 0?w:w.slice(0,T);if(!x.length){e.hidden=!0,o=null,s();return}if(!S&&(g??f.getMessages()).some(j=>j.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ih(A),e.dataset.variant=E,e.dataset.overflow=D;let P=document.createDocumentFragment(),I=f.isStreaming();x.forEach((_,j)=>{let te=Rh({item:_,index:j,surface:A,source:C,variant:E,streaming:I,config:z,plugins:Y,chipsConfig:h,session:f,getTextarea:()=>m,eventTarget:e,submitPrompt:b?.submitPrompt});P.appendChild(te),n.push(te),[...te instanceof HTMLButtonElement?[te]:[],...Array.from(te.querySelectorAll("button"))].forEach(X=>{t.includes(X)||(X.disabled=I,t.push(X))})}),e.appendChild(P),i(),l();let J=JSON.stringify({normalized:x,surface:A,variant:E,source:C});J!==o&&(o=J,aW(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:x.map(_=>({..._})),surface:A,source:C,variant:E},bubbles:!0,composed:!0})),S&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:x.map(_=>_.prompt)},bubbles:!0,composed:!0})))}}};var Eo={"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"};nr();Ge();ln();er();Ge();ln();Pa();var lW="persona-header-control",cW="persona-header-control--glyph",dW="persona-header-control--sparse",pW=20,uW={x:[1.4,1.05]},vM="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",fW="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ou=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=uW[t]??[1,1.5],l=!o;e.classList.toggle(cW,l),e.classList.toggle(dW,l&&s!==1);let c=parseFloat(o??"")||pW,d=We(t,`${Math.round(c*s)}px`,"currentColor",i);d?(d.style.display="block",l||(d.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(d)):r&&(e.textContent=r)},Na=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=vM,size:l,iconSize:c,color:d,backgroundColor:p,borderWidth:f,borderColor:m,borderRadius:g,paddingX:h,paddingY:b,hidden:C,extraClassName:A,attrs:S}=e,E=v("div",i),k=!!(f||m),D=F("button",{className:Jt(lW,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!k&&"persona-border-none",!g&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...S},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:d||lo.actionIconColor,backgroundColor:p,border:k?`${f||"0px"} solid ${m||"transparent"}`:void 0,borderRadius:g,paddingLeft:h,paddingRight:h,paddingTop:b,paddingBottom:b}});return r?Ou(D,r,{iconSize:c,iconText:s}):s&&(D.textContent=s),E.appendChild(D),$n({anchor:D,trigger:E,text:()=>D.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:D,wrapper:E}},Fa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=vM,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:d,wrapper:p}=Na({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:d,wrapper:p}},Va=(e,t={})=>{let{wrapperClassName:n=fW,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:d,wrapper:p}=Na({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:d,wrapper:p}};var lo={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)"},Wh={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)"},mW={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)"},Ii=e=>{let{config:t,showClose:n=!0}=e,o=F("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:lo.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??Ll,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,d=F("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(c){let D=parseFloat(s)||24,z=We(c,D*.6,"currentColor",1);z?(z.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,z.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren(z)):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let D=v("img");D.src=t.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,d.replaceChildren(D)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=F("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:lo.titleColor,...Wh}}),m=F("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:lo.subtitleColor,...mW}});p.append(f,m),l?o.append(p):o.append(d,p);let g=r.clearChat??{},h=g.enabled??!0,b=g.placement??"inline",C=null,A=null;if(h){let z=Va(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=z.button,A=z.wrapper,b==="top-right"&&(A.style.right="48px"),b==="inline"&&o.appendChild(A)}let S=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&b==="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:E,wrapper:k}=Fa(t,{showClose:n,wrapperClassName:S});return i!=="top-right"&&o.appendChild(k),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:m,closeButton:E,closeButtonWrapper:k,clearChatButton:C,clearChatButtonWrapper:A}},xc=(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))};Ge();Bh();Ri();Pu();var gW=e=>{let t=Ii({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 hW(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Na({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Lu(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 i=dc(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Sc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var yW=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=lo.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 c=r?.titleMenu,d,p;if(c){let k=wM({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:D=>{let z=T=>{T===!1&&k.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},Y=c.onSelect(D);Y instanceof Promise?Y.then(z,()=>{}):z(Y)},hover:c.hover,className:""});d=k.element,d.style.color=lo.titleColor,p=d.querySelector(".persona-combo-btn-label")??d}else{if(d=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=lo.titleColor,Object.assign(p.style,Wh),p.textContent=i.title??"Chat Assistant",d.appendChild(p),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let D=r.onTitleClick;d.addEventListener("click",z=>{z.target.closest("button")||D()}),d.addEventListener("keydown",z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),D())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:m,wrapper:g}=Fa(t,{showClose:n,wrapperClassName:f});o&&m.addEventListener("click",o);let h=v("div","persona-flex persona-items-center persona-gap-1");c||hW(h,r?.trailingActions,r?.onAction??s);let b=i.clearChat??{},C=null,A=null;if(b.enabled??!0){let k=b.placement??"inline",D=Va(t,{wrapperClassName:k==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});C=D.button,A=D.wrapper,k==="top-right"?A.style.right="48px":h.appendChild(A)}h.appendChild(g),l.appendChild(h);let S=v("div");S.style.display="none";let E=v("span");return E.style.display="none",{header:l,iconHolder:S,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:g,clearChatButton:C,clearChatButtonWrapper:A}},xM={default:gW,minimal:yW},bW=e=>xM[e]??xM.default,Fu=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=v("div");l.style.display="none";let c=v("span"),d=v("span"),p=v("button");p.style.display="none";let f=v("div");return f.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:d,closeButton:p,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=bW(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};Ge();Ws();var Ac=e=>{let{config:t}=e,n=F("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=Fp(),r=F("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:i}=Dp(t);i();let l=_p(t),c=Ia(t),d=Op(t),p=Np(t),f=F("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(f),d&&(d.previewsContainer.style.gap="8px",f.append(d.previewsContainer),r.append(d.input)),r.append(s);let m=F("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=F("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),h=F("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&g.append(d.wrapper),c&&h.append(c.wrapper),h.append(l.wrapper),m.append(g,h),r.append(m),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,p,r):n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,header:f,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:l.setMode}};Ge();var Vu=require("lucide");ao();Ws();Wp();var SM=()=>{let e=F("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=v("span","persona-pill-peek__icon"),n=Je(Vu.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Je(Vu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},$u=e=>{let{config:t}=e,n=F("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Fp(),r=Np(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Dp(t,{defaultMaxLines:5});i();let l=_p(t),c=Ia(t),d=Op(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let p=F("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),f=F("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&f.append(d.wrapper);let m=F("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&m.append(c.wrapper),m.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),d&&p.append(d.input),p.append(f,s,m);let g=F("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(g),d&&g.append(d.previewsContainer),n.append(o,p,r);let h=p;return{footer:n,suggestions:o,composerForm:p,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:h,leftActions:f,rightActions:m,setSendButtonMode:l.setMode}};Ge();ln();Ge();zg();Ri();ln();Rs();hc();var vW=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}},CW=(e,t)=>{if(!e)return null;let n=vW(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},wW=(e,t)=>{let n=v("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},xW=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},_h=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(":"))},Oh=320,kM=320,SW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),AW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),MW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),TW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),EW=e=>{if(!e||e.length===0)return null;let t=F("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=F("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=We(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(F("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},kW=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Zl(o.ref,{readonly:!0,render:t}))}return n},AM="\uE000",MM="\uE001",LW=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=m=>`${AM}${r}:${m}${MM}`,i=t.map((m,g)=>m.kind==="text"?m.text:s(g)).join(""),l=n(i);if(!t.every((m,g)=>m.kind==="text"||l.includes(s(g)))){e.replaceChildren(kW(t,o));return}e.innerHTML=l;let d=new RegExp(`${AM}${r}:(\\d+)${MM}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let m=p.nextNode();m;m=p.nextNode())f.push(m);for(let m of f){let g=m;for(let h=d.exec(g.data);h;h=d.exec(g.data)){let b=t[Number(h[1])],C=g.splitText(h.index);C.data=C.data.slice(h[0].length),b?.kind==="mention"&&C.parentNode?.insertBefore(Zl(b.ref,{readonly:!0,render:o}),C),g=C}}},PW=(e,t,n)=>{if(e.length===0)return null;try{let o=v("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,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let d=v("img");d.alt=l.alt?.trim()||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Oh}px`,d.style.maxHeight=`${kM}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,d.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),d.remove(),r===0&&i())}),d.addEventListener("load",()=>{p=!0}),xW(l.image)?(d.src=l.image,o.appendChild(d)):(p=!0,r=Math.max(0,r-1),d.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},IW=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!_h(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Oh}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},HW=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!_h(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Oh}px`,r.style.maxHeight=`${kM}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}},RW=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!_h(o.data))return;let r=v("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}},Mc=()=>{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},WW=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Mc};if(t){let r=t(o);if(r!==null)return r}return Mc()},BW=(e,t)=>{let n=v("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=v("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},TM=(e,t,n="div")=>{let o=v(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},Tc=(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},EM={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"}},DW=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=EM[n??"bubble"]??EM.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)`)},Uu="custom:",_W=e=>`${Uu}${e}`,LM=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),OW=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,d=(t.showEdit??!1)&&o?.canEdit===!0,p=(t.showQuote??!1)&&o?.canQuote!==!1,f=LM(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!d&&!p&&f.length===0){let E=v("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let m=t.visibility??"hover",g=t.align??"right",h=t.layout??"pill-inside",b={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[g],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[h],A=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${b} ${C} ${m==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let S=(E,k,D)=>{let z=Ln({icon:E,label:k,size:14,className:"persona-message-action-btn",chromeless:!0});return z.setAttribute("data-action",D),z};r&&A.appendChild(S("copy","Copy message","copy")),l&&A.appendChild(S("volume-2","Read aloud","read-aloud")),s&&A.appendChild(S("thumbs-up","Upvote","upvote")),i&&A.appendChild(S("thumbs-down","Downvote","downvote")),c&&A.appendChild(S("refresh-cw","Regenerate response","regenerate")),d&&A.appendChild(S("pencil","Edit message","edit")),p&&A.appendChild(S("quote","Quote message","quote"));for(let E of f)A.appendChild(S(E.iconName??"ellipsis",E.label,_W(E.id)));return A},Nh=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,d=i.timestamp,p=c?.show??!1,f=d?.show??!1,m=c?.position??"left",g=d?.position??"below",h=Tc(e.role,l),b=v("div",h.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=hh(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;DW(b,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(b.style.backgroundColor="transparent",b.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=SW(e),E=e.content?.trim()??"",D=S.length>0&&E===La,z=Bu(s?.widgetConfig?.features?.streamAnimation),Y=s?.widgetConfig?.features?.streamAnimation?.plugins,T=e.role==="assistant"&&z.type!=="none"?uc(z.type,Y):null,W=e.role==="assistant"&&T?.isAnimating?.(e)===!0,L=e.role==="assistant"&&T!==null&&(!!e.streaming||W);L&&T?.bubbleClass&&b.classList.add(T.bubbleClass);let w=document.createElement("div");w.classList.add("persona-message-content"),e.streaming&&w.classList.add("persona-content-streaming"),L&&T&&(T.containerClass&&w.classList.add(T.containerClass),w.style.setProperty("--persona-stream-step",`${z.speed}ms`),w.style.setProperty("--persona-stream-duration",`${z.duration}ms`));let x=L?Du(e.content??"",z.buffer,T,e,!!e.streaming):e.content??"",P=()=>{let re=t({text:x,message:e,streaming:!!e.streaming,raw:e.rawContent});return L&&T?.wrap==="char"?fc(re,"char",e.id,{skipTags:T.skipTags}):L&&T?.wrap==="word"?fc(re,"word",e.id,{skipTags:T.skipTags}):re},I=null;if(D?(I=document.createElement("div"),I.innerHTML=P(),I.style.display="none",w.appendChild(I)):e.contentSegments?.length?LW(w,e.contentSegments,re=>t({text:re,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):w.innerHTML=P(),L&&T?.useCaret&&!D&&E){let re=_u(),N=w.querySelectorAll(".persona-stream-char, .persona-stream-word"),ke=N[N.length-1];if(ke?.parentNode)ke.parentNode.insertBefore(re,ke.nextSibling);else{let ve=w.lastElementChild;ve?ve.appendChild(re):w.appendChild(re)}}if(f&&g==="inline"&&e.createdAt){let re=TM(e,d,"span");re.classList.add("persona-timestamp-inline");let N=w.lastElementChild;N?N.appendChild(re):w.appendChild(re)}if(S.length>0){let re=PW(S,!D&&!!E,()=>{D&&I&&(I.style.display="")});re?b.appendChild(re):D&&I&&(I.style.display="")}let J=AW(e);if(J.length>0){let re=IW(J);re&&b.appendChild(re)}let _=MW(e);if(_.length>0){let re=HW(_);re&&b.appendChild(re)}let j=TW(e);if(j.length>0){let re=RW(j);re&&b.appendChild(re)}let te=e.contentSegments?.length?null:EW(e.contextMentions);if(te&&b.appendChild(te),b.appendChild(w),f&&g==="below"&&e.createdAt){let re=TM(e,d);re.classList.add("persona-mt-1"),b.appendChild(re)}let K=e.role==="assistant"?CW(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let re=!!(x&&x.trim()),N=z.placeholder==="skeleton",ke=N&&z.buffer==="line"&&re;if(re)ke&&b.appendChild(mc());else if(N)b.appendChild(mc());else{let ve=WW("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ve&&b.appendChild(ve)}}K&&e.stopReason&&!e.streaming&&(E||(w.style.display="none"),b.appendChild(wW(e.stopReason,K)));let X=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,oe=s?.actionEligibility,de=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&oe?.canEdit===!0||o?.showQuote===!0&&oe?.canQuote===!0||LM(o,"user").length>0);if((X||de)&&o){let re=OW(e,de?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,oe);b.appendChild(re)}if(!p||e.role==="system")return b;let xe=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Te=BW(c,e.role);return m==="right"||m==="left"&&e.role==="user"?xe.append(b,Te):xe.append(Te,b),xe};var NW=40,FW=(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=We(t.name,NW);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(F("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(F("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},PM=(e,t,n={})=>{let o=F("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),i=v("p","persona-welcome-subtitle"),l=F("div",{className:"persona-welcome-head-text"},r,s),c=F("div",{className:"persona-welcome-title-row"},o,l);return{host:F("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)"}},c,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},$a=(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)},qu=(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==="",FW(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")},VW="data-persona-welcome-plugin",IM="data-persona-welcome-overlay",zu="persona-welcome-overlay-active",Fh=new WeakMap,Vh=(e,t,n)=>{n.setAttribute(VW,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(IM,""),e.classList.contains(zu)||(Fh.set(e,e.scrollTop),e.classList.add(zu),e.scrollTop=0)},$h=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(IM),e.classList.contains(zu)&&(e.classList.remove(zu),e.scrollTop=Fh.get(e)??e.scrollTop,Fh.delete(e))},HM=()=>{let e=F("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},ju=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=F("div",{className:Tc("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(F("div",{className:"persona-flex"},r)),e.hidden=!1},RM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,WM=(e,t)=>{if(RM()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let h=getComputedStyle(o);r=parseFloat(h.rowGap)||0;let b=e.previousElementSibling,C=e.nextElementSibling,S=o.getBoundingClientRect().top+(parseFloat(h.borderTopWidth)||0)+(parseFloat(h.paddingTop)||0)-o.scrollTop;s=Math.max(0,b?n.top-b.getBoundingClientRect().bottom-r:n.top-S),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),d=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,f=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${p}px`,marginTop:`${s}px`,marginBottom:`${i}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"}),m=!1,g=()=>{m||(m=!0,e.style.overflow=l,t(f))};return f.finished.then(g).catch(g),f},BM=(e,t,n,o=260)=>{if(t<=1||RM()||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 $W="Hello \u{1F44B}",UW="I can answer questions and help you get things done here.",DM=new WeakSet,co=(e,t)=>!!e&&e[t]!==void 0,zW=(e,t)=>{!e||e.debug!==!0||!t.length||DM.has(e)||(DM.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ku=(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"),i=co(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":co(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];co(n,"title")&&co(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),co(n,"subtitle")&&co(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),co(n,"variant")&&co(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&co(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&co(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=n?.anchor??(s==="centered"&&t?"center":"bottom"),p=cc(n?.anchorComposerTop)!==null;return co(n,"anchorComposerTop")&&!p&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),d!=="center"&&(co(n,"anchorComposerTop")||co(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),zW(e,c),{title:co(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":$W),kicker:n?.kicker??"",subtitle:co(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":UW),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:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:d,anchorComposerTop:p?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Tu}},_M=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ua=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");ha();var qW="var(--persona-components-panel-maxWidth)",OM="var(--persona-components-panel-height)",jW="var(--persona-components-panel-maxHeight)",Wi=e=>{let t=Ur(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${OM})`:`max(200px, calc(${OM} - ${o}px))`;return{width:n??SC,maxWidth:n??qW,height:r,maxHeight:jW}},NM="16px",zh="10px",qh="14px",FM=e=>{let t=e?.launcher?.enabled??!0,n=un(e);if(Cc(e)){let d=e?.launcher?.composerBar??{},p=v("div","persona-widget-wrapper persona-fixed persona-transition");p.setAttribute("data-persona-composer-bar",""),p.dataset.state="collapsed",p.dataset.expandedSize=d.expandedSize??"anchored",p.style.zIndex=String(e?.launcher?.zIndex??Jn);let f=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");f.style.width="100%",p.appendChild(f);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=d.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Jn),{wrapper:p,panel:f,pillRoot:m}}if(n){let d=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(p),{wrapper:d,panel:p}}if(!t){let d=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),p=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),f=Ur(e),g=f.launcherWidth||f.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Wi(e).width:"100%";return d.style.width=g,p.style.width="100%",d.appendChild(p),{wrapper:d,panel:p}}let r=e?.launcher??{},s=r.position&&Eo[r.position]?Eo[r.position]:Eo["bottom-right"],i=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Jn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Wi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},jh=e=>{let t=F("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ih(e)}});return t.hidden=!0,t},VM=(e,t)=>{let n=jh("starter"),o=PM(e,n,{flatShadow:un(e)}),r=Ku(e);qu(o,r),$a(t,o.host,Ua(r,e?.initialMessages));let s=HM();return ju(s,r.message,e),{welcome:o,greetingHost:s}},KW=(e,t)=>{let n=v("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}=Fa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:NM,iconSize:zh});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let Y=Va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:NM,iconSize:qh});i=Y.button,l=Y.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=F("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=F("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"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:f}=VM(e,d),{host:m,title:g,subtitle:h}=p,b=p.starterSuggestions,C=v("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=jh("followUp"),S=Os(e,!0);S&&(C.style.maxWidth=S,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),d.append(m,f,C,A);let E=F("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"}}),k=$u({config:e}),{root:D,textNode:z}=SM();return n.append(c,r,d,E),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:C,starterSuggestions:b,transcriptSuggestions:A,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,welcomeHost:m,welcomeIconHolder:p.iconHolder,greetingHost:f,introKicker:p.kicker,introTitle:g,introSubtitle:h,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:c,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:D,peekTextNode:z}},$M=(e,t=!0)=>{if(Cc(e))return KW(e,t);let n=F("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?Fu(e,o,{showClose:t}):Ii({config:e,showClose:t}),i=F("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=VM(e,i),{host:d,title:p,subtitle:f}=l,m=l.starterSuggestions,g=v("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let h=jh("followUp"),b=Os(e,!1);b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),i.append(d,c,g,h);let C=Ac({config:e}),A=e?.layout?.showFooter!==!1;r?xc(n,s,e):(s.header.style.display="none",xc(n,s,e)),n.append(i);let S=F("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 A||(C.footer.style.display="none"),n.append(C.footer),n.append(S),{container:n,body:i,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:h,composerOverlay:S,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:p,introSubtitle:f,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};Ws();Ge();ln();nr();var Kh=(e,t)=>{let n=v("button");n.type="button",n.innerHTML=`
1175
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let d=[];s&&d.push(vr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(c){let d=[];i&&d.push(vr(i)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=i);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.#O&&!n?.voiceTurn&&(this.#O.failed=!0,this.#O=null),(this.#I||this.#x||this.#v||this.#W)&&await this.#Fe(),this.stopSpeaking(),this.abortController?.abort(),this.#ye(),this.#me++,this.#ve();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(g=>g.id===s&&g.role==="user"):void 0,l=i?.id??Cp(),c=Ea();this.#a=null;let d=n?.contentParts&&xp(n.contentParts)?La:"",p={id:l,role:"user",content:o||d,createdAt:new Date().toISOString(),sequence:this.#Q(),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??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#le(p),this.#H(!0);let f=new AbortController;if(this.abortController=f,n?.mentions){let g=this.messages.find(h=>h.id===l)??p;if(await this.#Qe(g,o,n.mentions.finalize),f.signal.aborted||this.abortController!==f)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let g=this.messages.find(b=>b.id===l)??p,h=mS({quote:n.quote,text:g.llmContent??g.content,contentParts:g.contentParts});h.contentParts&&(g.contentParts=h.contentParts),h.llmContent!==void 0&&(g.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(g.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let m=i?[...this.messages.filter(g=>g!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(m,f,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt,voiceSpoken:!!n?.voiceTurn})}catch(g){if(this.status==="resuming"||this.#r)return;this.#O&&(this.#O.failed=!0);let h=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));if(!h){let b=ah(g,this.config.errorMessage);if(b){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.#Q()};this.#le(C)}}this.#Z("idle"),this.#H(!1),this.abortController=null,h||(g instanceof Error?this.callbacks.onError?.(g):this.callbacks.onError?.(new Error(String(g))))}}resubmitFrom(t,n){let o=gS(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let d=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.#Je(s.options):r.composerOptions,f=s?s.contentSegments:r.contentSegments,m=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...f?.length?{contentSegments:[...f]}:{},...p?{composerOptions:p}:{},...m?{quote:m}:{},...d&&Object.keys(d).length>0?{replayFields:d}:{},viaVoice:g===!0}),!0}#Je(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.#I||this.#x||this.#v||this.#W)&&await this.#Fe(),this.abortController?.abort(),this.#ve();let t=Ea();this.#a=null,this.#H(!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.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=ah(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#Q()};this.#le(l)}}this.#Z("idle"),this.#H(!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.#a=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#H(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#t;this.#t=s;try{this.handleEvent(i)}finally{this.#t=l}},n?.assistantMessageId,n?.seedContent),this.#Be(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#Be(s),this.#Z("error"),this.webMcpResolveControllers.size===0&&(this.#H(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#Ve(){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.#l}`,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")}#Ze;#me;#Le(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#H(s),appendMessage:s=>this.#le(s),nextSequence:()=>this.#Q(),settleApprovalPausedToolCall:s=>this.#ze(s),resumeAfter:s=>this.#o?.executionId===s?this.#o.lastEventId:void 0},o=fS();if(o)return t(o,n);let r=this.#me;return Kg().then(s=>r===this.#me?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#Le((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Le((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Le((n,o)=>n.resolveWebMcpToolCall(o,t))}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}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#p;queueMicrotask(()=>{s===this.#p&&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))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#p;queueMicrotask(()=>{if(t===this.#p)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(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.#Le((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#ye(){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.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#H(!1),this.#Z("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.messages=[],this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H(!1),this.#Z("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#f}selectArtifact(t){this.#f=t,this.#be()}clearArtifacts(){this.#Re()}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.#f=n,this.#be(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=ks(this.config.features?.artifacts,t),r=Il(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(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#$e(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ks(this.config.features?.artifacts,n),s=Il(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])}#Re(){this.artifacts.size===0&&this.#f===null||(this.artifacts.clear(),this.#f=null,this.#be())}#be(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#f})}#rt(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.#f=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.#be()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ve(),this.#ye(),this.#me++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ge(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#Q()}))),this.#H(!1),this.#Z("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.#f=n,this.#be()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#a||this.agentExecution?.status!=="running")return;let o=this.#o===null;this.#o={executionId:n,lastEventId:t,assistantMessageId:this.#a,status:"running"},this.#dt(o)}#it(){return this.#o!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ue()}#Ue(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#We(){this.#r||!this.#o||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#o}),this.#H(!0),this.#Z("resuming"),this.#at().then(t=>{this.#r&&this.#o&&t.begin()}))}#at(){return this.#s?Promise.resolve(this.#s):(this.#g||(this.#g=GS().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#s=n,n}),this.#g.catch(()=>{this.#g=null})),this.#g)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#o,clearResumable:()=>t.#Pe(),getStatus:()=>t.status,setStatus:n=>t.#Z(n),setStreaming:n=>t.#H(n),setReconnecting:n=>{t.#r=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.#le(n),nextSequence:()=>t.#Q(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>ah(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#s?.wake();return}this.#We()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=Ea(),this.#le({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#Q()})),this.#a=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#o={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#We()}#ct(){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}#ve(){this.#r=!1,this.#s?.teardown(),this.#Pe()}#Pe(){this.#c&&(clearTimeout(this.#c),this.#c=null);let t=this.#o!==null;this.#o=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#o);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#o)},500))}}getResumableHandle(){return this.#o}#Z(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#H(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#Be(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=sh(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Xg(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=sh(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()}#Be(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#ze(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#ze(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#le(t){let n=this.#Me(t);this.messages=this.#ge([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#Me(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#le(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let f=r.approval,m=n.approval;i.approval={...f,...m,executionId:m.executionId||f.executionId,toolName:m.toolName||f.toolName,description:m.description||f.description,toolType:m.toolType??f.toolType,reason:m.reason??f.reason,parameters:m.parameters??f.parameters,toolCallId:m.toolCallId??f.toolCallId}}let c=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(c&&YS(c)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let f=`${d}:${p}`,m=this.webMcpInflightKeys.has(f),g=this.webMcpResolvedKeys.has(f),h=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&YS(h)&&r.toolCall?.status==="complete";(m||g||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#ge(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#Me(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#Q()}}#Q(){return this.#n++}#ge(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 i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Ge();var Vo=require("lucide");ao();ln();Rs();var BH={add:e=>nx(e)},DH=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,yu={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function _H(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function OH(e){return e==="application/pdf"?Vo.FileText:e.startsWith("text/")?Vo.FileText:e.includes("word")?Vo.FileText:e.includes("excel")||e.includes("spreadsheet")?Vo.FileSpreadsheet:e==="application/json"?Vo.FileCode:Vo.File}var rc=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#n=!1;this.config={allowedTypes:t.allowedTypes??yu.allowedTypes,maxFileSize:t.maxFileSize??yu.maxFileSize,maxFiles:t.maxFiles??yu.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#t;#n;#o(){return typeof this.config.adapter?.add=="function"}#a(){return this.#o()?this.config.adapter:BH}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#f(n)}this.#i()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:yu.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.#n)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=ox(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:_H(),file:o,previewUrl:Sp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#o()?"uploading":"processing",progress:this.#o()?0:void 0};this.attachments.push(s),this.#f(s),n.push(s)}this.#i(),this.#c(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#t.set(t.id,n);let o=()=>this.#n||n.signal.aborted||this.#t.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#a().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=DH(s),this.#p(t),this.#c())}});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.#t.get(t.id)===n&&this.#t.delete(t.id)}this.#p(t),this.#c()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#n||(n.status=this.#o()?"uploading":"processing",n.progress=this.#o()?0:void 0,n.error=void 0,this.#p(n),this.#c(),this.#r(n))}#s(t){let n=this.#t.get(t);n&&(this.#t.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.#s(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#g(o.contentPart),this.#i(),this.#c()}#g(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.#s(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#i(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let t of this.#t.values())t.abort();this.#t.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#f(t){if(!this.#e)return;let n=Sp(t.file),o=v("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=v("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=v("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 f=OH(t.file.type),m=Je(f,20,"var(--persona-muted, #6b7280)",1.5);m&&p.appendChild(m);let g=v("span");g.textContent=rx(t.file.type,t.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",p.appendChild(g),o.appendChild(p)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let i=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=We("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let d=Je(Vo.X,10,"var(--persona-text-inverse, #ffffff)",2);d?c.appendChild(d):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#l(o,t)}#p(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#l(n,t)}#l(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)}%`:""}}#i(){this.#e&&(this.#e.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 XS=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),NH=(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 QS(){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",i=()=>{let p=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(f=>Object.freeze({...f}))),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=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let p=l();for(let f of[...t])try{f(p)}catch(m){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",m)}},d=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,d())},setAttachments:p=>{NH(e.attachments,p)||(e.attachments=[...p],d())},setMentionRefs:p=>{XS(e.mentionRefs,p)||(e.mentionRefs=[...p],d())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,d())},setActiveModeIds:p=>{XS(e.activeModeIds,p)||(e.activeModeIds=[...p],d())},setQuote:p=>{let f=e.quote;f?.text===p?.text&&f?.messageId===p?.messageId&&f?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,d())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,d())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,d())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,d())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,d())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,d())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Ge();var wo=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},JS=(e,t)=>{let n=v("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function ZS(e,t={}){let n=wo(e,"[data-persona-composer-form]"),o=wo(e,"[data-persona-composer-input]");if(!n||!o){let A=`[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(A);return typeof console<"u"&&console.warn(A),null}let r={header:wo(e,"[data-persona-composer-header]"),body:wo(e,"[data-persona-composer-body]"),actionsStart:wo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:wo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:wo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:wo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:wo(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=JS("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,S,E,k)=>{if(A)return A;s.add(C);let D=JS(S,E);return k.appendChild(D),D},d=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),f=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),m=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),g=[],h=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,b=wo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:d,actionsEnd:p,suggestions:f,status:m,attachmentInput:b,attachmentPreviews:wo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:wo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:wo(e,"[data-persona-composer-submit]")??void 0,micButton:wo(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,S,E)=>{C.addEventListener(A,S,E),g.push({target:C,type:A,handler:S,options:E})},removeListener:(C,A,S,E)=>{C.removeEventListener(A,S,E),g=g.filter(k=>!h(k,{target:C,type:A,handler:S}))},destroy:()=>{for(let C of g)C.target.removeEventListener(C.type,C.handler,C.options);g=[]}}}Ge();ln();Pa();Ws();Ra();Ge();ln();Ws();var FH='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',VH=["--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"],lh="data-persona-menu-focus",$H=new Set(["ArrowDown","ArrowUp","Home","End"]);function eA(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(FH)??e}var UH=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function tA(e){let t=e.label,n=!1,o=v("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Mo} ${rr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{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 J=We("plus",Co,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],d=-1,p=!1,f=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},m=()=>{let I=f();for(let J of c){let _=!!I&&eA(J)===I;J.toggleAttribute(lh,_&&p)}},g=()=>c.filter(I=>I.isConnected||s.contains(I)).map(eA).filter(I=>!UH(I)),h=(I,J)=>{I.forEach((_,j)=>{_.setAttribute("tabindex",j===J?"0":"-1")})},b=I=>{let J=g();if(J.length===0)return;let _=(I%J.length+J.length)%J.length;d=_,h(J,_),J[_].focus(),m()},C=()=>o.ownerDocument??document,A=null,S=null,E=null,k=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},D=()=>{S&&(s.removeEventListener("focusin",S),S=null),E&&(s.removeEventListener("pointerdown",E,!0),E=null)},z=null,Y=()=>(z||(z=Bs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),k()}})),z),T=()=>z?.isOpen===!0,W=(I=!1)=>{if(T()){z?.close(),r.setAttribute("aria-expanded","false"),k(),D(),d=-1,p=!1;for(let J of c)J.removeAttribute(lh);I&&r.focus()}},L=(I=0,J=!1)=>{if(n||T())return;p=J,Bp(r,s,VH),Y().open(),r.setAttribute("aria-expanded","true");let _=g();h(_,-1),b(I<0?_.length-1:I),A=j=>{let te=typeof j.composedPath=="function"?j.composedPath():[];te.includes(s)||te.includes(o)||W()},C().addEventListener("focusin",A,!0),S=()=>m(),s.addEventListener("focusin",S),E=()=>{p=!1},s.addEventListener("pointerdown",E,!0)},w=I=>{I.preventDefault(),I.stopPropagation(),T()?W(!0):L(0)},x=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),p=!0,T()?b(0):L(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),p=!0,T()?b(-1):L(-1,!0))},P=I=>{switch($H.has(I.key)&&(p=!0),I.key){case"ArrowDown":I.preventDefault(),b(d+1);return;case"ArrowUp":I.preventDefault(),b(d-1);return;case"Home":I.preventDefault(),b(0);return;case"End":I.preventDefault(),b(g().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),W(!0);return;case"Tab":W(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",x),s.addEventListener("keydown",P),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let _ of c)I.includes(_)||_.removeAttribute(lh);if(c=[...I],!T())return;let J=g();h(J,Math.min(d,J.length-1)),m()},isOpen:T,open:()=>L(0),close:W,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:i,destroy:()=>{n=!0,k(),D(),r.removeEventListener("click",w),r.removeEventListener("keydown",x),s.removeEventListener("keydown",P),z?.destroy(),z=null,o.remove(),s.remove(),c=[]}}}var wr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},nA="data-persona-composer-action",ch="data-persona-composer-disable-when-streaming",zH="core:overflow",qH=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function jH(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=v("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 dh(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 oA=(e,t)=>{!e||typeof console>"u"||console.warn(t)},KH=(e,t)=>t.includes(":")?t:`${e}:${t}`;function GH(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){oA(t,`[Persona] composer action "${l.id}" is already contributed by ${rA(c)}; the ${rA(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 i=(l,c,d)=>{let p=d?KH(d,l.id):l.id,f=l.order??wr.custom;l.placement==="end"&&f>=wr.send&&(oA(t,`[Persona] composer action "${p}" ordered at ${f} would render after send; clamped to ${wr.send-1}.`),f=wr.send-1),s({id:p,placement:l.placement,presentation:l.presentation??"bar",order:f,sequence:r++,source:c,pluginId:d,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(d){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,d);continue}for(let d of c??[])i(d,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var rA=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",sA=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,YH=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function XH(e,t){if(!e||e==="always")return!0;let n=YH(t);return e==="when-text"?n:!n}var _s=e=>e.kind==="custom",ph=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,QH=e=>{let t=ph(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},JH='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function ZH(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(JH)||o.childNodes.forEach(n)};return n(e),t.trim()}var eR=e=>ZH(e).length===0;function iA(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(w,x)=>{let P=w.button;if(!P)return;P.setAttribute("role","menuitem"),P.setAttribute("tabindex","-1"),P.className="persona-composer-overflow-menu__item";for(let _ of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])P.style[_]="";P.style.lineHeight="1",x.tooltipText?P.setAttribute("title",x.tooltipText):P.removeAttribute("title"),P.replaceChildren();let I=v("span","persona-composer-overflow-menu__icon");if(x.iconName){let _=We(x.iconName,16,"currentColor",1.5);_&&I.appendChild(_)}let J=v("span","persona-composer-overflow-menu__label");J.textContent=x.shortLabel??x.label,P.append(I,J)},i=(w,x)=>{let P=w.button;if(!P)return;if(P.setAttribute("aria-label",x.label),x.pressed===void 0?P.removeAttribute("aria-pressed"):P.setAttribute("aria-pressed",x.pressed?"true":"false"),P.toggleAttribute(ch,x.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,x);return}P.removeAttribute("role"),P.removeAttribute("tabindex"),P.removeAttribute("title");let I=r(),J=!!x.shortLabel;if(P.className=Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Mo,rr,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),P.style.width=I&&!J?I:"",P.style.height=I??"",P.style.minWidth=I&&!J?I:"",P.style.minHeight=I??"",P.style.fontSize=J?"":"18px",P.style.lineHeight="1",P.style.color=x.iconColor??"",P.style.backgroundColor=x.backgroundColor??"",P.replaceChildren(),x.iconName){let _=We(x.iconName,Co,"currentColor",1.5);_&&P.appendChild(_)}if(J){let _=v("span","persona-composer-action-button__label");_.textContent=x.shortLabel,P.appendChild(_)}else P.firstChild||(P.textContent=x.label);w.tooltip?.destroy(),w.tooltip=$n({anchor:P,trigger:w.element,text:()=>x.tooltipText??x.label,enabled:!!x.tooltipText})},l=(w,x)=>{let P=w.action,I=F("button",{attrs:{type:"button"}}),J=I;if(x==="bar"){let te=v("div","persona-send-button-wrapper");te.appendChild(I),J=te}J.setAttribute(nA,w.id);let _={resolved:w,element:J,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:x},j=te=>{if(te.preventDefault(),te.stopPropagation(),_.busy||I.disabled)return;let K=_.resolved.action;_.mode==="menu"&&g?.close(!0);let X;try{X=K.onSelect(e.actionContext,te)}catch(oe){e.reportError(oe,{actionId:_.resolved.id});return}!X||typeof X.then!="function"||(_.busy=!0,I.setAttribute("aria-busy","true"),X.catch(oe=>{e.reportError(oe,{actionId:_.resolved.id})}).finally(()=>{_.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",j),_.detach=()=>I.removeEventListener("click",j),i(_,P),_},c=w=>{let x=w.action,P;try{P=x.render({...e.actionContext,id:w.id,action:x})}catch(I){return e.reportError(I,{actionId:w.id}),null}return P?.element?(P.element.setAttribute(nA,w.id),P.element.toggleAttribute(ch,x.disableWhenStreaming===!0),{resolved:w,element:P.element,owned:!0,managed:!0,destroy:P.destroy,busy:!1,visible:!0,mode:"bar"}):null},d=(w,x)=>{if(w.builtIn){let I=w.builtIn.element;return I?{resolved:w,element:I,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let P=w.action;return P?_s(P)?c(w):l(w,x):null},p=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(x){e.reportError(x,{actionId:w.resolved.id})}w.element.remove()}},f=(w,x)=>{for(let P=0;P<x.length;P++){let I=x[P];if(!I.managed)continue;let J=null;for(let _=P+1;_<x.length;_++){let j=x[_];if(!j.managed&&j.element.parentElement===w){J=j.element;break}}J?(I.element.parentElement!==w||I.element.nextSibling!==J)&&w.insertBefore(I.element,J):w.lastChild!==I.element&&w.appendChild(I.element)}},m=(w,x)=>{if(w.button){w.button.disabled=x;return}if(!w.owned)return;let P=w.element;P.toggleAttribute("data-disabled",x),P.setAttribute("aria-disabled",x?"true":"false");let I=P instanceof HTMLButtonElement||P instanceof HTMLSelectElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement?P:P.querySelector("button, select, input, textarea");I&&(I.disabled=x)},g=null,h=null,b=null,C=0,A=()=>{let w=e.getOverflow?.();return w?.enabled===!0?w:void 0},S=()=>(g?g.setLabel(e.getOverflowLabel?.()??"More actions"):g=tA({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),E=w=>{h!==w&&(b?.disconnect(),h=w,C=dh(w),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(x=>{let I=x[x.length-1]?.contentRect?.width??dh(w);I!==C&&(C=I,W())}),b.observe(w)))},k=(w,x)=>{let P=jH(w.collapseAutoActionsBelow,x);if(P===null)return!1;let I=C||dh(x);return I>0&&I<P},D=(w,x,P)=>{if(!x)return"bar";if(w.resolved.builtIn){let J=qH(w.resolved.id);return J&&x.includeBuiltIns?.includes(J)?"menu":"bar"}let I=w.resolved.presentation;return I==="overflow"||I==="auto"&&P?"menu":"bar"},z=w=>{let x=w.menuSlot;if(!x)return;if(!eR(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let P=QH(w.element);if(!P){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==P&&(w.menuLabel.textContent=P),w.menuLabel.parentElement!==x&&x.appendChild(w.menuLabel)},Y=(w,x)=>{if(w.mode===x)return w;let P=w.resolved.action;if(P&&!_s(P)){p(w),t.delete(w.resolved.id);let I=l(w.resolved,x);return t.set(w.resolved.id,I),I}if(x==="menu"){let I=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[wg]:""}});I.appendChild(w.element),vx(ph(w.element)),w.menuSlot=I;let J=_=>{let j=ph(w.element);if(j.disabled)return;let te=_.target===j||j.contains(_.target);g?.close(!0),te||j.click()};I.addEventListener("click",J,!0),w.detachMenuSlot=()=>I.removeEventListener("click",J,!0),w.managed=!0,z(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=x,w},T=(w,x)=>{let P=x.map(I=>I.menuSlot??I.element);for(P.forEach((I,J)=>{let _=w.children[J];_!==I&&(_?w.insertBefore(I,_):w.appendChild(I))});w.children.length>P.length;)w.lastElementChild?.remove()},W=()=>{if(o)return;let w=e.getBindings();if(!w)return;let x=e.getState(),P=x.phase==="streaming",I=A();I&&E(w.footer);let J=I?k(I,w.footer):!1,_={start:[],end:[]},j=[];for(let te of n){let K=t.get(te.id);if(!K)continue;let X=te.action,oe=X?sA(X.visible,x,!0)&&XH(X.visibility,x):!0;if(K.visible!==oe&&(K.visible=oe,!oe&&K.managed&&(K.menuSlot??K.element).remove()),!!oe){if(K=Y(K,D(K,I,J)),X){let de=sA(X.disabled,x,!1)||X.disableWhenStreaming===!0&&P;m(K,de),!_s(X)&&X.pressed!==void 0&&K.button?.setAttribute("aria-pressed",X.pressed?"true":"false")}K.mode==="menu"?(z(K),j.push(K)):_[te.placement].push(K)}}if(j.length>0){let te=S();T(te.panel,j),te.setItems(j.map(de=>de.menuSlot??de.element)),te.applyButtonSize();let K=Number.isFinite(I?.order)?I?.order:wr.overflow,X=_.start.findIndex(de=>de.resolved.order>K),oe={resolved:{id:zH,placement:"start",presentation:"bar",order:K,sequence:-1,source:"core"},element:te.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};_.start.splice(X<0?_.start.length:X,0,oe)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));f(w.actionsStart,_.start),f(w.actionsEnd,_.end)};return{resolve:()=>{if(o)return;let w=GH(e.collect()),x=new Set(w.map(P=>P.id));for(let[P,I]of t)x.has(P)||(p(I),t.delete(P));for(let P of w){let I=t.get(P.id);if(!I){let te=d(P,"bar");te&&t.set(P.id,te);continue}let J=I.resolved.action,_=P.action;if(!!J!=!!_||J&&_&&_s(J)!==_s(_)||J&&_&&_s(J)&&_s(_)&&J.render!==_.render){p(I),t.delete(P.id);let te=d(P,I.mode);te&&t.set(P.id,te);continue}I.resolved=P,P.builtIn?(I.managed=P.builtIn.managed===!0||I.mode==="menu",P.builtIn.element&&I.mode==="bar"&&(I.element=P.builtIn.element)):_&&!_s(_)?i(I,_):_&&I.element.toggleAttribute(ch,_.disableWhenStreaming===!0)}n=w,W()},sync:W,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,b?.disconnect(),b=null,h=null;for(let w of t.values())p(w);t.clear(),g?.destroy(),g=null,n=[]}}}}Ra();Ge();ln();Ws();var tR="core:model",nR=700,aA=16,oR=["--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"],lA=()=>{let e=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function cA(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let d=e.getSelectedModelId();return c.find(p=>p.id===d)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),d="",p=()=>{let b=e.getModels(),C=b.map(A=>`${A.id}:${A.label}`).join("|");C!==d&&(d=C,c.replaceChildren(...b.map(A=>{let S=F("option",{attrs:{value:A.id}});return S.textContent=A.label,S}))),c.value=r(b)?.id??""};p(),o=p;let f=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",f);let m=b=>b.stopPropagation();c.addEventListener("click",m);let{wrapper:g,chevron:h}=lA();return g.append(c,h),{element:g,destroy:()=>{o===p&&(o=null),c.removeEventListener("change",f),c.removeEventListener("click",m)}}},i=()=>{let c=F("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"}}),d=v("span","persona-composer-model-picker-label"),p=v("span","persona-composer-model-picker-suffix");c.append(d,p);let f=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),m=new Map,g="",h=null,b=()=>h?.isOpen===!0,C=(x=!1)=>{b()&&(h?.close(),c.setAttribute("aria-expanded","false"),x&&c.focus())},A=x=>{let P=[...m.values()];if(P.length===0)return;let I=(x%P.length+P.length)%P.length;P[I].focus()},S=x=>{if(b())return;h||(h=Bs({anchor:c,content:f,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Bp(c,f,oR),h.open(),c.setAttribute("aria-expanded","true");let I=[...m.keys()].indexOf(r(e.getModels())?.id??"");A(x??(I>=0?I:0))},E=x=>{C(!0),e.onSelect(x)},k=x=>{x.preventDefault(),x.stopPropagation();let P=x.currentTarget.getAttribute("data-persona-model-option");P&&E(P)},D=x=>{let P=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":x.id}});if(x.icon){let te=We(x.icon,aA,"currentColor",1.5);if(te){let K=v("span","persona-composer-model-option-icon");K.appendChild(te),P.appendChild(K)}}let I=v("span","persona-composer-model-option-body"),J=v("span","persona-composer-model-option-label");if(J.textContent=x.label,I.appendChild(J),x.description){let te=v("span","persona-composer-model-option-description");te.textContent=x.description,I.appendChild(te)}P.appendChild(I);let _=v("span","persona-composer-model-option-check");_.setAttribute("aria-hidden","true");let j=We("check",aA,"currentColor",2);return j&&_.appendChild(j),P.appendChild(_),P.addEventListener("click",k),P},z=()=>{let x=e.getModels(),P=x.map(_=>`${_.id}:${_.label}:${_.icon??""}:${_.description??""}`).join("|");if(P!==g){g=P;for(let _ of m.values())_.removeEventListener("click",k);m.clear(),f.replaceChildren(...x.map(_=>{let j=D(_);return m.set(_.id,j),j}))}let I=r(x);for(let[_,j]of m)j.setAttribute("aria-selected",String(_===I?.id));d.textContent=I?.label??"";let J=e.getSuffix?.()??"";p.textContent=J,c.setAttribute("aria-label",[t,[I?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};z(),o=z;let Y=x=>{x.preventDefault(),x.stopPropagation(),b()?C(!0):S()},T=x=>{if(x.key==="ArrowDown"){x.preventDefault(),b()?A(0):S(0);return}x.key==="ArrowUp"&&(x.preventDefault(),b()?A(-1):S(-1))},W=x=>{let P=[...m.values()],I=P.indexOf(x.target?.closest?.(".persona-composer-model-option"));switch(x.key){case"ArrowDown":x.preventDefault(),A(I+1);return;case"ArrowUp":x.preventDefault(),A(I-1);return;case"Home":x.preventDefault(),A(0);return;case"End":x.preventDefault(),A(P.length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",Y),c.addEventListener("keydown",T),f.addEventListener("keydown",W);let{wrapper:L,chevron:w}=lA();return L.append(c,w),{element:L,destroy:()=>{o===z&&(o=null),c.removeEventListener("click",Y),c.removeEventListener("keydown",T),f.removeEventListener("keydown",W);for(let x of m.values())x.removeEventListener("click",k);m.clear(),h?.destroy(),h=null,f.remove()}}};return{action:{id:tR,kind:"custom",placement:"end",order:nR,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ge();ln();zp();var rR=":scope > [data-persona-composer-mode]";function dA(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=d=>{let p=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":d.id}});if(d.iconName){let h=v("span","persona-mention-chip-icon"),b=We(d.iconName,12,"currentColor",1.5);b&&h.appendChild(b),p.appendChild(h)}let f=v("span","persona-mention-chip-label");f.textContent=d.shortLabel??d.label,p.appendChild(f);let m=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${d.label}`}}),g=We("x",12,"currentColor",2);return g?m.appendChild(g):m.textContent="\xD7",m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),e.onRemove(d.id)}),p.appendChild(m),p},i=()=>Array.from(t.querySelectorAll(rR)),l=d=>{d.setAttribute("data-persona-chip-exit",""),d.setAttribute("aria-hidden","true"),d.style.pointerEvents="none";let p=()=>{d.remove(),Ha(t)},f=t.ownerDocument.defaultView,m=typeof f?.getComputedStyle=="function"?f.getComputedStyle(d).animationName:"";if(!m||m==="none"){p();return}d.addEventListener("animationend",p,{once:!0}),d.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let d of i())d.remove()};return{element:t,render:(d,p)=>{if(o)return;let f=p.filter(b=>d.includes(b.id)),m=f.map(b=>`${b.id}:${b.shortLabel??b.label}`).join("|");if(m===n)return;n=m;let g=new Map;for(let b of i()){let C=b.getAttribute("data-persona-composer-mode");C&&f.some(S=>S.id===C)&&!b.hasAttribute("data-persona-chip-exit")?g.set(C,b):b.hasAttribute("data-persona-chip-exit")||l(b)}let h=t.firstChild;for(let b of f){let C=g.get(b.id);C||(C=s(b),r.has(b.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(b.id),C!==h&&t.insertBefore(C,h),h=C.nextSibling}Ha(t)},destroy:()=>{o=!0,c(),Ha(t)}}}Ge();ln();var pA=e=>`core:mode:${e}`;var uh=e=>Math.min(300+e,499),uA=e=>`core:mode-group:${e}`;function bu(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function sR(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function fA(e,t){return e?.length?e.filter(n=>!bu(n.groupId,t)&&!sR(n.groupId,t)):[]}var iR=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function mA(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(iR(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function vu(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function gA(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function hA(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var aR=16;function yA(e){let t=null;return{action:{id:uA(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=d=>{d.preventDefault(),d.stopPropagation();let f=d.currentTarget.getAttribute("data-persona-composer-mode");!f||e.getActiveIds().includes(f)&&e.getGroup()?.selection==="single"||e.onSelect(f)},l=d=>{let p=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":d.id,"aria-label":d.label}});if(d.iconName){let m=We(d.iconName,aR,"currentColor",1.5);m&&p.appendChild(m)}let f=v("span","persona-composer-segmented-label");return f.textContent=d.shortLabel??d.label,p.appendChild(f),p.addEventListener("click",i),p},c=()=>{let d=e.getGroup();d?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",d.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let p=e.getModes(),f=p.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(f!==s){s=f;for(let h of r.values())h.removeEventListener("click",i);r.clear();let g=p.map(h=>{let b=l(h);return r.set(h.id,b),b});o.replaceChildren(...g)}let m=e.getActiveIds();for(let[g,h]of r)h.setAttribute("aria-pressed",String(m.includes(g)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let d of r.values())d.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}zp();Ge();ln();function bA(e){let t=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let f=v("div","persona-composer-quote-source");f.textContent=s.sourceLabel,l.appendChild(f)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=lu(s.text),l.appendChild(c);let d=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=We("x",12,"currentColor",2);p?d.appendChild(p):d.textContent="\xD7",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,d)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Ge();ln();function vA(e){let t=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,d)=>{let p=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),f=We(i,12,"currentColor",2);return f?p.appendChild(f):p.textContent=l,p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),d()}),p},s=i=>{let l=lu(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=F("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,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()}}}Ge();function CA(e){let t=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=F("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=v("div","persona-message-edit-actions"),s=(l,c,d,p)=>{let f=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[d]:""},text:l});return f.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),p()}),f},i=()=>{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",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),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 wA(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 xA(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),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}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function SA(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 AA(e){return e.wrapped||e.text.includes(`
1176
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function MA(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function TA(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 i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}Jp();Wp();function fh(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 kA(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var lR=e=>typeof e?.then=="function";function EA(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 LA(e,t,n){let o;try{o=e(fh(t),{signal:n})}catch(r){return{status:"error",error:r}}return lR(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:EA(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):EA(t,o)}Wg();Ug();Eg();Rs();var Cu=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),wu={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"};er();er();var Su="16px",Au="transparent",cR=(()=>{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})(),sc={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:cR,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"}},xu={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"}},To={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:Um,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Su,canvasBackground:Au,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"}}},dR=sc.colors.gray,pR={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},uR={...sc,colors:{...sc.colors,gray:dR}},fR={...sc,colors:{...sc.colors,gray:pR},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var mR=xu,gR={...xu,colors:{...xu.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...xu.typography,fontSize:"14px",lineHeight:"1.5"}};var gh=To,hR={...To,launcher:wu,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:{...To.input,borderRadius:"palette.radius.full"},introCard:{...To.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...To.suggestion.chip,fontWeight:"400"},card:{...To.suggestion.card,fontWeight:"400"},list:{...To.suggestion.list,fontWeight:"400"}},panel:{...To.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...To.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:{...To.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...To.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:{...To.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...To.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)"}};var yR=e=>Ts({future:e}),hh=e=>yR(e)==="v5"?{palette:fR,semantic:gR,components:hR}:{palette:uR,semantic:mR,components:gh};function zn(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."))?zn(e,o):o}function IA(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=zn(e,i);c!==void 0&&(t[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function bR(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 HA(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]=HA(s,r):n[o]=r}return n}function vR(e,t){return t?HA(e,t):e}function _a(e,t={}){let n=hh(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:vR(o.components,e?.components)},s=e?.components?.activity;for(let d of["toolBubble","reasoningBubble"])for(let p of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[p]!==void 0&&(r.components[d][p]=s[p]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let d=bR(r);if(!d.valid)throw new Error(`Theme validation failed: ${d.errors.map(p=>p.message).join(", ")}`)}if(t.plugins)for(let d of t.plugins)r=d.transform(r);return r}var mh=e=>e.trim()==="0"?"0px":e,PA="--persona-",CR=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let d=c.endsWith("%"),p=parseFloat(d?c.slice(0,-1):c);return d?p/100*255:p}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},wR=.179,Un=(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[PA+s],r!==void 0)break;r!==void 0&&(e[PA+n]=r)}};function RA(e){let t=IA(e),n={};for(let[N,ke]of Object.entries(t)){let ve=N.replace(/\./g,"-");n[`--persona-${ve}`]=ke.value}Un(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"],Un(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"]]),Un(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"]}`,Un(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"]??Su,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Au,Un(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"]]),Un(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=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"],Un(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"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],Un(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 c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let d=n["--persona-components-history-railHeader-border"];d&&(n["--persona-history-rail-header-border"]=d);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[N,ke]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ve=n[`--persona-components-history-overlay-${N}`];ve&&(n[`--persona-history-overlay-${ke}`]=ve)}for(let[N,ke]of[["background","bg"],["borderRadius","radius"]]){let ve=n[`--persona-components-history-menu-${N}`];ve&&(n[`--persona-history-menu-${ke}`]=ve)}let f=e.components?.history?.motion;if(f){let N=tt=>{if(tt===void 0)return;let xt=String(tt).trim();return/^\d+(\.\d+)?$/.test(xt)?`${xt}ms`:xt},ke=N(f.enterDurationMs);ke!==void 0&&(n["--persona-history-enter-ms"]=ke);let ve=N(f.exitDurationMs);ve!==void 0&&(n["--persona-history-exit-ms"]=ve),f.enterEasing&&(n["--persona-history-enter-easing"]=f.enterEasing),f.exitEasing&&(n["--persona-history-exit-easing"]=f.exitEasing)}let m=n["--persona-components-history-dangerForeground"];m&&(n["--persona-history-danger-fg"]=m),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 N of["scrim","shadow"]){let ke=n[`--persona-components-history-confirm-${N}`];ke&&(n[`--persona-history-confirm-${N}`]=ke)}for(let[N,ke]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ve=n[`--persona-components-tooltip-${N}`];ve&&(n[`--persona-tooltip-${ke}`]=ve)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,ke]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ve=n[`--persona-components-messageActions-${N}`];ve&&(n[`--persona-message-action-${ke}`]=ve)}Un(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let g=n["--persona-components-introCard-background"],h=n["--persona-components-introCard-shadow"],b=(!g||g==="transparent"||g==="none")&&(!h||h==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=b&&C==="1.5rem"?"1.5rem 0":C,Un(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"]]),Un(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 A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let S=n["--persona-components-markdown-heading-h1-fontWeight"];S&&(n["--persona-md-h1-weight"]=S);let E=n["--persona-components-markdown-heading-h2-fontSize"];E&&(n["--persona-md-h2-size"]=E);let k=n["--persona-components-markdown-heading-h2-fontWeight"];k&&(n["--persona-md-h2-weight"]=k);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),Un(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"]]),Un(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Un(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Un(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Un(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 z=[["container","surface"],["surface","surface"],["border","border"]];for(let[N,ke]of z){let ve=n[`--persona-components-collapsibleWidget-${N}`]??n[`--persona-${ke}`];ve!==void 0&&(n[`--persona-cw-${N}`]=ve,n[`--cw-${N}`]=ve)}Un(n,[["message-border","components-message-border","border"]]),Un(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 Y=e.components,T=Y?.iconButton;T&&(T.background&&(n["--persona-icon-btn-bg"]=T.background),T.border&&(n["--persona-icon-btn-border"]=T.border),T.color&&(n["--persona-icon-btn-color"]=T.color),T.padding&&(n["--persona-icon-btn-padding"]=T.padding),T.borderRadius&&(n["--persona-icon-btn-radius"]=T.borderRadius),T.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=T.hoverBackground),T.hoverColor&&(n["--persona-icon-btn-hover-color"]=T.hoverColor),T.activeBackground&&(n["--persona-icon-btn-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-icon-btn-active-border"]=T.activeBorder));let W=Y?.labelButton;W&&(W.background&&(n["--persona-label-btn-bg"]=W.background),W.border&&(n["--persona-label-btn-border"]=W.border),W.color&&(n["--persona-label-btn-color"]=W.color),W.padding&&(n["--persona-label-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-label-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-label-btn-hover-bg"]=W.hoverBackground),W.fontSize&&(n["--persona-label-btn-font-size"]=W.fontSize),W.gap&&(n["--persona-label-btn-gap"]=W.gap));let L=Y?.toggleGroup;L&&(L.gap&&(n["--persona-toggle-group-gap"]=L.gap),L.borderRadius&&(n["--persona-toggle-group-radius"]=L.borderRadius));let w=Y?.artifact;if(w?.toolbar){let N=w.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=mh(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=mh(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(e,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=mh(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(w?.tab){let N=w.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(w?.pane){let N=w.pane;if(N.toolbarBackground){let ke=zn(e,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ke}}if(w?.card){let N=w.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(w?.inline){let N=w.inline;N.background&&(n["--persona-artifact-inline-bg"]=zn(e,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(e,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(e,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(e,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(e,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let x=Y?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=zn(e,x.background)??x.background));let P=n["--persona-surface"],I=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",_=n["--persona-palette-colors-gray-200"]??"#e5e7eb",j=n["--persona-palette-colors-gray-300"]??"#d1d5db",te=!I||I===P,K=CR(P??n["--persona-background"]),X=te&&K!==void 0&&K<wR,oe=X?"rgba(255, 255, 255, 0.08)":J,de=X?"rgba(255, 255, 255, 0.12)":_,xe=X?"rgba(255, 255, 255, 0.16)":j,Te=te?oe:I,re=te?de:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Te,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??re,te&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??xe),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Te,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Te,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Te,n}Vd();var xR=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),WA=(e,t)=>{if(!t||!xR(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ac(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Ts(t)==="v5"?"400px":"420px"}}}},SR={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"}}},ic={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)"}}}},yh=SR,AR={...yh,colors:{...yh.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"}}},MR=ic,TR={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:{...ic.components,button:{...ic.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:{...ic.components?.eventStream,badge:{...ic.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"}}}}},ER=e=>Ts({future:e})==="v5"?{palette:AR,components:TR}:{palette:yh,components:MR},BA=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bh=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",kR=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":bh()},ac=e=>kR(e),LR=(e,t={})=>_a(e,t),PR=(e,t={})=>{let n=ER(t.future),o=Zo(n.components,e??{})??{};return _a({...o,palette:{...o.palette,colors:Ts(t)==="v5"?Zo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Jr=e=>{let t=ac(e),n=BA(e?.theme),o=Cu(e)==="circle"?wu:{...gh.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Zo({components:{launcher:o}},n),s=BA(e?.darkTheme);return WA(t==="dark"?PR(Zo(r??{},s??{}),{future:e?.future}):LR(r,{future:e?.future}),e)},IR=e=>RA(e),lc=(e,t)=>{let n=Jr(t),o=IR(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ac(t)),e.setAttribute("data-persona-defaults",Ts(t))},Mu=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(bh())});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(bh());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())}};Vd();var rs=require("lucide");ln();ao();Ge();var Os=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Tu="24px",vh=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",cc=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},DA=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);Pa();zd();Pu();var FA=require("idiomorph"),Iu=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;FA.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 i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var VA=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var wh={index:-1,draft:""};function $A(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){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(!i)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 UA(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 zA(){return new Map}function qA(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function jA(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function KA(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}Sh();nr();hc();Bn();var{setLoader:o$,load:iW}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(hM(),gM))});var yM=iW;nr();function Lh(e,t=Jn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var bc=0,Ns=null;function Ph(e=document){if(bc++,bc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ns={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,bc=Math.max(0,bc-1),bc===0&&Ns)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ns.originalOverflow,n.style.position=Ns.originalPosition,n.style.top=Ns.originalTop,n.style.width=Ns.originalWidth,o.scrollTo(0,Ns.scrollY),Ns=null}}}ha();var vc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},un=e=>(e?.launcher?.mountMode??"floating")==="docked",Cc=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",$o=e=>{let t=e?.launcher?.dock,n=Ur(e).dockWidth?t?.width:zn(Jr(e),"components.panel.width");return{side:t?.side??vc.side,width:n??vc.width,animate:t?.animate??vc.animate,reveal:t?.reveal??vc.reveal,maxHeight:t?.maxHeight??vc.maxHeight}};Ge();Ge();var vM=require("lucide");ln();ao();var Ih=e=>e==="followUp"?"follow-up":e,Hh=(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"}},bM=new WeakSet,aW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,lW=e=>{aW()||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"})})},Rh=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:d,session:p,getTextarea:f,eventTarget:m,submitPrompt:g}=e,h=o==="followUp",b=t.behavior,C=()=>{if(p.isStreaming())return;let E={suggestion:{...t},surface:o,source:r,behavior:b},k=m.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:E,bubbles:!0,composed:!0,cancelable:!0}));if(h&&m.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!k)return;for(let z of c)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let D=f();if(b==="fill"){D.value=t.prompt,D.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),D.focus();return}if(g){g(t.prompt);return}D.value="",p.sendMessage(t.prompt)},A=()=>{let E=v("button",`persona-suggestion persona-suggestion--${s}`);if(E.type="button",E.disabled=i,E.dataset.suggestionId=t.id,E.dataset.emphasis=t.emphasis,E.dataset.behavior=b,s==="chip"&&(d?.fontWeight&&(E.style.fontWeight=d.fontWeight),d?.paddingX&&(E.style.paddingLeft=d.paddingX,E.style.paddingRight=d.paddingX),d?.paddingY&&(E.style.paddingTop=d.paddingY,E.style.paddingBottom=d.paddingY)),t.icon){let D=We(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);D&&(D.classList.add("persona-suggestion__icon"),t.iconColor&&(D.style.color=t.iconColor),E.appendChild(D))}let k=v("span","persona-suggestion__copy");if(k.appendChild(F("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&k.appendChild(F("span",{className:"persona-suggestion__description",text:t.description})),E.appendChild(k),s!=="chip"){let D=Je(vM.ArrowRight,16,"currentColor",1.8);D&&(D.classList.add("persona-suggestion__arrow"),E.appendChild(D))}return E.addEventListener("click",C),E},S=null;for(let E of c)if(E.renderSuggestion&&(S=E.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),S))break;return S??=A(),S.dataset.suggestionId||=t.id,S.dataset.behavior||=b,S.dataset.emphasis||=t.emphasis,S instanceof HTMLButtonElement||S.setAttribute("aria-disabled",i?"true":"false"),S},wc=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{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 f=getComputedStyle(e).direction==="rtl",m=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),g=4,h=m<=g,b=m>=p-g,C=f?!b:!h,A=f?!h:!b;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,f,m,g,h,b)=>{e.replaceChildren(),t.length=0,n.length=0;let C=b?.source??"config",A=b?.surface??(C==="config"?"starter":"followUp"),S=A==="followUp",E=b?.variant??"chip",k=b?.behavior??"send",D=b?.overflow??"wrap",z=b?.config??{},Y=b?.plugins??[],T=typeof b?.maxItems=="number"?Math.max(0,Math.floor(b.maxItems)):void 0,W=S?"followUps":"starters";!bM.has(z)&&z.debug===!0&&E!=="chip"&&z.suggestions?.[W]?.overflow!==void 0&&(bM.add(z),console.info(`[persona] suggestions.${W}.overflow applies to the "chip" variant only; the "${E}" variant manages its own stacking.`));let L=_=>_.map(Hh).filter(j=>j!==null).map(j=>({...j,behavior:j.behavior??k})),w=L(p??[]);Y.forEach(_=>{_.transformSuggestions&&(w=L(_.transformSuggestions({suggestions:w.map(j=>({...j})),surface:A,source:C,config:z})))});let x=T===void 0?w:w.slice(0,T);if(!x.length){e.hidden=!0,o=null,s();return}if(!S&&(g??f.getMessages()).some(j=>j.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ih(A),e.dataset.variant=E,e.dataset.overflow=D;let P=document.createDocumentFragment(),I=f.isStreaming();x.forEach((_,j)=>{let te=Rh({item:_,index:j,surface:A,source:C,variant:E,streaming:I,config:z,plugins:Y,chipsConfig:h,session:f,getTextarea:()=>m,eventTarget:e,submitPrompt:b?.submitPrompt});P.appendChild(te),n.push(te),[...te instanceof HTMLButtonElement?[te]:[],...Array.from(te.querySelectorAll("button"))].forEach(X=>{t.includes(X)||(X.disabled=I,t.push(X))})}),e.appendChild(P),i(),l();let J=JSON.stringify({normalized:x,surface:A,variant:E,source:C});J!==o&&(o=J,lW(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:x.map(_=>({..._})),surface:A,source:C,variant:E},bubbles:!0,composed:!0})),S&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:x.map(_=>_.prompt)},bubbles:!0,composed:!0})))}}};var Eo={"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"};nr();Ge();ln();er();Ge();ln();Pa();var cW="persona-header-control",dW="persona-header-control--glyph",pW="persona-header-control--sparse",uW=20,fW={x:[1.4,1.05]},CM="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mW="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ou=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=fW[t]??[1,1.5],l=!o;e.classList.toggle(dW,l),e.classList.toggle(pW,l&&s!==1);let c=parseFloat(o??"")||uW,d=We(t,`${Math.round(c*s)}px`,"currentColor",i);d?(d.style.display="block",l||(d.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(d)):r&&(e.textContent=r)},Na=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=CM,size:l,iconSize:c,color:d,backgroundColor:p,borderWidth:f,borderColor:m,borderRadius:g,paddingX:h,paddingY:b,hidden:C,extraClassName:A,attrs:S}=e,E=v("div",i),k=!!(f||m),D=F("button",{className:Jt(cW,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!k&&"persona-border-none",!g&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...S},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:d||lo.actionIconColor,backgroundColor:p,border:k?`${f||"0px"} solid ${m||"transparent"}`:void 0,borderRadius:g,paddingLeft:h,paddingRight:h,paddingTop:b,paddingBottom:b}});return r?Ou(D,r,{iconSize:c,iconText:s}):s&&(D.textContent=s),E.appendChild(D),$n({anchor:D,trigger:E,text:()=>D.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:D,wrapper:E}},Fa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=CM,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:d,wrapper:p}=Na({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:d,wrapper:p}},Va=(e,t={})=>{let{wrapperClassName:n=mW,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:d,wrapper:p}=Na({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:d,wrapper:p}};var lo={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)"},Wh={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)"},gW={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)"},Ii=e=>{let{config:t,showClose:n=!0}=e,o=F("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:lo.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??Ll,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,d=F("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(c){let D=parseFloat(s)||24,z=We(c,D*.6,"currentColor",1);z?(z.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,z.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren(z)):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let D=v("img");D.src=t.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,d.replaceChildren(D)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=F("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:lo.titleColor,...Wh}}),m=F("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:lo.subtitleColor,...gW}});p.append(f,m),l?o.append(p):o.append(d,p);let g=r.clearChat??{},h=g.enabled??!0,b=g.placement??"inline",C=null,A=null;if(h){let z=Va(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=z.button,A=z.wrapper,b==="top-right"&&(A.style.right="48px"),b==="inline"&&o.appendChild(A)}let S=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&b==="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:E,wrapper:k}=Fa(t,{showClose:n,wrapperClassName:S});return i!=="top-right"&&o.appendChild(k),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:m,closeButton:E,closeButtonWrapper:k,clearChatButton:C,clearChatButtonWrapper:A}},xc=(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))};Ge();Bh();Ri();Pu();var hW=e=>{let t=Ii({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 yW(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Na({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Lu(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 i=dc(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Sc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var bW=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=lo.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 c=r?.titleMenu,d,p;if(c){let k=xM({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:D=>{let z=T=>{T===!1&&k.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},Y=c.onSelect(D);Y instanceof Promise?Y.then(z,()=>{}):z(Y)},hover:c.hover,className:""});d=k.element,d.style.color=lo.titleColor,p=d.querySelector(".persona-combo-btn-label")??d}else{if(d=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=lo.titleColor,Object.assign(p.style,Wh),p.textContent=i.title??"Chat Assistant",d.appendChild(p),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let D=r.onTitleClick;d.addEventListener("click",z=>{z.target.closest("button")||D()}),d.addEventListener("keydown",z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),D())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:m,wrapper:g}=Fa(t,{showClose:n,wrapperClassName:f});o&&m.addEventListener("click",o);let h=v("div","persona-flex persona-items-center persona-gap-1");c||yW(h,r?.trailingActions,r?.onAction??s);let b=i.clearChat??{},C=null,A=null;if(b.enabled??!0){let k=b.placement??"inline",D=Va(t,{wrapperClassName:k==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});C=D.button,A=D.wrapper,k==="top-right"?A.style.right="48px":h.appendChild(A)}h.appendChild(g),l.appendChild(h);let S=v("div");S.style.display="none";let E=v("span");return E.style.display="none",{header:l,iconHolder:S,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:g,clearChatButton:C,clearChatButtonWrapper:A}},SM={default:hW,minimal:bW},vW=e=>SM[e]??SM.default,Fu=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=v("div");l.style.display="none";let c=v("span"),d=v("span"),p=v("button");p.style.display="none";let f=v("div");return f.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:d,closeButton:p,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=vW(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};Ge();Ws();var Ac=e=>{let{config:t}=e,n=F("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=Fp(),r=F("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:i}=Dp(t);i();let l=_p(t),c=Ia(t),d=Op(t),p=Np(t),f=F("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(f),d&&(d.previewsContainer.style.gap="8px",f.append(d.previewsContainer),r.append(d.input)),r.append(s);let m=F("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=F("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),h=F("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&g.append(d.wrapper),c&&h.append(c.wrapper),h.append(l.wrapper),m.append(g,h),r.append(m),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,p,r):n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,header:f,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:l.setMode}};Ge();var Vu=require("lucide");ao();Ws();Wp();var AM=()=>{let e=F("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=v("span","persona-pill-peek__icon"),n=Je(Vu.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Je(Vu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},$u=e=>{let{config:t}=e,n=F("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Fp(),r=Np(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Dp(t,{defaultMaxLines:5});i();let l=_p(t),c=Ia(t),d=Op(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let p=F("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),f=F("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&f.append(d.wrapper);let m=F("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&m.append(c.wrapper),m.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),d&&p.append(d.input),p.append(f,s,m);let g=F("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(g),d&&g.append(d.previewsContainer),n.append(o,p,r);let h=p;return{footer:n,suggestions:o,composerForm:p,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:h,leftActions:f,rightActions:m,setSendButtonMode:l.setMode}};Ge();ln();Ge();zg();Ri();ln();Rs();hc();var CW=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}},wW=(e,t)=>{if(!e)return null;let n=CW(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},xW=(e,t)=>{let n=v("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},SW=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},_h=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(":"))},Oh=320,LM=320,AW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),MW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),TW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),EW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),kW=e=>{if(!e||e.length===0)return null;let t=F("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=F("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=We(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(F("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},LW=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Zl(o.ref,{readonly:!0,render:t}))}return n},MM="\uE000",TM="\uE001",PW=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=m=>`${MM}${r}:${m}${TM}`,i=t.map((m,g)=>m.kind==="text"?m.text:s(g)).join(""),l=n(i);if(!t.every((m,g)=>m.kind==="text"||l.includes(s(g)))){e.replaceChildren(LW(t,o));return}e.innerHTML=l;let d=new RegExp(`${MM}${r}:(\\d+)${TM}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let m=p.nextNode();m;m=p.nextNode())f.push(m);for(let m of f){let g=m;for(let h=d.exec(g.data);h;h=d.exec(g.data)){let b=t[Number(h[1])],C=g.splitText(h.index);C.data=C.data.slice(h[0].length),b?.kind==="mention"&&C.parentNode?.insertBefore(Zl(b.ref,{readonly:!0,render:o}),C),g=C}}},IW=(e,t,n)=>{if(e.length===0)return null;try{let o=v("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,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let d=v("img");d.alt=l.alt?.trim()||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Oh}px`,d.style.maxHeight=`${LM}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,d.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),d.remove(),r===0&&i())}),d.addEventListener("load",()=>{p=!0}),SW(l.image)?(d.src=l.image,o.appendChild(d)):(p=!0,r=Math.max(0,r-1),d.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},HW=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!_h(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Oh}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},RW=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!_h(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Oh}px`,r.style.maxHeight=`${LM}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}},WW=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!_h(o.data))return;let r=v("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}},Mc=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},BW=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Mc};if(t){let r=t(o);if(r!==null)return r}return Mc()},DW=(e,t)=>{let n=v("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=v("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},EM=(e,t,n="div")=>{let o=v(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},Tc=(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},kM={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"}},_W=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=kM[n??"bubble"]??kM.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)`)},Uu="custom:",OW=e=>`${Uu}${e}`,PM=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),NW=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,d=(t.showEdit??!1)&&o?.canEdit===!0,p=(t.showQuote??!1)&&o?.canQuote!==!1,f=PM(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!d&&!p&&f.length===0){let E=v("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let m=t.visibility??"hover",g=t.align??"right",h=t.layout??"pill-inside",b={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[g],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[h],A=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${b} ${C} ${m==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let S=(E,k,D)=>{let z=Ln({icon:E,label:k,size:14,className:"persona-message-action-btn",chromeless:!0});return z.setAttribute("data-action",D),z};r&&A.appendChild(S("copy","Copy message","copy")),l&&A.appendChild(S("volume-2","Read aloud","read-aloud")),s&&A.appendChild(S("thumbs-up","Upvote","upvote")),i&&A.appendChild(S("thumbs-down","Downvote","downvote")),c&&A.appendChild(S("refresh-cw","Regenerate response","regenerate")),d&&A.appendChild(S("pencil","Edit message","edit")),p&&A.appendChild(S("quote","Quote message","quote"));for(let E of f)A.appendChild(S(E.iconName??"ellipsis",E.label,OW(E.id)));return A},Nh=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,d=i.timestamp,p=c?.show??!1,f=d?.show??!1,m=c?.position??"left",g=d?.position??"below",h=Tc(e.role,l),b=v("div",h.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=hh(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;_W(b,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(b.style.backgroundColor="transparent",b.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=AW(e),E=e.content?.trim()??"",D=S.length>0&&E===La,z=Bu(s?.widgetConfig?.features?.streamAnimation),Y=s?.widgetConfig?.features?.streamAnimation?.plugins,T=e.role==="assistant"&&z.type!=="none"?uc(z.type,Y):null,W=e.role==="assistant"&&T?.isAnimating?.(e)===!0,L=e.role==="assistant"&&T!==null&&(!!e.streaming||W);L&&T?.bubbleClass&&b.classList.add(T.bubbleClass);let w=document.createElement("div");w.classList.add("persona-message-content"),e.streaming&&w.classList.add("persona-content-streaming"),L&&T&&(T.containerClass&&w.classList.add(T.containerClass),w.style.setProperty("--persona-stream-step",`${z.speed}ms`),w.style.setProperty("--persona-stream-duration",`${z.duration}ms`));let x=L?Du(e.content??"",z.buffer,T,e,!!e.streaming):e.content??"",P=()=>{let re=t({text:x,message:e,streaming:!!e.streaming,raw:e.rawContent});return L&&T?.wrap==="char"?fc(re,"char",e.id,{skipTags:T.skipTags}):L&&T?.wrap==="word"?fc(re,"word",e.id,{skipTags:T.skipTags}):re},I=null;if(D?(I=document.createElement("div"),I.innerHTML=P(),I.style.display="none",w.appendChild(I)):e.contentSegments?.length?PW(w,e.contentSegments,re=>t({text:re,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):w.innerHTML=P(),L&&T?.useCaret&&!D&&E){let re=_u(),N=w.querySelectorAll(".persona-stream-char, .persona-stream-word"),ke=N[N.length-1];if(ke?.parentNode)ke.parentNode.insertBefore(re,ke.nextSibling);else{let ve=w.lastElementChild;ve?ve.appendChild(re):w.appendChild(re)}}if(f&&g==="inline"&&e.createdAt){let re=EM(e,d,"span");re.classList.add("persona-timestamp-inline");let N=w.lastElementChild;N?N.appendChild(re):w.appendChild(re)}if(S.length>0){let re=IW(S,!D&&!!E,()=>{D&&I&&(I.style.display="")});re?b.appendChild(re):D&&I&&(I.style.display="")}let J=MW(e);if(J.length>0){let re=HW(J);re&&b.appendChild(re)}let _=TW(e);if(_.length>0){let re=RW(_);re&&b.appendChild(re)}let j=EW(e);if(j.length>0){let re=WW(j);re&&b.appendChild(re)}let te=e.contentSegments?.length?null:kW(e.contextMentions);if(te&&b.appendChild(te),b.appendChild(w),f&&g==="below"&&e.createdAt){let re=EM(e,d);re.classList.add("persona-mt-1"),b.appendChild(re)}let K=e.role==="assistant"?wW(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let re=!!(x&&x.trim()),N=z.placeholder==="skeleton",ke=N&&z.buffer==="line"&&re;if(re)ke&&b.appendChild(mc());else if(N)b.appendChild(mc());else{let ve=BW("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ve&&b.appendChild(ve)}}K&&e.stopReason&&!e.streaming&&(E||(w.style.display="none"),b.appendChild(xW(e.stopReason,K)));let X=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,oe=s?.actionEligibility,de=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&oe?.canEdit===!0||o?.showQuote===!0&&oe?.canQuote===!0||PM(o,"user").length>0);if((X||de)&&o){let re=NW(e,de?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,oe);b.appendChild(re)}if(!p||e.role==="system")return b;let xe=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Te=DW(c,e.role);return m==="right"||m==="left"&&e.role==="user"?xe.append(b,Te):xe.append(Te,b),xe};var FW=40,VW=(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=We(t.name,FW);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(F("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(F("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},IM=(e,t,n={})=>{let o=F("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),i=v("p","persona-welcome-subtitle"),l=F("div",{className:"persona-welcome-head-text"},r,s),c=F("div",{className:"persona-welcome-title-row"},o,l);return{host:F("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)"}},c,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},$a=(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)},qu=(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==="",VW(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")},$W="data-persona-welcome-plugin",HM="data-persona-welcome-overlay",zu="persona-welcome-overlay-active",Fh=new WeakMap,Vh=(e,t,n)=>{n.setAttribute($W,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(HM,""),e.classList.contains(zu)||(Fh.set(e,e.scrollTop),e.classList.add(zu),e.scrollTop=0)},$h=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(HM),e.classList.contains(zu)&&(e.classList.remove(zu),e.scrollTop=Fh.get(e)??e.scrollTop,Fh.delete(e))},RM=()=>{let e=F("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},ju=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=F("div",{className:Tc("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(F("div",{className:"persona-flex"},r)),e.hidden=!1},WM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,BM=(e,t)=>{if(WM()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let h=getComputedStyle(o);r=parseFloat(h.rowGap)||0;let b=e.previousElementSibling,C=e.nextElementSibling,S=o.getBoundingClientRect().top+(parseFloat(h.borderTopWidth)||0)+(parseFloat(h.paddingTop)||0)-o.scrollTop;s=Math.max(0,b?n.top-b.getBoundingClientRect().bottom-r:n.top-S),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),d=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,f=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${p}px`,marginTop:`${s}px`,marginBottom:`${i}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"}),m=!1,g=()=>{m||(m=!0,e.style.overflow=l,t(f))};return f.finished.then(g).catch(g),f},DM=(e,t,n,o=260)=>{if(t<=1||WM()||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 UW="Hello \u{1F44B}",zW="I can answer questions and help you get things done here.",_M=new WeakSet,co=(e,t)=>!!e&&e[t]!==void 0,qW=(e,t)=>{!e||e.debug!==!0||!t.length||_M.has(e)||(_M.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ku=(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"),i=co(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":co(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];co(n,"title")&&co(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),co(n,"subtitle")&&co(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),co(n,"variant")&&co(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&co(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&co(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=n?.anchor??(s==="centered"&&t?"center":"bottom"),p=cc(n?.anchorComposerTop)!==null;return co(n,"anchorComposerTop")&&!p&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),d!=="center"&&(co(n,"anchorComposerTop")||co(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),qW(e,c),{title:co(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":UW),kicker:n?.kicker??"",subtitle:co(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":zW),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:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:d,anchorComposerTop:p?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Tu}},OM=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ua=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");ha();var jW="var(--persona-components-panel-maxWidth)",NM="var(--persona-components-panel-height)",KW="var(--persona-components-panel-maxHeight)",Wi=e=>{let t=Ur(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${NM})`:`max(200px, calc(${NM} - ${o}px))`;return{width:n??SC,maxWidth:n??jW,height:r,maxHeight:KW}},FM="16px",zh="10px",qh="14px",VM=e=>{let t=e?.launcher?.enabled??!0,n=un(e);if(Cc(e)){let d=e?.launcher?.composerBar??{},p=v("div","persona-widget-wrapper persona-fixed persona-transition");p.setAttribute("data-persona-composer-bar",""),p.dataset.state="collapsed",p.dataset.expandedSize=d.expandedSize??"anchored",p.style.zIndex=String(e?.launcher?.zIndex??Jn);let f=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");f.style.width="100%",p.appendChild(f);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=d.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Jn),{wrapper:p,panel:f,pillRoot:m}}if(n){let d=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(p),{wrapper:d,panel:p}}if(!t){let d=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),p=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),f=Ur(e),g=f.launcherWidth||f.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Wi(e).width:"100%";return d.style.width=g,p.style.width="100%",d.appendChild(p),{wrapper:d,panel:p}}let r=e?.launcher??{},s=r.position&&Eo[r.position]?Eo[r.position]:Eo["bottom-right"],i=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Jn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Wi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},jh=e=>{let t=F("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ih(e)}});return t.hidden=!0,t},$M=(e,t)=>{let n=jh("starter"),o=IM(e,n,{flatShadow:un(e)}),r=Ku(e);qu(o,r),$a(t,o.host,Ua(r,e?.initialMessages));let s=RM();return ju(s,r.message,e),{welcome:o,greetingHost:s}},GW=(e,t)=>{let n=v("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}=Fa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:FM,iconSize:zh});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let Y=Va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:FM,iconSize:qh});i=Y.button,l=Y.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=F("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=F("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"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:f}=$M(e,d),{host:m,title:g,subtitle:h}=p,b=p.starterSuggestions,C=v("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=jh("followUp"),S=Os(e,!0);S&&(C.style.maxWidth=S,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),d.append(m,f,C,A);let E=F("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"}}),k=$u({config:e}),{root:D,textNode:z}=AM();return n.append(c,r,d,E),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:C,starterSuggestions:b,transcriptSuggestions:A,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,welcomeHost:m,welcomeIconHolder:p.iconHolder,greetingHost:f,introKicker:p.kicker,introTitle:g,introSubtitle:h,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:c,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:D,peekTextNode:z}},UM=(e,t=!0)=>{if(Cc(e))return GW(e,t);let n=F("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?Fu(e,o,{showClose:t}):Ii({config:e,showClose:t}),i=F("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=$M(e,i),{host:d,title:p,subtitle:f}=l,m=l.starterSuggestions,g=v("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let h=jh("followUp"),b=Os(e,!1);b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),i.append(d,c,g,h);let C=Ac({config:e}),A=e?.layout?.showFooter!==!1;r?xc(n,s,e):(s.header.style.display="none",xc(n,s,e)),n.append(i);let S=F("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 A||(C.footer.style.display="none"),n.append(C.footer),n.append(S),{container:n,body:i,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:h,composerOverlay:S,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:p,introSubtitle:f,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};Ws();Ge();ln();nr();var Kh=(e,t)=>{let n=v("button");n.type="button",n.innerHTML=`
1177
1177
  <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>
1178
1178
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
1179
1179
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -1181,15 +1181,15 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1181
1181
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
1182
1182
  </span>
1183
1183
  <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>
1184
- `,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=un(s),c=Cu(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",i.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let d=n.querySelector("[data-role='launcher-title']");if(d){let k=i.title??"Chat Assistant";d.textContent=k,d.setAttribute("title",k)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let k=i.subtitle??"Here to help you get answers fast";p.textContent=k,p.setAttribute("title",k)}let f=n.querySelector(".persona-flex-col");f&&(i.textHidden||l||c?f.style.display="none":f.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let k=i.agentIconSize??"40px";if(m.style.height=k,m.style.width=k,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let D=parseFloat(k)||24,z=We(i.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",1.5);z?(m.appendChild(z),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let k=i.agentIconSize??"40px";g.style.height=k,g.style.width=k,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let k=i.callToActionIconSize??"32px";h.style.height=k,h.style.width=k,i.callToActionIconBackgroundColor?(h.style.backgroundColor=i.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(h.style.color=i.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let D=0;if(i.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=i.callToActionIconPadding,D=(parseFloat(i.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),i.callToActionIconHidden||c)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",i.callToActionIconName){let z=parseFloat(k)||24,Y=Math.max(z-D,8),T=We(i.callToActionIconName,Y,"currentColor",1.5);T?h.appendChild(T):h.textContent=i.callToActionIconText??"\u2197"}else h.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&Eo[i.position]?Eo[i.position]:Eo["bottom-right"],C="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",A="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?A:`${C} ${b}`,l||(n.style.zIndex=String(i.zIndex??Jn));let S="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",E="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=i.border??S,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:E,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=i.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}},GW="teaser-dismissed",zM=new Set,UM=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${GW}`},YW=(e,t)=>{if(zM.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},XW=(e,t)=>{if(zM.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},QW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,JW=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||un(e??{})?null:t},qM=(e,t)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,c=null,d=!1,p=!1,f=!1,m=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,h=()=>{c!==null&&(clearTimeout(c),c=null)},b=()=>{!s||!d||(d=!1,s.hidden=!0)},C=J=>{h(),f=!0,b(),XW(UM(o),J&&g())},A=J=>{!r||f||C(J==="user"&&d)},S=()=>{c=null,!(!s||f||m)&&(p=!0,d=!0,s.hidden=!1,!(QW()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},E=()=>{!r||!s||f||p||m||YW(UM(o),g())||(h(),c=setTimeout(S,Math.max(0,r.delayMs??0)))},k=()=>{C(g()),t()},D=J=>{J.stopPropagation(),C(g())},Y=Kh(e,()=>{A("user"),t()}),T=()=>{h(),l?.removeEventListener("click",k),i?.removeEventListener("click",D),s?.remove(),s=null,l=null,i=null,d=!1},W=()=>{l=F("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",k),i=F("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",D),s=F("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,Y.element)},L=()=>{let J=o.launcher?.position??"bottom-right",_=Eo[J]??Eo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",Y.element.style.position="";return}n.className=Jt("persona-launcher-surface",_),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??Jn),Y.element.style.position="static"},w=J=>{let _=JW(J);if(r=_,!_){T();return}s||W(),l.textContent=_.text,i.hidden=_.dismissible===!1,i.setAttribute("aria-label",_.dismissLabel??"Dismiss message"),E()},x=J=>{o=J,Y.update(J),w(J),L()},P=(J,_="user")=>{m=J,J&&A(_)},I=()=>{T(),Y.destroy(),n.remove()};return n.appendChild(Y.element),e&&(w(e),L()),{element:n,launcher:Y,get teaser(){return s?{element:s,show:S,dismiss:C}:null},setPanelOpen:P,update:x,destroy:I}};var jM=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=FM(e),s=$M(e,t),i={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},c={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={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:i,panelElements:s,transcript:l,header:c,composer:d,replaceHeader:m=>(c.element.replaceWith(m.header),c.element=m.header,c.iconHolder=m.iconHolder,c.headerTitle=m.headerTitle,c.headerSubtitle=m.headerSubtitle,c.closeButton=m.closeButton,c.closeButtonWrapper=m.closeButtonWrapper,c.clearChatButton=m.clearChatButton,c.clearChatButtonWrapper=m.clearChatButtonWrapper,m),replaceComposer:m=>{d.footer.replaceWith(m),d.footer=m}}},Gh=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Kh(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=qM(e,n);return{instance:r,element:r.element}};var ZW=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},eB=(e,t,n)=>`${ZW(e)}plugin:${t}:${n}`,KM=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=i=>eB(e(),r,i);return{get:i=>{let l=s(i),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let c=s(i),d=o();if(d)try{d.setItem(c,l);return}catch{n=!0}t.set(c,l)},remove:i=>{let l=s(i);t.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};Ge();ln();er();Gr();Gu();var tB=(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(`
1185
- `):""},Yh=(e,t,n)=>{np(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Xh=(e,t,n=new Set)=>{t=rp(t,"reasoning");let o=e.reasoning,r=Jd("persona-reasoning-bubble",e.id);if(!o)return qr(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??wi.expandable,l=i&&n.has(e.id),c=o.status!=="complete",d=tB(e,s.previewMaxLines??wi.previewMaxLines),p=Zd({expandable:i,expanded:l,bubbleType:"reasoning"}),f=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),g=Es(t,"reasoning")==="row",h=g&&!c?`Thought for ${Pl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",b=t?.reasoning??{},C=String(o.startedAt??Date.now()),A=()=>{let _=v("span","");return _.setAttribute("data-tool-elapsed",C),_.textContent=pp(o),_},S=b.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:d,isActive:c,config:t??{},elapsed:pp(o),createElapsedElement:A});typeof S=="string"&&S.trim()?(m.textContent=S,f.appendChild(m)):S instanceof HTMLElement?f.appendChild(S):(m.textContent=h,f.appendChild(m));let E=v("span","persona-text-xs persona-text-persona-primary");E.textContent=ew(o),g||f.appendChild(E);let k=s.loadingAnimation??wi.loadingAnimation,D=b.activeTextTemplate,z=b.completeTextTemplate,Y=c?D:z,T=S instanceof HTMLElement,W=(_,j)=>{m.textContent="";let te=up(_,""),K=0;for(let X of te){let oe=X.styles.length>0?(()=>{let de=v("span",X.styles.map(xe=>`persona-tool-text-${xe}`).join(" "));return m.appendChild(de),de})():m;if(X.isDuration&&c)oe.appendChild(A());else{let de=X.isDuration?pp(o):X.text;j?K=Fs(oe,de,K):oe.appendChild(document.createTextNode(de))}}};if(!T&&Y)if(E.style.display="none",m.style.display="",c&&k!=="none"){let _=b.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),k==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),W(Y,!1)):(m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),k==="shimmer-color"&&(b.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",b.loadingAnimationColor),b.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",b.loadingAnimationSecondaryColor)),W(Y,!0))}else W(Y,!1);else if(!T&&c&&k!=="none"){m.style.display="";let _=b.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),k==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`);else{m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),k==="shimmer-color"&&(b.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",b.loadingAnimationColor),b.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",b.loadingAnimationSecondaryColor));let j=m.textContent||h;m.textContent="",Fs(m,j,0)}o.status==="complete"&&!g&&(m.style.display="none")}else T||(o.status==="complete"&&!g?m.style.display="none":m.style.display="");if(s.iconName&&!T){let _=v("span","persona-reasoning-header-icon"),j=We(s.iconName,16,"currentColor",2);j&&(_.appendChild(j),p.appendChild(_))}let L="currentColor",w=ba(p,f,{expandable:i,expanded:l,iconColor:L,metaGap:!1}),x=ep({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:d,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:d,isActive:c,config:t??{}})});if(!i)return r.append(p,x),qr(r,e,t,"reasoning");let P=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=l?"":"none";let I=o.chunks.join(""),J=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=I||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),P.appendChild(J),tp({expanded:l,header:p,toggleIcon:w,content:P,collapsedPreview:x,iconColor:L}),r.append(p,x,P),qr(r,e,t,"reasoning")};Ge();Gr();ln();var GM=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return GM(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},nB=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 YM(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let d=F("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=F("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),f=tr(c),m=F("pre",{className:`persona-tool-detail-value${nB(c)?" persona-tool-detail-code":""}`,text:f,attrs:f.length>420||f.split(`
1186
- `).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),g=F("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),h=We("copy",14,"currentColor",1.7);h&&g.appendChild(h),d.append(p,m,g),e.appendChild(d)};GM(o.args)||s("Request",o.args);let i=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");i!==void 0&&(typeof i!="string"||i.trim())&&s("Response",i),o.success===!1&&e.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Qh=new WeakMap;async function XM(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(Qh.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=We("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"}Qh.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=We("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),Qh.delete(e)},1800))}Ge();er();Gr();Gu();var QM=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),oB=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
1184
+ `,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=un(s),c=Cu(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",i.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let d=n.querySelector("[data-role='launcher-title']");if(d){let k=i.title??"Chat Assistant";d.textContent=k,d.setAttribute("title",k)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let k=i.subtitle??"Here to help you get answers fast";p.textContent=k,p.setAttribute("title",k)}let f=n.querySelector(".persona-flex-col");f&&(i.textHidden||l||c?f.style.display="none":f.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let k=i.agentIconSize??"40px";if(m.style.height=k,m.style.width=k,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let D=parseFloat(k)||24,z=We(i.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",1.5);z?(m.appendChild(z),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let k=i.agentIconSize??"40px";g.style.height=k,g.style.width=k,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let k=i.callToActionIconSize??"32px";h.style.height=k,h.style.width=k,i.callToActionIconBackgroundColor?(h.style.backgroundColor=i.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(h.style.color=i.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let D=0;if(i.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=i.callToActionIconPadding,D=(parseFloat(i.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),i.callToActionIconHidden||c)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",i.callToActionIconName){let z=parseFloat(k)||24,Y=Math.max(z-D,8),T=We(i.callToActionIconName,Y,"currentColor",1.5);T?h.appendChild(T):h.textContent=i.callToActionIconText??"\u2197"}else h.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&Eo[i.position]?Eo[i.position]:Eo["bottom-right"],C="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",A="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?A:`${C} ${b}`,l||(n.style.zIndex=String(i.zIndex??Jn));let S="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",E="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=i.border??S,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:E,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=i.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}},YW="teaser-dismissed",qM=new Set,zM=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${YW}`},XW=(e,t)=>{if(qM.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},QW=(e,t)=>{if(qM.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},JW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ZW=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||un(e??{})?null:t},jM=(e,t)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,c=null,d=!1,p=!1,f=!1,m=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,h=()=>{c!==null&&(clearTimeout(c),c=null)},b=()=>{!s||!d||(d=!1,s.hidden=!0)},C=J=>{h(),f=!0,b(),QW(zM(o),J&&g())},A=J=>{!r||f||C(J==="user"&&d)},S=()=>{c=null,!(!s||f||m)&&(p=!0,d=!0,s.hidden=!1,!(JW()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},E=()=>{!r||!s||f||p||m||XW(zM(o),g())||(h(),c=setTimeout(S,Math.max(0,r.delayMs??0)))},k=()=>{C(g()),t()},D=J=>{J.stopPropagation(),C(g())},Y=Kh(e,()=>{A("user"),t()}),T=()=>{h(),l?.removeEventListener("click",k),i?.removeEventListener("click",D),s?.remove(),s=null,l=null,i=null,d=!1},W=()=>{l=F("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",k),i=F("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",D),s=F("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,Y.element)},L=()=>{let J=o.launcher?.position??"bottom-right",_=Eo[J]??Eo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",Y.element.style.position="";return}n.className=Jt("persona-launcher-surface",_),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??Jn),Y.element.style.position="static"},w=J=>{let _=ZW(J);if(r=_,!_){T();return}s||W(),l.textContent=_.text,i.hidden=_.dismissible===!1,i.setAttribute("aria-label",_.dismissLabel??"Dismiss message"),E()},x=J=>{o=J,Y.update(J),w(J),L()},P=(J,_="user")=>{m=J,J&&A(_)},I=()=>{T(),Y.destroy(),n.remove()};return n.appendChild(Y.element),e&&(w(e),L()),{element:n,launcher:Y,get teaser(){return s?{element:s,show:S,dismiss:C}:null},setPanelOpen:P,update:x,destroy:I}};var KM=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=VM(e),s=UM(e,t),i={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},c={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={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:i,panelElements:s,transcript:l,header:c,composer:d,replaceHeader:m=>(c.element.replaceWith(m.header),c.element=m.header,c.iconHolder=m.iconHolder,c.headerTitle=m.headerTitle,c.headerSubtitle=m.headerSubtitle,c.closeButton=m.closeButton,c.closeButtonWrapper=m.closeButtonWrapper,c.clearChatButton=m.clearChatButton,c.clearChatButtonWrapper=m.clearChatButtonWrapper,m),replaceComposer:m=>{d.footer.replaceWith(m),d.footer=m}}},Gh=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Kh(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=jM(e,n);return{instance:r,element:r.element}};var eB=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},tB=(e,t,n)=>`${eB(e)}plugin:${t}:${n}`,GM=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=i=>tB(e(),r,i);return{get:i=>{let l=s(i),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let c=s(i),d=o();if(d)try{d.setItem(c,l);return}catch{n=!0}t.set(c,l)},remove:i=>{let l=s(i);t.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};Ge();ln();er();Gr();Gu();var nB=(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(`
1185
+ `):""},Yh=(e,t,n)=>{np(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Xh=(e,t,n=new Set)=>{t=rp(t,"reasoning");let o=e.reasoning,r=Jd("persona-reasoning-bubble",e.id);if(!o)return qr(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??wi.expandable,l=i&&n.has(e.id),c=o.status!=="complete",d=nB(e,s.previewMaxLines??wi.previewMaxLines),p=Zd({expandable:i,expanded:l,bubbleType:"reasoning"}),f=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),g=Es(t,"reasoning")==="row",h=g&&!c?`Thought for ${Pl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",b=t?.reasoning??{},C=String(o.startedAt??Date.now()),A=()=>{let _=v("span","");return _.setAttribute("data-tool-elapsed",C),_.textContent=pp(o),_},S=b.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:d,isActive:c,config:t??{},elapsed:pp(o),createElapsedElement:A});typeof S=="string"&&S.trim()?(m.textContent=S,f.appendChild(m)):S instanceof HTMLElement?f.appendChild(S):(m.textContent=h,f.appendChild(m));let E=v("span","persona-text-xs persona-text-persona-primary");E.textContent=ew(o),g||f.appendChild(E);let k=s.loadingAnimation??wi.loadingAnimation,D=b.activeTextTemplate,z=b.completeTextTemplate,Y=c?D:z,T=S instanceof HTMLElement,W=(_,j)=>{m.textContent="";let te=up(_,""),K=0;for(let X of te){let oe=X.styles.length>0?(()=>{let de=v("span",X.styles.map(xe=>`persona-tool-text-${xe}`).join(" "));return m.appendChild(de),de})():m;if(X.isDuration&&c)oe.appendChild(A());else{let de=X.isDuration?pp(o):X.text;j?K=Fs(oe,de,K):oe.appendChild(document.createTextNode(de))}}};if(!T&&Y)if(E.style.display="none",m.style.display="",c&&k!=="none"){let _=b.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),k==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),W(Y,!1)):(m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),k==="shimmer-color"&&(b.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",b.loadingAnimationColor),b.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",b.loadingAnimationSecondaryColor)),W(Y,!0))}else W(Y,!1);else if(!T&&c&&k!=="none"){m.style.display="";let _=b.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),k==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`);else{m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),k==="shimmer-color"&&(b.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",b.loadingAnimationColor),b.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",b.loadingAnimationSecondaryColor));let j=m.textContent||h;m.textContent="",Fs(m,j,0)}o.status==="complete"&&!g&&(m.style.display="none")}else T||(o.status==="complete"&&!g?m.style.display="none":m.style.display="");if(s.iconName&&!T){let _=v("span","persona-reasoning-header-icon"),j=We(s.iconName,16,"currentColor",2);j&&(_.appendChild(j),p.appendChild(_))}let L="currentColor",w=ba(p,f,{expandable:i,expanded:l,iconColor:L,metaGap:!1}),x=ep({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:d,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:d,isActive:c,config:t??{}})});if(!i)return r.append(p,x),qr(r,e,t,"reasoning");let P=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=l?"":"none";let I=o.chunks.join(""),J=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=I||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),P.appendChild(J),tp({expanded:l,header:p,toggleIcon:w,content:P,collapsedPreview:x,iconColor:L}),r.append(p,x,P),qr(r,e,t,"reasoning")};Ge();Gr();ln();var YM=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return YM(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},oB=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 XM(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let d=F("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=F("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),f=tr(c),m=F("pre",{className:`persona-tool-detail-value${oB(c)?" persona-tool-detail-code":""}`,text:f,attrs:f.length>420||f.split(`
1186
+ `).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),g=F("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),h=We("copy",14,"currentColor",1.7);h&&g.appendChild(h),d.append(p,m,g),e.appendChild(d)};YM(o.args)||s("Request",o.args);let i=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");i!==void 0&&(typeof i!="string"||i.trim())&&s("Response",i),o.success===!1&&e.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Qh=new WeakMap;async function QM(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(Qh.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=We("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"}Qh.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=We("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),Qh.delete(e)},1800))}Ge();er();Gr();Gu();var JM=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),rB=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
1187
1187
  `);let r=tr(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
1188
- `):""},Jh=(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)"},rB=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??zr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":oB(e,o?.previewMaxLines??zr.previewMaxLines),i=n?Es(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:nw(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",c=t?.toolCall??{},d=i;return r==="tool-name"?d=n.name?.trim()||i:r==="tool-preview"&&s&&(d=s),l&&c.activeTextTemplate?d=og(n,c.activeTextTemplate,d):!l&&c.completeTextTemplate&&(d=og(n,c.completeTextTemplate,d)),n.success===!1?d+=" \xB7 Failed":n.superseded&&(d+=" \xB7 Approved, ran again below"),{summary:d,previewText:s,isActive:l}},Zh=(e,t,n,o)=>{np(e,t,{stateSet:n,previewKind:"tool",iconColor:QM(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},ey=(e,t,n=new Set)=>{t=rp(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Jd("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 qr(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??zr.expandable,c=l&&n.has(e.id),{summary:d,previewText:p,isActive:f}=rB(e,t),m=Zd({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=v("div","persona-flex persona-flex-col persona-text-left"),h=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(h.style.color=r.headerTextColor);let b=String(o.startedAt??Date.now()),C=()=>{let x=v("span","");return x.setAttribute("data-tool-elapsed",b),x.textContent=Wl(o),x},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:d,previewText:p,collapsedMode:i.collapsedMode??zr.collapsedMode,isActive:f,config:t??{},elapsed:Wl(o),createElapsedElement:C});typeof A=="string"&&A.trim()?(h.textContent=A,g.appendChild(h)):A instanceof HTMLElement?g.appendChild(A):(h.textContent=d,g.appendChild(h));let S=i.loadingAnimation??zr.loadingAnimation,E=r.activeTextTemplate,k=r.completeTextTemplate,D=f?E:k,z=A instanceof HTMLElement,Y=(x,P)=>{h.textContent="";let I=o.name?.trim()||"tool",J=up(x,I),_=0;for(let j of J){let te=j.styles.length>0?(()=>{let K=v("span",j.styles.map(X=>`persona-tool-text-${X}`).join(" "));return h.appendChild(K),K})():h;if(j.isDuration&&f)te.appendChild(C());else{let K=j.isDuration?Wl(o):j.text;P?_=Fs(te,K,_):te.appendChild(document.createTextNode(K))}}};if(!z)if(f&&S!=="none"){let x=r.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),S==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${x}ms`),D&&Y(D,!1);else if(h.classList.add(`persona-tool-loading-${S}`),h.style.setProperty("--persona-tool-anim-duration",`${x}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),D)Y(D,!0);else{let P=h.textContent||d;h.textContent="",Fs(h,P,0)}}else D&&Y(D,!1);let T=QM(r,Es(t,"tool")==="row"),W=ba(m,g,{expandable:l,expanded:c,iconColor:T,metaGap:!0}),L=ep({bubble:s,previewKind:"tool",expanded:c,isActive:f,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:p,isActive:f,config:t??{}})});if(!l)return s.append(m,L),qr(s,e,t,"tool");let w=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=c?"":"none",r.contentBackgroundColor&&(w.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(w.style.color=r.contentTextColor),r.contentPaddingX&&(w.style.paddingLeft=r.contentPaddingX,w.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(w.style.paddingTop=r.contentPaddingY,w.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)YM(w,e,t);else{if(o.name){let x=v("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?x.style.color=r.contentTextColor:r.headerTextColor&&(x.style.color=r.headerTextColor),x.textContent=o.name,w.appendChild(x)}if(o.args!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Arguments";let I=v("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",Jh(I,r),I.textContent=tr(o.args),x.append(P,I),w.appendChild(x)}if(o.chunks&&o.chunks.length){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Activity";let I=v("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",Jh(I,r),I.textContent=o.chunks.join(""),x.append(P,I),w.appendChild(x)}if(o.success===!1&&w.appendChild(F("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 x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Result";let I=v("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",Jh(I,r),I.textContent=tr(o.result),x.append(P,I),w.appendChild(x)}if(o.status==="complete"&&typeof o.duration=="number"){let x=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(x.style.color=r.contentTextColor),x.textContent=`Duration: ${o.duration}ms`,w.appendChild(x)}}return tp({expanded:c,header:m,toggleIcon:W,content:w,collapsedPreview:L,iconColor:T}),s.append(m,L,w),qr(s,e,t,"tool")};gp();Nl();Gr();Bn();var{setLoader:Iz,load:pB,provide:Hz,getSync:uB}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(iT(),sT))});var aT=pB;var lT=uB;Ai();Bn();var{setLoader:Gz,load:IB}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(CT(),vT))});var dy=IB;Bn();Pc();Si();Gd();var Sy=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:ij,load:fD,provide:aj,getSync:mD}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(GT(),KT))}),Ga=null,af=new Set,YT=e=>{if(Ga)return Ga;Ga=e,e.initArtifactsUi({componentRegistry:sr});for(let o of Sy)sr.has(o)||sr.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Oo();t?e.__provideMarkdownParsers(t):va(()=>{let o=Oo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Kd());let n=[...af];af.clear();for(let o of n)try{o()}catch{}return e};var lf=()=>fD().then(YT);var ts=()=>{if(Ga)return Ga;let e=mD();return e?YT(e):null},Ay=e=>Ga?()=>{}:(af.add(e),()=>{af.delete(e)});function po(e){return e?.features?.artifacts?.enabled===!0}function XT(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"),!po(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 gD(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 QT=["panel","seamless","detached"];function My(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&QT.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Ty(e){return!e||!po(e)?!1:My(e)==="detached"}function _c(e,t){if(!po(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"),gD(e),XT(e,t);return}let n=t.features?.artifacts?.layout,o=My(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 i=[[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,c]of i){let d=l?.trim();d?e.style.setProperty(c,d):e.style.removeProperty(c)}XT(e,t)}function Oc(e,t){for(let l of QT)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"),!po(t))return;let n=t.features?.artifacts?.layout,o=My(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 i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function JT(e,t){return!t||!po(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Hl();Hl();var hD=new Set(["__proto__","prototype","constructor"]),yD=new Set(["collapsed","card","panel","inline"]),ZT=new Set(["markdown","component"]),bD=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Vi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),df=e=>!hD.has(e),Ey=e=>typeof e=="string"&&yD.has(e),$i=e=>Object.keys(e).length>0;function Ar(e,t,n,o){e.push({path:t,code:n,message:o})}var vD="Ignored because this key is not part of the persisted preference schema.",cf="Ignored an unsupported value.",CD="Expected collapsed, panel, or inline.",wD='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eE={kind:"mode",message:cf},Ya={kind:"string",message:"Expected a CSS length string."},ns={kind:"boolean"},xD={paneWidth:Ya,paneMaxWidth:Ya,paneMinWidth:Ya,expandedPanelWidth:Ya,resizableMinWidth:Ya,resizableMaxWidth:Ya,expandLauncherPanelWhenOpen:ns,resizable:ns},SD={kind:"object",message:"Expected a preference object.",children:{showToolCalls:ns,showReasoning:ns,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cf},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cf},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cf},expandable:ns,grouped:ns}},reasoningDisplay:{kind:"object",children:{expandable:ns,activePreview:ns}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eE,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eE,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:ZT,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:ZT}}},filePreview:{kind:"object",children:{enabled:ns}},layout:{kind:"object",children:xD}}}}};function tE(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Ar(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Ar(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Ar(o,n,"invalid_value",t.message);case"mode":return Ey(e)?No(e):Ar(o,n,"invalid_value",t.message);case"modeMap":{if(!Vi(e))return Ar(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let c=r?i:wa(i);df(i)&&(r?r.has(i):bD.test(c))?Ey(l)?s[c]=No(l):Ar(o,`${n}.${i}`,"invalid_value",CD):Ar(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":wD)}return $i(s)?s:void 0}case"object":{if(t.bareMode&&Ey(e))return No(e);if(!Vi(e))return Ar(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))(!df(l)||!r.includes(l))&&Ar(o,s(l),"unknown_key",vD);let i={};for(let l of r){let c=t.children[l],d=tE(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&Ar(o,s(l),"deprecated_key",c.deprecated),d===void 0)continue;let p=c.alias??l,f=i[p];i[p]=Vi(f)&&Vi(d)?{...f,...d}:d}return $i(i)?i:void 0}}}function AD(e){let t=[];return{preferences:(e===null?void 0:tE(e,SD,"",t))??{},issues:t}}function Xa(e){if(Array.isArray(e))return e.map(Xa);if(!Vi(e))return e;let t={};for(let[n,o]of Object.entries(e))df(n)&&o!==void 0&&(t[n]=Xa(o));return t}function nE(e,t){let n=Xa(e);for(let[o,r]of Object.entries(t)){if(!df(o)||r===void 0)continue;let s=n[o];n[o]=Vi(s)&&Vi(r)?nE(s,r):Xa(r)}return n}function MD(e){let t={},n;for(let r of e){let s=AD(r).preferences;n=oE(n,s.artifacts?.display),t=nE(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function TD(e,t){if(t===void 0)return e===void 0?void 0:Xa(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}:{},...$i(r)?{byMediaType:r}:{}};return $i(s)?s:void 0}function oE(e,t){if(t===void 0)return e===void 0?void 0:Xa(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=TD(n.files,t.files),i={...o?{default:o}:{},...$i(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return $i(i)?i:void 0}function ED(e={},t){let n=MD(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 i=oE(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}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 ky(e){let t=e.preferences;return!t||!$i(t)?e:{...e,features:ED(e.features??{},[t])}}function kD(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 LD(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 PD(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ID(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Ly(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 rE(e,t,n,o,r,s,i=200){let l=kD(r,200),c=ID(t,n,o,i);c=Math.max(l,c);let d=LD(s);return d!==null&&(c=Math.min(c,d)),PD(e,l,c)}Bn();var{setLoader:yj,load:HD,provide:bj,getSync:RD}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(lE(),aE))});var cE=HD;var dE=RD;var Py=class{#e=new Map;register(t){this.#e.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.#e.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.#e.get(t);n&&(n.onUnregister?.(),this.#e.delete(t))}getAll(){return Array.from(this.#e.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,i)=>(i.priority??0)-(s.priority??0))}clear(){this.#e.forEach(t=>t.onUnregister?.()),this.#e.clear()}},Iy=new Py;er();er();ha();Nm();var pE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),WD=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),uE=(e,t,n)=>{if(!pE(e)||!pE(t)||WD.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]=uE(e[r],t[r],s)}return o};function fE(e,t){let n=$d(Ci),o=wC(e,t,n),r=_m(xC(uE(e,t,""),n,o),o);return Vm(jd(r),AC(e,t))}ha();var mE=()=>{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(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var BD=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},DD=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},Ry=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=BD(e),n=DD(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}},Hy=e=>typeof e=="string"?e:e==null?"":String(e),Nc={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Hy(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Hy(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:Hy(n.text)}}},gE=e=>Array.isArray(e)?e.map(t=>String(t)):[],Wy=e=>{let t=new Set(gE(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(gE(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&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=i?e.parsers.reduce((d,p)=>d||p?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let c={action:l,message:s.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let p=()=>{e.emit("action:resubmit",c)},f=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let m=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:m,resubmit:f.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var _D=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}},OD=e=>e.map(t=>({...t,streaming:!1})),ND=e=>e.map(t=>({...t,status:"complete"})),hE=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_D(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?OD(n.messages):void 0,artifacts:n.artifacts?ND(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 FD=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")},yE=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 FD(e)},VD=async(e,t)=>{let n=await yE(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await yE(`${e}\0${t}`)}`}};var bE=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,c=0,d=null,p=null,f=new Set,m=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},g=()=>{let T=m();if(!T)return d;try{return T.getItem(o)}catch{return i=!0,d}},h=(T,W)=>{if(l||T===d)return;let L=d;d=T,c+=1;let w={previousToken:L,token:T,source:W,revision:c};for(let x of f)x(w)},b=T=>{l||T.key!==null&&T.key!==o||h(T.key===null?null:T.newValue??null,"external")},C=(async()=>{let T=await VD(e,t);o=T.storageKey,r=T.leaseKey,s=T.lockName,d=g(),!n&&typeof window<"u"&&window.addEventListener("storage",b)})(),A=T=>new Promise(W=>setTimeout(W,T)),S=()=>{let T=m();if(!T)return null;try{let W=T.getItem(r);if(!W)return null;let L=JSON.parse(W);return typeof L?.expiresAt=="number"&&typeof L?.ownerNonce=="string"?L:null}catch{return null}},E=T=>{let W=m();if(W)try{S()?.ownerNonce===T&&W.removeItem(r)}catch{}},k=new Set,D=T=>l?Promise.reject(new Error("Visitor store destroyed before its first init could start")):T(),z=T=>new Promise(W=>{let L=setTimeout(w,T);function w(){clearTimeout(L),k.delete(w),window.removeEventListener("storage",x),W()}function x(P){(P.key===null||P.key===r)&&w()}k.add(w),window.addEventListener("storage",x)}),Y=async T=>{let W=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,L=Date.now()+15e3;for(;!l&&Date.now()<L;){let w=m();if(!w)break;let x=Date.now(),P=S();if(P&&P.expiresAt>x&&P.ownerNonce!==W){await z(Math.min(P.expiresAt-x,500));continue}try{w.setItem(r,JSON.stringify({ownerNonce:W,expiresAt:x+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),S()?.ownerNonce!==W){await z(500);continue}p=W;try{return await D(T)}finally{p=null,E(W)}}return D(T)};return{ready:C,async get(){return await C,h(g(),"external"),d},async set(T){await C;let W=m();if(W)try{W.setItem(o,T)}catch{i=!0}h(T,"local")},async clear(){await C;let T=m();if(T)try{T.removeItem(o)}catch{i=!0}h(null,"local")},revision(){return c},subscribe(T){return f.add(T),()=>{f.delete(T)}},async withFirstInitLock(T){await C;let W=globalThis.navigator?.locks;return W?.request?W.request(s,()=>D(T)):m()?Y(T):D(T)},matches(T,W,L){return T===e&&W===t&&L===n},destroy(){l=!0,f.clear(),typeof window<"u"&&window.removeEventListener("storage",b),p&&E(p);for(let T of[...k])T()}}};Bn();var{setLoader:p5,load:m_}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(_E(),DE))});var OE=m_;Bn();var{setLoader:S5,load:v_,provide:A5,getSync:C_}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(jE(),qE))});var KE=v_;var hf=C_;var w_=null;function GE(){return w_}Pc();Pc();var Ky=require("partial-json");Ge();function YE(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=sr.get(e.component);if(!s){if(Sy.includes(e.component)){lf().catch(()=>{});let l=v("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 i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function XE(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 Gy(e){let t=XE(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 QE(e){let t=XE(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 x_=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function JE(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:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:d=x_}=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 f=null,m=document.createElement("div");m.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,g.appendChild(h);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=r,g.appendChild(b),m.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let z=1;z<=5;z++){let Y=document.createElement("button");Y.type="button",Y.className="persona-feedback-rating-btn persona-feedback-star-btn",Y.setAttribute("role","radio"),Y.setAttribute("aria-checked","false"),Y.setAttribute("aria-label",`${z} star${z>1?"s":""}: ${d[z-1]}`),Y.title=d[z-1],Y.dataset.rating=String(z),Y.innerHTML=`
1188
+ `):""},Jh=(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)"},sB=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??zr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":rB(e,o?.previewMaxLines??zr.previewMaxLines),i=n?Es(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:nw(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",c=t?.toolCall??{},d=i;return r==="tool-name"?d=n.name?.trim()||i:r==="tool-preview"&&s&&(d=s),l&&c.activeTextTemplate?d=og(n,c.activeTextTemplate,d):!l&&c.completeTextTemplate&&(d=og(n,c.completeTextTemplate,d)),n.success===!1?d+=" \xB7 Failed":n.superseded&&(d+=" \xB7 Approved, ran again below"),{summary:d,previewText:s,isActive:l}},Zh=(e,t,n,o)=>{np(e,t,{stateSet:n,previewKind:"tool",iconColor:JM(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},ey=(e,t,n=new Set)=>{t=rp(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Jd("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 qr(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??zr.expandable,c=l&&n.has(e.id),{summary:d,previewText:p,isActive:f}=sB(e,t),m=Zd({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=v("div","persona-flex persona-flex-col persona-text-left"),h=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(h.style.color=r.headerTextColor);let b=String(o.startedAt??Date.now()),C=()=>{let x=v("span","");return x.setAttribute("data-tool-elapsed",b),x.textContent=Wl(o),x},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:d,previewText:p,collapsedMode:i.collapsedMode??zr.collapsedMode,isActive:f,config:t??{},elapsed:Wl(o),createElapsedElement:C});typeof A=="string"&&A.trim()?(h.textContent=A,g.appendChild(h)):A instanceof HTMLElement?g.appendChild(A):(h.textContent=d,g.appendChild(h));let S=i.loadingAnimation??zr.loadingAnimation,E=r.activeTextTemplate,k=r.completeTextTemplate,D=f?E:k,z=A instanceof HTMLElement,Y=(x,P)=>{h.textContent="";let I=o.name?.trim()||"tool",J=up(x,I),_=0;for(let j of J){let te=j.styles.length>0?(()=>{let K=v("span",j.styles.map(X=>`persona-tool-text-${X}`).join(" "));return h.appendChild(K),K})():h;if(j.isDuration&&f)te.appendChild(C());else{let K=j.isDuration?Wl(o):j.text;P?_=Fs(te,K,_):te.appendChild(document.createTextNode(K))}}};if(!z)if(f&&S!=="none"){let x=r.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),S==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${x}ms`),D&&Y(D,!1);else if(h.classList.add(`persona-tool-loading-${S}`),h.style.setProperty("--persona-tool-anim-duration",`${x}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),D)Y(D,!0);else{let P=h.textContent||d;h.textContent="",Fs(h,P,0)}}else D&&Y(D,!1);let T=JM(r,Es(t,"tool")==="row"),W=ba(m,g,{expandable:l,expanded:c,iconColor:T,metaGap:!0}),L=ep({bubble:s,previewKind:"tool",expanded:c,isActive:f,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:p,isActive:f,config:t??{}})});if(!l)return s.append(m,L),qr(s,e,t,"tool");let w=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=c?"":"none",r.contentBackgroundColor&&(w.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(w.style.color=r.contentTextColor),r.contentPaddingX&&(w.style.paddingLeft=r.contentPaddingX,w.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(w.style.paddingTop=r.contentPaddingY,w.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)XM(w,e,t);else{if(o.name){let x=v("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?x.style.color=r.contentTextColor:r.headerTextColor&&(x.style.color=r.headerTextColor),x.textContent=o.name,w.appendChild(x)}if(o.args!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Arguments";let I=v("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",Jh(I,r),I.textContent=tr(o.args),x.append(P,I),w.appendChild(x)}if(o.chunks&&o.chunks.length){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Activity";let I=v("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",Jh(I,r),I.textContent=o.chunks.join(""),x.append(P,I),w.appendChild(x)}if(o.success===!1&&w.appendChild(F("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 x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Result";let I=v("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",Jh(I,r),I.textContent=tr(o.result),x.append(P,I),w.appendChild(x)}if(o.status==="complete"&&typeof o.duration=="number"){let x=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(x.style.color=r.contentTextColor),x.textContent=`Duration: ${o.duration}ms`,w.appendChild(x)}}return tp({expanded:c,header:m,toggleIcon:W,content:w,collapsedPreview:L,iconColor:T}),s.append(m,L,w),qr(s,e,t,"tool")};gp();Nl();Gr();Bn();var{setLoader:Hz,load:uB,provide:Rz,getSync:fB}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(aT(),iT))});var lT=uB;var cT=fB;Ai();Bn();var{setLoader:Yz,load:HB}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(wT(),CT))});var dy=HB;Bn();Pc();Si();Gd();var Sy=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:aj,load:mD,provide:lj,getSync:gD}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(YT(),GT))}),Ga=null,af=new Set,XT=e=>{if(Ga)return Ga;Ga=e,e.initArtifactsUi({componentRegistry:sr});for(let o of Sy)sr.has(o)||sr.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Oo();t?e.__provideMarkdownParsers(t):va(()=>{let o=Oo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Kd());let n=[...af];af.clear();for(let o of n)try{o()}catch{}return e};var lf=()=>mD().then(XT);var ts=()=>{if(Ga)return Ga;let e=gD();return e?XT(e):null},Ay=e=>Ga?()=>{}:(af.add(e),()=>{af.delete(e)});function po(e){return e?.features?.artifacts?.enabled===!0}function QT(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"),!po(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 hD(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 JT=["panel","seamless","detached"];function My(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&JT.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Ty(e){return!e||!po(e)?!1:My(e)==="detached"}function _c(e,t){if(!po(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"),hD(e),QT(e,t);return}let n=t.features?.artifacts?.layout,o=My(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 i=[[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,c]of i){let d=l?.trim();d?e.style.setProperty(c,d):e.style.removeProperty(c)}QT(e,t)}function Oc(e,t){for(let l of JT)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"),!po(t))return;let n=t.features?.artifacts?.layout,o=My(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 i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function ZT(e,t){return!t||!po(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Hl();Hl();var yD=new Set(["__proto__","prototype","constructor"]),bD=new Set(["collapsed","card","panel","inline"]),eE=new Set(["markdown","component"]),vD=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Vi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),df=e=>!yD.has(e),Ey=e=>typeof e=="string"&&bD.has(e),$i=e=>Object.keys(e).length>0;function Ar(e,t,n,o){e.push({path:t,code:n,message:o})}var CD="Ignored because this key is not part of the persisted preference schema.",cf="Ignored an unsupported value.",wD="Expected collapsed, panel, or inline.",xD='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',tE={kind:"mode",message:cf},Ya={kind:"string",message:"Expected a CSS length string."},ns={kind:"boolean"},SD={paneWidth:Ya,paneMaxWidth:Ya,paneMinWidth:Ya,expandedPanelWidth:Ya,resizableMinWidth:Ya,resizableMaxWidth:Ya,expandLauncherPanelWhenOpen:ns,resizable:ns},AD={kind:"object",message:"Expected a preference object.",children:{showToolCalls:ns,showReasoning:ns,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cf},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cf},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cf},expandable:ns,grouped:ns}},reasoningDisplay:{kind:"object",children:{expandable:ns,activePreview:ns}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:tE,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:tE,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:eE,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:eE}}},filePreview:{kind:"object",children:{enabled:ns}},layout:{kind:"object",children:SD}}}}};function nE(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Ar(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Ar(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Ar(o,n,"invalid_value",t.message);case"mode":return Ey(e)?No(e):Ar(o,n,"invalid_value",t.message);case"modeMap":{if(!Vi(e))return Ar(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let c=r?i:wa(i);df(i)&&(r?r.has(i):vD.test(c))?Ey(l)?s[c]=No(l):Ar(o,`${n}.${i}`,"invalid_value",wD):Ar(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":xD)}return $i(s)?s:void 0}case"object":{if(t.bareMode&&Ey(e))return No(e);if(!Vi(e))return Ar(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))(!df(l)||!r.includes(l))&&Ar(o,s(l),"unknown_key",CD);let i={};for(let l of r){let c=t.children[l],d=nE(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&Ar(o,s(l),"deprecated_key",c.deprecated),d===void 0)continue;let p=c.alias??l,f=i[p];i[p]=Vi(f)&&Vi(d)?{...f,...d}:d}return $i(i)?i:void 0}}}function MD(e){let t=[];return{preferences:(e===null?void 0:nE(e,AD,"",t))??{},issues:t}}function Xa(e){if(Array.isArray(e))return e.map(Xa);if(!Vi(e))return e;let t={};for(let[n,o]of Object.entries(e))df(n)&&o!==void 0&&(t[n]=Xa(o));return t}function oE(e,t){let n=Xa(e);for(let[o,r]of Object.entries(t)){if(!df(o)||r===void 0)continue;let s=n[o];n[o]=Vi(s)&&Vi(r)?oE(s,r):Xa(r)}return n}function TD(e){let t={},n;for(let r of e){let s=MD(r).preferences;n=rE(n,s.artifacts?.display),t=oE(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function ED(e,t){if(t===void 0)return e===void 0?void 0:Xa(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}:{},...$i(r)?{byMediaType:r}:{}};return $i(s)?s:void 0}function rE(e,t){if(t===void 0)return e===void 0?void 0:Xa(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=ED(n.files,t.files),i={...o?{default:o}:{},...$i(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return $i(i)?i:void 0}function kD(e={},t){let n=TD(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 i=rE(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}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 ky(e){let t=e.preferences;return!t||!$i(t)?e:{...e,features:kD(e.features??{},[t])}}function LD(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 PD(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 ID(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function HD(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Ly(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 sE(e,t,n,o,r,s,i=200){let l=LD(r,200),c=HD(t,n,o,i);c=Math.max(l,c);let d=PD(s);return d!==null&&(c=Math.min(c,d)),ID(e,l,c)}Bn();var{setLoader:bj,load:RD,provide:vj,getSync:WD}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(cE(),lE))});var dE=RD;var pE=WD;var Py=class{#e=new Map;register(t){this.#e.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.#e.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.#e.get(t);n&&(n.onUnregister?.(),this.#e.delete(t))}getAll(){return Array.from(this.#e.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,i)=>(i.priority??0)-(s.priority??0))}clear(){this.#e.forEach(t=>t.onUnregister?.()),this.#e.clear()}},Iy=new Py;er();er();ha();Nm();var uE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BD=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),fE=(e,t,n)=>{if(!uE(e)||!uE(t)||BD.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]=fE(e[r],t[r],s)}return o};function mE(e,t){let n=$d(Ci),o=wC(e,t,n),r=_m(xC(fE(e,t,""),n,o),o);return Vm(jd(r),AC(e,t))}ha();var gE=()=>{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(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var DD=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},_D=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},Ry=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=DD(e),n=_D(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}},Hy=e=>typeof e=="string"?e:e==null?"":String(e),Nc={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Hy(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Hy(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:Hy(n.text)}}},hE=e=>Array.isArray(e)?e.map(t=>String(t)):[],Wy=e=>{let t=new Set(hE(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(hE(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&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=i?e.parsers.reduce((d,p)=>d||p?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let c={action:l,message:s.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let p=()=>{e.emit("action:resubmit",c)},f=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let m=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:m,resubmit:f.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var OD=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}},ND=e=>e.map(t=>({...t,streaming:!1})),FD=e=>e.map(t=>({...t,status:"complete"})),yE=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?OD(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ND(n.messages):void 0,artifacts:n.artifacts?FD(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 VD=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")},bE=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 VD(e)},$D=async(e,t)=>{let n=await bE(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await bE(`${e}\0${t}`)}`}};var vE=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,c=0,d=null,p=null,f=new Set,m=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},g=()=>{let T=m();if(!T)return d;try{return T.getItem(o)}catch{return i=!0,d}},h=(T,W)=>{if(l||T===d)return;let L=d;d=T,c+=1;let w={previousToken:L,token:T,source:W,revision:c};for(let x of f)x(w)},b=T=>{l||T.key!==null&&T.key!==o||h(T.key===null?null:T.newValue??null,"external")},C=(async()=>{let T=await $D(e,t);o=T.storageKey,r=T.leaseKey,s=T.lockName,d=g(),!n&&typeof window<"u"&&window.addEventListener("storage",b)})(),A=T=>new Promise(W=>setTimeout(W,T)),S=()=>{let T=m();if(!T)return null;try{let W=T.getItem(r);if(!W)return null;let L=JSON.parse(W);return typeof L?.expiresAt=="number"&&typeof L?.ownerNonce=="string"?L:null}catch{return null}},E=T=>{let W=m();if(W)try{S()?.ownerNonce===T&&W.removeItem(r)}catch{}},k=new Set,D=T=>l?Promise.reject(new Error("Visitor store destroyed before its first init could start")):T(),z=T=>new Promise(W=>{let L=setTimeout(w,T);function w(){clearTimeout(L),k.delete(w),window.removeEventListener("storage",x),W()}function x(P){(P.key===null||P.key===r)&&w()}k.add(w),window.addEventListener("storage",x)}),Y=async T=>{let W=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,L=Date.now()+15e3;for(;!l&&Date.now()<L;){let w=m();if(!w)break;let x=Date.now(),P=S();if(P&&P.expiresAt>x&&P.ownerNonce!==W){await z(Math.min(P.expiresAt-x,500));continue}try{w.setItem(r,JSON.stringify({ownerNonce:W,expiresAt:x+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),S()?.ownerNonce!==W){await z(500);continue}p=W;try{return await D(T)}finally{p=null,E(W)}}return D(T)};return{ready:C,async get(){return await C,h(g(),"external"),d},async set(T){await C;let W=m();if(W)try{W.setItem(o,T)}catch{i=!0}h(T,"local")},async clear(){await C;let T=m();if(T)try{T.removeItem(o)}catch{i=!0}h(null,"local")},revision(){return c},subscribe(T){return f.add(T),()=>{f.delete(T)}},async withFirstInitLock(T){await C;let W=globalThis.navigator?.locks;return W?.request?W.request(s,()=>D(T)):m()?Y(T):D(T)},matches(T,W,L){return T===e&&W===t&&L===n},destroy(){l=!0,f.clear(),typeof window<"u"&&window.removeEventListener("storage",b),p&&E(p);for(let T of[...k])T()}}};Bn();var{setLoader:u5,load:g_}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(OE(),_E))});var NE=g_;Bn();var{setLoader:A5,load:C_,provide:M5,getSync:w_}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(KE(),jE))});var GE=C_;var hf=w_;var x_=null;function YE(){return x_}Pc();Pc();var Ky=require("partial-json");Ge();function XE(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=sr.get(e.component);if(!s){if(Sy.includes(e.component)){lf().catch(()=>{});let l=v("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 i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function QE(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 Gy(e){let t=QE(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 JE(e){let t=QE(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 S_=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ZE(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:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:d=S_}=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 f=null,m=document.createElement("div");m.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,g.appendChild(h);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=r,g.appendChild(b),m.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let z=1;z<=5;z++){let Y=document.createElement("button");Y.type="button",Y.className="persona-feedback-rating-btn persona-feedback-star-btn",Y.setAttribute("role","radio"),Y.setAttribute("aria-checked","false"),Y.setAttribute("aria-label",`${z} star${z>1?"s":""}: ${d[z-1]}`),Y.title=d[z-1],Y.dataset.rating=String(z),Y.innerHTML=`
1189
1189
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1190
1190
  <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>
1191
1191
  </svg>
1192
- `,Y.addEventListener("click",()=>{f=z,A.forEach((T,W)=>{let L=W<z;T.classList.toggle("selected",L),T.setAttribute("aria-checked",W===z-1?"true":"false")})}),A.push(Y),C.appendChild(Y)}m.appendChild(C);let S=null;if(c){let z=document.createElement("div");z.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),z.appendChild(S),m.appendChild(z)}let E=document.createElement("div");E.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=l,k.addEventListener("click",()=>{n?.(),p.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=i,D.addEventListener("click",async()=>{if(f===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let z=S?.value.trim()||void 0;await t(f,z),p.remove()}catch(z){D.disabled=!1,D.textContent=i,console.error("[CSAT Feedback] Failed to submit:",z)}}),E.appendChild(k),E.appendChild(D),m.appendChild(E),p.appendChild(m),p}function ZE(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:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:p="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,h.appendChild(C),g.appendChild(h);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=d;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,S.appendChild(E),S.appendChild(k);let D=document.createElement("div");D.className="persona-feedback-numbers";let z=[];for(let w=0;w<=10;w++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-number-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`Rating ${w} out of 10`),x.textContent=String(w),x.dataset.rating=String(w),w<=6?x.classList.add("persona-feedback-detractor"):w<=8?x.classList.add("persona-feedback-passive"):x.classList.add("persona-feedback-promoter"),x.addEventListener("click",()=>{m=w,z.forEach((P,I)=>{P.classList.toggle("selected",I===w),P.setAttribute("aria-checked",I===w?"true":"false")})}),z.push(x),D.appendChild(x)}A.appendChild(S),A.appendChild(D),g.appendChild(A);let Y=null;if(c){let w=document.createElement("div");w.className="persona-feedback-comment-container",Y=document.createElement("textarea"),Y.className="persona-feedback-comment",Y.placeholder=s,Y.rows=3,Y.setAttribute("aria-label","Additional comments"),w.appendChild(Y),g.appendChild(w)}let T=document.createElement("div");T.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=l,W.addEventListener("click",()=>{n?.(),f.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=i,L.addEventListener("click",async()=>{if(m===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=Y?.value.trim()||void 0;await t(m,w),f.remove()}catch(w){L.disabled=!1,L.textContent=i,console.error("[NPS Feedback] Failed to submit:",w)}}),T.appendChild(W),T.appendChild(L),g.appendChild(T),f.appendChild(g),f}var Qa="persona-chat-history",M_=30*1e3,T_="Tap the mic to resume your voice call",E_=641,Ja="data-persona-composer-reason",qc="data-persona-composer-notice",k_={"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 L_(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=k_[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 yf(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 P_(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 I_(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Yy=e=>!e||typeof e!="object"?{}:{...e},e0=e=>e.map(t=>({...t,streaming:!1})),t0=(e,t,n)=>{let o=e?.markdown?ip(e.markdown):null,r=lp(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,i=l=>{let c=l.text??"",d=l.message.rawContent??null;if(t){let m=t.process({text:c,raw:d??c,message:l.message,streaming:l.streaming});m!==null&&(c=m.text,m.persist||(l.message.__skipPersist=!0),m.resubmit&&!l.streaming&&n&&n())}let p=Oo()!==null,f;if(e?.postprocessMessage){let m=e.postprocessMessage({...l,text:c,raw:d??l.text??""});f=r?r(m):m}else if(o){let m=l.streaming?UC(c):c,g=o(m);f=r&&p?r(g):g}else f=jr(c);return f};return l=>{try{return i(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),jr(l.text??"")}}};function n0(e){let t=v("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,i=We(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var H_=(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},R_=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:H_(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),o0=(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=jd(t),r=new Set,s=new Set,i=PC((a,u)=>{Yn.delete(a);let y=Array.from($e.querySelectorAll("[data-message-id]")).find(M=>M.dataset.messageId===a);y&&(u==="tool"?Zh(a,y,r,o):Yh(a,y,s))}),l=new Map,c=()=>{yx({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let d=o.features;o=ky(o);let p=Iy.getForInstance(o.plugins),f=OA(e),m=[],g=!1,h=KM(()=>o),b=null,C=null,A=null,S=!1,E=null,k=a=>{b=a,a.initApprovalUi({webMcpToolTitle:cp});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},D=()=>{if(b)return b;let a=lT();return a?(k(a),a):(aT().then(u=>{S||b||(k(u),E?.())}).catch(()=>{}),null)},z=!1,Y=!1,T=null,W=(a,u,y,M)=>{if(!a.querySelector("[data-tv-form]"))return;let H=dE();if(H){H.enhanceWithForms(a,u,y,M);return}cE().then(()=>{z||Y||!T||(Y=!0,T())}).catch(()=>{})};o.components&&sr.registerAll(o.components);let L=mE(),x=o.persistState===!1?null:o.storageAdapter??hE(),P=!!o.clientToken&&typeof o.reconnectStream!="function",I={},J=null,_,j=new Promise(a=>{_=a}),te=()=>{},K=new Promise(a=>{te=a}),X,oe=!1,de=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:y,open:M}=u;return M&&(oe=!0),y}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(x?.load)try{let a=x.load();if(a&&typeof a.then=="function")J=a.then(u=>de(u??{messages:[],metadata:{}}));else{let y=de(a??{messages:[],metadata:{}});y.metadata&&(I=Yy(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null}),X=y.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=de({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}J||_();let xe=()=>I,Te=a=>{I=a({...I})??{},na()},re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ry],N=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Nc.message,Nc.messageAndClick],ke=Wy({parsers:re,handlers:N,getSessionMetadata:xe,updateSessionMetadata:Te,emit:L.emit,documentRef:typeof document<"u"?document:null});ke.syncFromMetadata();let ve=o.launcher?.enabled??!0,tt=o.launcher?.autoExpand??!1,xt=o.autoFocusInput??!1,ht=tt,lt=ve,Ye=o.layout?.header?.layout,dt=!1,Pe=()=>Cc(o),Se=()=>ve||Pe(),U=Pe()?!1:ve?tt:!0,R=!1,G=null,ne=()=>{R=!0,G&&clearTimeout(G),G=setTimeout(()=>{R&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),R=!1)},1e4)},Z=t0(o,ke,ne),le=o.features?.showReasoning??!0,Me=o.features?.showToolCalls??!0,Ie=o.features?.showEventStreamToggle??!1,_e=o.features?.scrollToBottom??{},ct=o.features?.scrollBehavior??{},Tt=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",nt=`${Tt()}event-stream`,Ut=null,tn=o.features?.eventStream?.maxEvents??2e3,ee=null,Re=null,Fe=null,yt=!1,bt=null,Ee=!1,He=null,je=0,It=(a,u)=>{ee?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},wn=(a,u)=>{Re?.processEvent(a,u),ee?It(a,u):Fe&&(Fe.length>=tn&&Fe.shift(),Fe.push({type:a,payload:u}))},nn=()=>{ee||!Ie||(Fe??=[],dy().then(a=>{if(yt||ee||!Ie)return;Ut=new a.EventStreamStore(nt),ee=new a.EventStreamBuffer(tn,Ut),Re=Re??new a.ThroughputTracker,Ut.open().then(()=>ee?.restore()).catch(y=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",y)});let u=Fe??[];Fe=null;for(let y of u)Re?.processEvent(y.type,y.payload),It(y.type,y.payload)}).catch(()=>{}))};Ie&&nn();let Ot=!1,mt=null,Ht=()=>{},St=()=>{},Kt=()=>{},gn=()=>{},Zn=()=>{},ss=()=>Ee||Ot&&mt==="panel",jn={onCopy:a=>{L.emit("message:copy",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{L.emit("message:feedback",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},qs=o.statusIndicator??{},oo=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Cn.idle:a==="connecting"?u.connectingText??Cn.connecting:a==="connected"?u.connectedText??Cn.connected:a==="error"?u.errorText??Cn.error:a==="paused"?u.pausedText??Cn.paused:a==="resuming"?u.resumingText??Cn.resuming:Cn[a];function Tr(a,u,y,M){if(!Pe()&&(y.mode==="transient"||a.classList.contains("persona-mb-2"))&&(Ym(a,Pn,y),xi(a,y,M)),!(a.hasAttribute(Ja)||a.hasAttribute(qc)))if(M==="idle"&&y.idleLink){a.textContent="";let H=document.createElement("a");H.href=y.idleLink,H.target="_blank",H.rel="noopener noreferrer",H.textContent=u,H.style.color="inherit",H.style.textDecoration="none",a.appendChild(H)}else a.textContent=u}let At=jM({config:o,showClose:Se()}),{wrapper:ot,panel:Ve,pillRoot:cn}=At.shell,wt=At.panelElements,{container:Be,body:ye,messagesWrapper:$e,starterSuggestions:uo,transcriptSuggestions:fo,suggestions:eo,textarea:we,sendButton:ze,composerForm:Pn,statusText:Mt,welcomeHost:$,welcomeIconHolder:me,greetingHost:Ne,introKicker:ft,introTitle:pt,introSubtitle:An,closeButton:Ze,iconHolder:Nt,headerTitle:mo,headerSubtitle:ir,header:Vt,footer:gt,actionsRow:zi}=wt,Kn=wt.leftActions,js=wt.rightActions,ro=wt.sendButtonWrapper,Kc=wt.setSendButtonMode,De=wt.micButton,Dn=wt.micButtonWrapper,Zt=wt.attachmentButton,In=wt.attachmentButtonWrapper,Gt=wt.attachmentInput,_n=wt.attachmentPreviewsContainer;Be.classList.add("persona-relative"),ye.classList.add("persona-relative");let Gc=12,is=()=>_e.label??"",vf=()=>_e.iconName??"arrow-down",Cf=()=>_e.enabled!==!1,Gn=()=>ct.mode??"anchor-top",zo=()=>Gn()==="follow"||Gn()==="anchor-top"&&dl,Ks=()=>ct.anchorTopOffset??16,Yc=()=>ct.restorePosition??"bottom",el=()=>ct.pauseOnInteraction===!0,tl=()=>ct.showActivityWhilePinned!==!1,qi=()=>ct.announce===!0,Gs=()=>ct.scrollbar??"on-scroll",fn=v("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");fn.type="button",fn.style.display="none",fn.setAttribute("data-persona-scroll-to-bottom","true");let Ys=v("span","persona-flex persona-items-center"),nl=v("span",""),Mn=v("span","");Mn.setAttribute("data-persona-scroll-to-bottom-count",""),Mn.style.display="none",fn.append(Ys,nl,Mn),Be.appendChild(fn);let xn=v("div","persona-stream-anchor-spacer");xn.setAttribute("aria-hidden","true"),xn.setAttribute("data-persona-anchor-spacer",""),xn.style.flexShrink="0",xn.style.pointerEvents="none",xn.style.height="0px",xn.style.display="none",ye.appendChild(xn);let qo=v("div","persona-sr-only");qo.setAttribute("aria-live","polite"),qo.setAttribute("aria-atomic","true"),qo.setAttribute("role","status"),qo.setAttribute("data-persona-live-region",""),Object.assign(qo.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"}),Be.appendChild(qo);let as=null,Er=null,Xs=a=>{!qi()||!a||(Er=a,as===null&&(as=setTimeout(()=>{as=null,Er&&qi()&&(qo.textContent=Er),Er=null},400)))},go=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(ve||un(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!un(o)},B=()=>Ku(o,go()),Q="empty",fe=0,Le=()=>fe||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Xe=()=>{let u=gt.style.display==="none"?0:gt.offsetHeight;fn.style.bottom=`${u+Le()+Gc}px`};Xe();let dn=()=>{Qi||(gt.style.marginBottom=fe>0?`${fe}px`:"")},on=()=>{let a=vh(o,Pe()),u=B();e.setAttribute("data-persona-welcome-fullscreen",String(go())),e.setAttribute("data-persona-welcome-layout",u.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom");let M=gt.style.display==="none"?0:gt.offsetHeight,H=u.anchor==="center"&&Q==="empty"?cc(u.anchorComposerTop)??cc("44%"):null,O=H!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,se=O?getComputedStyle(ye):null,ge=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,ce=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,be=Math.max(0,(parseFloat(se?.paddingBottom??"")||0)-(a==="overlay"?ge+ce:0)),Ce=O?ye.getBoundingClientRect().top-Be.getBoundingClientRect().top:0,Ae=!O||$.hidden?0:($.querySelector("[data-persona-welcome-plugin]")??$).offsetHeight,Ke=H===null||Pe()?0:O?Math.max(0,Math.round((Be.clientHeight-Ce-Ae-be-M)/2)):BA({columnHeight:Be.clientHeight,footerHeight:M,fraction:H});e.style.setProperty("--persona-composer-overlay-height",`${M}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?Ke:0}px`),fe=a==="block"?Ke:0,dn(),Xe()},rn=()=>{let a=!!is();fn.setAttribute("aria-label",is()||"Jump to latest"),fn.title=is(),fn.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ys.innerHTML="";let u=We(vf(),"14px","currentColor",2);u?(Ys.appendChild(u),Ys.style.display=""):Ys.style.display="none",nl.textContent=is(),nl.style.display=a?"":"none"};rn();let ut=null,Rt=null,Oe=XS(),ji=a=>{try{Be.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};Oe.subscribe(ji);let ko=()=>{Oe.setText(we?.value??"")},kr=()=>{Oe.setMentionRefs(Rt?.getMentionRefs()??[])},h0=a=>({id:a.id,name:a.file.name,mimeType:a.file.type,size:a.file.size,status:a.status,progress:a.progress,error:a.error}),nb=a=>{let u=Object.freeze(a.map(h0));Oe.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(y){console.error("[AgentWidget] attachments.onChange failed:",y)}Zf()};Oe.setSelectedModelId(o.composer?.selectedModelId);let ol=()=>o.composer?.modes??[],Ki=()=>uA(ol(),o.composer?.modeGroups);{let a=vu(o.composer?.defaultActiveModeIds??[],ol());a.length&&Oe.setActiveModeIds(a)}function ob(a){if(Oe.getState().selectedModelId!==a){Oe.setSelectedModelId(a),ls?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function Xc(a){Oe.setActiveModeIds(a),Lr?.render(a,Ki()),Gi.forEach(u=>u.repaint()),jo?.resolve(),Sd(),Ko()}function wf(a){Xc(fA(Oe.getState().activeModeIds,a,ol(),o.composer?.modeGroups))}let ls=null,xf=null,Lr=null,Gi=new Map,cs=null;function ar(a){Oe.setQuote(a),cs?.render(Oe.getState().quote),Ko(),Xb()}let rb=!1;function Sf(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!rb&&o.debug===!0&&(rb=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ds=null;function Yi(a){Oe.setPendingSubmission(a),ds?.render(Oe.getState().pendingSubmission),Ko()}let y0=a=>{let u=Gi.get(a);if(u)return u;let y=hA({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(M=>M.id===a),getModes:()=>ol().filter(M=>M.groupId===a),getActiveIds:()=>Oe.getState().activeModeIds,onSelect:M=>wf(M)});return Gi.set(a,y),y},b0=()=>{let a=[],u=Oe.getState().activeModeIds,y=new Set;if(ol().forEach((M,H)=>{if(bu(M.groupId,o.composer?.modeGroups)){let O=M.groupId;if(y.has(O))return;y.add(O);let se=y0(O);se.action.order=uh(H),se.action.label=o.composer?.modeGroups?.find(ge=>ge.id===O)?.label??O,a.push(se.action);return}a.push({id:dA(M.id),kind:"button",placement:"start",order:uh(H),presentation:M.presentation??"auto",label:M.label,shortLabel:M.shortLabel,iconName:M.iconName,pressed:u.includes(M.id),onSelect:()=>wf(M.id)})}),o.composer?.models?.length&&!p.some(M=>M.renderComposer)){let M=o.composer?.modelPicker?.presentation??"native";(!ls||xf!==M)&&(xf=M,ls=lA({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Oe.getState().selectedModelId,onSelect:H=>ob(H),presentation:M,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push(ls.action)}return a},Af=null,sb=p.find(a=>a.renderHeader);if(sb?.renderHeader){let a=sb.renderHeader({config:o,defaultRenderer:()=>{let u=Ii({config:o,showClose:Se()});return xc(Be,u,o),u.header},onClose:()=>Yt(!1,"user")});if(a){let u=Vt;u&&(u.replaceWith(a),Vt=a,At.header.element=a)}}let ib=()=>{bt&&(ye.style.display="none",gt.parentNode?.insertBefore(bt.element,gt),bt.update())},Mf=()=>{if(!ee){nn();return}if(Ee=!0,bt?ib():dy().then(u=>{bt||!Ee||!ee||(bt=u.createEventStreamView({buffer:ee,getFullHistory:()=>ee.getAllFromStore(),onClose:()=>Xi(),config:o,plugins:p,getThroughput:()=>Re?.getMetric()??{status:"idle"},renderIconByName:We}),ib())}).catch(()=>{Xi()}),$t){$t.style.boxShadow=`inset 0 0 0 1.5px ${lo.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(y=>y&&$t.classList.add(y))}let a=()=>{if(!Ee)return;let u=Date.now();u-je>=200&&(bt?.update(),je=u),He=requestAnimationFrame(a)};je=0,He=requestAnimationFrame(a),Xn(),L.emit("eventStream:opened",{timestamp:Date.now()})},Xi=()=>{if(Ee){if(Ee=!1,bt&&bt.element.remove(),ye.style.display="",$t){$t.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&$t.classList.remove(u))}He!==null&&(cancelAnimationFrame(He),He=null),Xn(),L.emit("eventStream:closed",{timestamp:Date.now()})}},$t=null;if(Ie){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");$t=v("button",u),$t.style.width="28px",$t.style.height="28px",$t.style.color=lo.actionIconColor,$t.type="button",$t.setAttribute("aria-label","Event Stream"),$t.title="Event Stream";let y=Je(rs.Activity,"18px","currentColor",1.5);y&&$t.appendChild(y);let M=wt.clearChatButtonWrapper,H=wt.closeButtonWrapper,O=M||H;O&&O.parentNode===Vt?Vt.insertBefore($t,O):Vt.appendChild($t),$t.addEventListener("click",()=>{Ee?Xi():Mf()})}let ab=a=>{let u=o.attachments;if(!u?.enabled)return;let y=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!y){y=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let H=a.querySelector("[data-persona-composer-form]");H?.parentNode?H.parentNode.insertBefore(y,H):a.insertBefore(y,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let H=v("input");H.type="file",H.setAttribute("data-persona-composer-attachment-input",""),H.accept=(u.allowedTypes??Qr).join(","),H.multiple=(u.maxFiles??4)>1,H.style.display="none",H.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(H)}},Qi=!1,lb=a=>{let u=p.find(H=>H.renderComposer);if(!u?.renderComposer)return null;let y=o.composer,M=g?V.isStreaming():!1;return u.renderComposer({config:o,defaultRenderer:a,requestRender:()=>sC(),storage:h(u.id),onSubmit:H=>{!V||V.isStreaming()||Hd(H.trim(),{consumeDraft:!1})},streaming:M,disabled:M,openAttachmentPicker:()=>{pr()||Gt?.click()},models:y?.models,selectedModelId:Oe.getState().selectedModelId??y?.selectedModelId,onModelChange:H=>ob(H),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Af?.()}:void 0})},cb=lb(()=>Ac({config:o}).footer);cb&&(At.replaceComposer(cb),gt=At.composer.footer,Qi=!0);let Bt=null,v0=a=>{Pn=a.form,we=a.input,ro=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(ze=a.sendButton),a.micButton&&(De=a.micButton,Dn=a.micButton.parentElement),a.found.status&&(Mt=a.found.status),a.found.suggestions&&(eo=a.found.suggestions),a.attachmentButton&&(Zt=a.attachmentButton,In=a.attachmentButton.parentElement),Gt=a.attachmentInput??null,_n=a.attachmentPreviews??null,a.found.actionsRow&&(zi=a.found.actionsRow),Kn=a.found.actionsStart,js=a.found.actionsEnd};function Tf(){let a=we;if(!a)return;let u=o.composer?.inputAttributes,y=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Rp(a,u),y&&a.setAttribute("aria-label",y),Hp(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(a)}),Cx(a,Ip(o.composer?.maxLines,Pe()?5:3))}let db=a=>{Bt=JS(a,{debug:o.debug===!0}),Bt&&v0(Bt),Tf()};ab(gt),db(gt),ko();let rl=Os(o,Pe());rl&&($e.style.maxWidth=rl,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ne.style.maxWidth=rl,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%",uo.style.maxWidth=rl,fo.style.maxWidth=rl,fo.style.marginLeft="auto",fo.style.marginRight="auto",fo.style.width="100%");let pb=()=>{let a=Os(o,Pe());if(!(!a||Pe()))for(let u of[Pn,eo,_n,Mt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};pb();let ub=()=>{!o.attachments?.enabled||!Gt||!_n||(ut?ut.remountPreviews(_n):(ut=rc.fromConfig(o.attachments,nb),ut.setPreviewsContainer(_n)),Bt?.addListener(Gt,"change",a=>{let u=a.target;ut?.handleFileSelect(u.files),u.value=""}),Be.querySelector(".persona-attachment-drop-overlay")||Be.appendChild(n0(o.attachments.dropOverlay)))};ub();let C0=()=>Rt?.prefetch(),Ef=()=>{if(!o.contextMentions?.enabled||!we)return;let a=qg();if(!a){let M=we;iu().then(()=>{Rt||we!==M||!M.isConnected||(Ef(),jo?.resolve())},()=>{});return}let u=Bt?.header??null,y=u?Pg(u):void 0;if(Rt=a.createContextMentionOrchestrator({deps:{loadContextMentions:Zp,loadContextMentionsInline:su,renderLucideIcon:We,createMentionButton:Vp},config:o,textarea:we,anchor:Pn??we,getMessages:()=>V.getMessages(),liveRegionHost:Be,chipRow:y}),Rt&&!y){let M=we;M.parentElement?.insertBefore(Rt.contextRow,M)}};Ef();let jo=null,w0={getState:()=>Oe.getState(),getValue:()=>we?.value??"",setValue:a=>{we&&(we.value=a,we.dispatchEvent(new Event("input",{bubbles:!0})),ko())},submit:()=>{Gl(Bt?.form??null)},openAttachmentPicker:()=>{pr()||Gt?.click()},toggleVoice:()=>{Af?.()},requestRender:()=>jo?.resolve()},x0=()=>{let a=[];return(Rt?.affordanceButtons??[]).forEach((y,M)=>{a.push({id:`core:mention-${M}`,placement:"start",order:wr.mention+M,element:y,managed:!0})}),In&&a.push({id:"core:attachment",placement:"start",order:wr.attachment,element:In}),Dn&&a.push({id:"core:mic",placement:"end",order:wr.mic,element:Dn}),ro&&a.push({id:"core:send",placement:"end",order:wr.send,element:ro}),a},fb=()=>{jo?.destroy(),jo=sA({getBindings:()=>Bt,collect:()=>({builtIns:x0(),configActions:[...b0(),...o.composer?.actions??[]],plugins:p,contributionContext:{config:o,getState:()=>Oe.getState(),requestRender:()=>jo?.resolve()},debug:o.debug===!0}),actionContext:w0,getState:()=>Oe.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),jo.resolve()};fb();let kf=()=>{if(Lr?.destroy(),Lr=null,!Ki().length)return;let a=Bt?.header;a&&(Lr=cA({row:Pg(a),onRemove:u=>wf(u),initialIds:Oe.getState().activeModeIds}),Lr.render(Oe.getState().activeModeIds,Ki()))};kf();let mb=()=>{cs?.destroy(),cs=null,ds?.destroy(),ds=null;let a=Bt?.header;a&&(cs=yA({onDismiss:()=>ar(void 0)}),a.appendChild(cs.element),cs.render(Oe.getState().quote),Sf()==="defer-one"&&(ds=bA({onEdit:()=>bk(),onRemove:()=>Yi(void 0)}),a.appendChild(ds.element),ds.render(Oe.getState().pendingSubmission)))};mb();let Lf=AA(),S0=()=>{let a=Bt?.header?.querySelector(Lg);if(a)return a.childElementCount>0;let u=Oe.getState();return u.mentionRefs.length>0||vu(u.activeModeIds,Ki()).length>0};function Ko(){let a=Oe.getState(),u=Lf.observe(MA(we),a.text);gt.toggleAttribute("data-persona-composer-compact",SA({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:S0(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function gb(){o.composer?.layout==="single-row"&&!Pe()?gt.setAttribute("data-persona-composer-layout","single-row"):gt.removeAttribute("data-persona-composer-layout")}gb(),Oe.subscribe(()=>{jo?.sync(),Zf(),Cd(),Ko(),Xb()}),Cd();let hb=!1,A0=a=>{if(hb||o.debug!==!0)return;let u=["messages","composer"].filter(y=>a[y]);u.length&&(hb=!0,console.warn(`[persona] layout.slots.${u.join(" and layout.slots.")} ${u.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 a=o.layout?.slots??{};A0(a);let u=M=>{switch(M){case"body-top":return ye.querySelector("[data-persona-intro-card]");case"messages":return $e;case"footer-top":return eo;case"composer":return Pn;case"footer-bottom":return Mt;default:return null}},y=(M,H)=>{switch(M){case"header-left":case"header-center":case"header-right":if(M==="header-left")Vt.insertBefore(H,Vt.firstChild);else if(M==="header-right")Vt.appendChild(H);else{let O=Vt.querySelector(".persona-flex-col");O?O.parentNode?.insertBefore(H,O.nextSibling):Vt.appendChild(H)}break;case"body-top":{let O=ye.querySelector("[data-persona-intro-card]");O?O.replaceWith(H):ye.insertBefore(H,ye.firstChild);break}case"body-bottom":ye.appendChild(H);break;case"footer-top":eo.replaceWith(H);break;case"footer-bottom":Mt.replaceWith(H);break;default:break}};for(let[M,H]of Object.entries(a))if(H)try{let O=H({config:o,defaultContent:()=>u(M)});O&&y(M,O)}catch(O){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${M}":`,O)}})(),$e.addEventListener("click",a=>{let u=a.target;if(!(u instanceof Element))return;let y=u.closest("button[data-persona-copy-tool-detail]");y&&(a.preventDefault(),a.stopPropagation(),XM(y))});let Pf=a=>{let y=a.target.closest('button[data-expand-header="true"]');if(!y)return;let M=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!M)return;let H=M.getAttribute("data-message-id");if(!H)return;gs(),sa();let O=y.getAttribute("data-bubble-type");if(M.classList.contains("persona-activity-row")){i.manual(H);let se=M.parentElement?.closest("[data-persona-tool-group]");se?.dataset.messageId&&i.manual(se.dataset.messageId)}if(O==="reasoning")s.has(H)?s.delete(H):s.add(H),Yh(H,M,s);else if(O==="tool")r.has(H)?r.delete(H):r.add(H),Zh(H,M,r,o);else if(O==="approval"&&b){let ge=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",ce=l.get(H)??ge;l.set(H,!ce),b.updateApprovalDetailsUI(H,M,o,l)}Yn.delete(H)};$e.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Pf(a))}),$e.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&Pf(a)}),$e.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Pf(a))}),$e.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let y=$e.getRootNode(),M=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!M||M.isCollapsed)return;let H=M.toString(),O=FA(H);!O||O===H||(u.setData("text/plain",O),a.preventDefault())});let If=new Map,yb=null,bb="idle",M0={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},T0=(a,u)=>{let{icon:y,label:M}=M0[u];a.setAttribute("aria-label",M),a.title=M,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let H=We(y,14,"currentColor",2);H&&(a.innerHTML="",a.appendChild(H))},vb=()=>{$e.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let M=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;T0(u,M&&M===yb?bb:"idle")})};$e.addEventListener("click",a=>{let y=a.target.closest(".persona-message-action-btn[data-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.closest("[data-actions-for]");if(!M)return;let H=M.getAttribute("data-actions-for");if(!H)return;let O=y.getAttribute("data-action");if(O==="copy"){let ge=V.getMessages().find(ce=>ce.id===H);if(ge&&jn.onCopy){let ce=ge.content||"";navigator.clipboard.writeText(ce).then(()=>{y.classList.add("persona-message-action-success");let be=Je(rs.Check,14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Ce=Je(rs.Copy,14,"currentColor",2);Ce&&(y.innerHTML="",y.appendChild(Ce))},2e3)}).catch(be=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",be)}),jn.onCopy(ge)}}else if(O==="read-aloud")V.toggleReadAloud(H);else if(O==="upvote"||O==="downvote"){let ge=(If.get(H)??null)===O,ce=O==="upvote"?"thumbs-up":"thumbs-down";if(ge){If.delete(H),y.classList.remove("persona-message-action-active");let be=We(ce,14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be))}else{let be=O==="upvote"?"downvote":"upvote",Ce=M.querySelector(`[data-action="${be}"]`);if(Ce){Ce.classList.remove("persona-message-action-active");let Dt=We(be==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Dt&&(Ce.innerHTML="",Ce.appendChild(Dt))}If.set(H,O),y.classList.add("persona-message-action-active");let Ae=We(ce,14,"currentColor",2);Ae&&(Ae.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(Ae)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Pt=V.getMessages().find(Ft=>Ft.id===H);Pt&&jn.onFeedback&&jn.onFeedback({type:O,messageId:Pt.id,message:Pt})}}else if(O==="regenerate")Qc?.regenerate(H);else if(O==="edit")Qc?.edit(H);else if(O==="quote")Qc?.quote(H);else if(O?.startsWith(Uu)){let se=O.slice(Uu.length),ge=o.messageActions?.custom?.find(be=>be.id===se),ce=V.getMessages().find(be=>be.id===H);if(!ge||!ce)return;try{ge.onSelect(ce)}catch(be){console.error(`[AgentWidget] messageActions.custom "${se}" onSelect failed:`,be)}}});let Qc=null;$e.addEventListener("click",a=>{let y=a.target.closest("button[data-approval-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.closest(".persona-approval-bubble");if(!M)return;let H=M.getAttribute("data-message-id");if(!H)return;let O=y.getAttribute("data-approval-action");if(!O)return;let se=O==="approve"?"approved":"denied",ce=V.getMessages().find(Ce=>Ce.id===H);if(!ce?.approval)return;let be=M.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(Ae=>{Ae.disabled=!0,Ae.style.opacity="0.5",Ae.style.cursor="not-allowed"}),ce.approval.toolType==="webmcp"?V.resolveWebMcpApproval(H,se):V.resolveApproval(ce.approval,se)});let Et=null,Cb=!1,sl=null,Qs=()=>{},il="none",Jc=null,Lo={artifacts:[],selectedId:null},Pr=!1,Go=!1,al=!1,Ji=!1,wb=()=>Ji||Lo.artifacts.some(a=>ks(o.features?.artifacts,a)==="panel"),Zc=()=>Lo.artifacts.length>0&&!Pr&&wb(),Po={current:null},Hf=(a,u)=>{let y=V.getArtifactById(u),M=y?.markdown,H=y?.title||"artifact",O=y?.file,se=y?.artifactType??"markdown";if(!M){let be=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(be){let Ae=V.getMessages().find(Ke=>Ke.id===be);if(Ae?.rawContent)try{let Ke=JSON.parse(Ae.rawContent);M=Ke?.props?.markdown,H=Ke?.props?.title||H,Ke?.props?.file&&typeof Ke.props.file=="object"&&(O=Ke.props.file),!y&&typeof Ke?.props?.artifactType=="string"&&(se=Ke.props.artifactType)}catch{}}}return{markdown:M,title:H,file:O,artifactType:se}};$e.addEventListener("click",a=>{let y=a.target.closest("[data-download-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-download-artifact");if(!M||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:M})===!0)return;let{markdown:O,title:se,file:ge}=Hf(y,M);if(!O)return;let ce=ts();ce&&ce.triggerArtifactDownload(ce.downloadInfoFor({title:se,markdown:O,file:ge}))}),$e.addEventListener("click",a=>{let y=a.target.closest("[data-artifact-custom-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-artifact-custom-action");if(!M)return;let H=y.closest("[data-artifact-inline]"),O=H?null:y.closest("[data-open-artifact]"),se=H?H.getAttribute("data-artifact-inline"):O?.getAttribute("data-open-artifact")??null,ce=(H?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ft=>Ft.id===M);if(!ce)return;let{markdown:be,title:Ce,file:Ae,artifactType:Ke}=Hf(y,se??""),Pt={artifactId:se,title:Ce,artifactType:Ke,markdown:be,file:Ae};try{Promise.resolve(ce.onClick(Pt)).catch(()=>{})}catch{}}),$e.addEventListener("click",a=>{let y=a.target.closest("[data-copy-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-copy-artifact");if(!M)return;let H=V.getArtifactById(M),O=ts();if(!O)return;let se="";if(H)se=O.artifactCopyText(H);else{let{markdown:ge,file:ce,artifactType:be}=Hf(y,M);be==="markdown"&&(se=O.artifactCopyText({id:M,artifactType:"markdown",status:"complete",markdown:ge??"",...ce?{file:ce}:{}}))}se&&navigator.clipboard.writeText(se).then(()=>{let ge=Je(rs.Check,16,"currentColor",2);ge&&(y.replaceChildren(ge),setTimeout(()=>{let ce=Je(rs.Copy,16,"currentColor",2);ce&&y.replaceChildren(ce)},1500))}).catch(()=>{})}),$e.addEventListener("click",a=>{let y=a.target.closest("[data-expand-artifact-inline]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-expand-artifact-inline");!M||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:M})===!0||(Pr=!1,Ji=!0,Go=!0,al=!0,V.selectArtifact(M),Yo())}),$e.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let y=u.closest("[data-open-artifact]");if(!y)return;let M=y.getAttribute("data-open-artifact");!M||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:M})===!0||(a.preventDefault(),a.stopPropagation(),Pr=!1,Ji=!0,V.selectArtifact(M),Yo())}),$e.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let ll=wt.composerOverlay,Rf=a=>{iu().catch(()=>{}),bw(a,o,ll)},xb=null,E0={mount:e,overlay:ll,sessionRef:Po,config:()=>o},ed=!1,Sb=a=>u=>{let y=u.target,M=y?.closest?.("[data-persona-ask-sheet-for]");if(!M||!(a==="click"?!!y?.closest("[data-ask-user-action]"):u.key==="Enter"&&!!y?.matches?.('[data-ask-free-text-input="true"]')))return;let O=ge=>{xb??=ge.createAskUserSheetHandlers(E0),xb[a](u)},se=qg();if(se){O(se);return}ed||(ed=!0,iu().then(ge=>{ed=!1,M.isConnected&&O(ge)},()=>{ed=!1}))};ll.addEventListener("click",Sb("click")),ll.addEventListener("keydown",Sb("keydown"));let Ab=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let y=ll.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let M=Number(a.key),O=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[M-1];O&&(a.preventDefault(),O.click())};document.addEventListener("keydown",Ab);let Ir=null,pn=null,cl=null,td=null,nd=()=>{},Mb=!1,od="",rd="";function Wf(){td?.(),td=null}let k0=()=>{let a=sn?.railShell?sn.railHost:null,u=a?.isConnected?a:null,y=u?u.getBoundingClientRect().width:0;return y<=0?200:y+360},Tb=()=>{if(!Ir||!pn)return;let a=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,y=u.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||y){pn.style.removeProperty("position"),pn.style.removeProperty("left"),pn.style.removeProperty("top"),pn.style.removeProperty("bottom"),pn.style.removeProperty("width"),pn.style.removeProperty("z-index");return}let M=Ir.firstElementChild;if(!M||M===pn)return;let H=10;pn.style.position="absolute",pn.style.top="0",pn.style.bottom="0",pn.style.width=`${H}px`,pn.style.zIndex="5";let O=Ly(Ir,u),se=M.offsetWidth+O/2-H/2;pn.style.left=`${Math.max(0,se)}px`},sd=()=>{},Eb=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>y?!1:ve||un(o)},id=()=>!po(o)||!Zc()||e.classList.contains("persona-artifact-narrow-host")||Eb()||(e.ownerDocument.defaultView??window).innerWidth<E_?"none":Ty(o)?"detached":"welded",Yo=()=>{if(!Et||!po(o))return;_c(e,o),Oc(e,o),sd();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=Ve.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let y=Zc();Et.setVisible(y),Et.update(Lo),Pr?(Et.setMobileOpen(!1),Et.element.classList.add("persona-hidden"),Et.backdrop?.classList.add("persona-hidden"),Go=!1,al=!1):Lo.artifacts.length>0&&wb()?(Et.element.classList.remove("persona-hidden"),Et.setMobileOpen(!0)):(Et.setMobileOpen(!1),Et.element.classList.add("persona-hidden"),Et.backdrop?.classList.add("persona-hidden"),Go=!1,al=!1);let M=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Et.setExpandToggleVisible(M),Et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Et.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Et.setTabFade(o.features?.artifacts?.layout?.tabFade),Et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!M&&!al&&(Go=!1),Go!==Mb){let O=Et.element;Go?(od=O.style.width,rd=O.style.maxWidth,O.style.removeProperty("width"),O.style.removeProperty("max-width")):(od&&(O.style.width=od),rd&&(O.style.maxWidth=rd),od="",rd=""),Mb=Go}e.classList.toggle("persona-artifact-expanded",Go),Et.setExpanded(Go);let H=id();H!==il&&(il=H,Qs()),nd()};if(po(o)){Ve.style.position="relative";let a=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(Be),Ir=u,u.appendChild(a),Ve.appendChild(u);let y=H=>{Cb||Et||(Et=H.createArtifactPane(o,{onSelect:O=>Po.current?.selectArtifact(O),onDismiss:()=>{Pr=!0,Yo()},onToggleExpand:()=>{let O=!Go,se=Lo.selectedId??Lo.artifacts[Lo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:se,expanded:O})!==!0&&(Go=O,O||(al=!1),Yo())}}),Et.element.classList.add("persona-hidden"),u.appendChild(Et.element),Et.backdrop&&Ve.appendChild(Et.backdrop),nd(),Yo())},M=ts();M?y(M):(Ay(()=>{let H=ts();H&&y(H)}),lf().catch(()=>{})),nd=()=>{if(!Ir||!Et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){cl?.(),cl=null,Wf(),pn&&(pn.remove(),pn=null),Et.element.style.removeProperty("width"),Et.element.style.removeProperty("maxWidth");return}if(!pn){let O=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let se=e.ownerDocument,ge=se.defaultView??window,ce=be=>{if(!Et||be.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||ge.innerWidth<=640)return;be.preventDefault(),Wf();let Ce=be.clientX,Ae=Et.element.getBoundingClientRect().width,Ke=o.features?.artifacts?.layout,Pt=Dt=>{let bo=Ir.getBoundingClientRect().width,an=e.classList.contains("persona-artifact-welded-split"),mn=Ly(Ir,ge),io=an?0:O.getBoundingClientRect().width||6,bn=Ae-(Dt.clientX-Ce),zt=rE(bn,bo,mn,io,Ke?.resizableMinWidth,Ke?.resizableMaxWidth,k0());Et.element.style.width=`${zt}px`,Et.element.style.maxWidth="none",Tb()},Ft=()=>{se.removeEventListener("pointermove",Pt),se.removeEventListener("pointerup",Ft),se.removeEventListener("pointercancel",Ft),td=null;try{O.releasePointerCapture(be.pointerId)}catch{}};td=Ft,se.addEventListener("pointermove",Pt),se.addEventListener("pointerup",Ft),se.addEventListener("pointercancel",Ft);try{O.setPointerCapture(be.pointerId)}catch{}};O.addEventListener("pointerdown",ce),pn=O,Ir.insertBefore(O,Et.element),cl=()=>{O.removeEventListener("pointerdown",ce)}}if(pn){let O=Zc();pn.classList.toggle("persona-hidden",!O),Tb()}},sd=()=>{if(!ve||!Et||(o.launcher?.sidebarMode??!1)||un(o)&&$o(o).reveal==="emerge")return;let O=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640;if(se&&O.innerWidth<=ge||!JT(o,ve))return;let ce=Wi(o).width,be=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Zc()?(Ve.style.width=be,Ve.style.maxWidth=be):(Ve.style.width=ce,Ve.style.maxWidth=ce)},typeof ResizeObserver<"u"&&(sl=new ResizeObserver(()=>{Yo()}),sl.observe(Ve))}else Ve.appendChild(Be);Pe()&&cn&&(wt.peekBanner&&cn.appendChild(wt.peekBanner),cn.appendChild(gt)),e.appendChild(ot),cn&&e.appendChild(cn);let Bf=()=>{let a=Eb()||Pe()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!un(o);if($e.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",$e.style.setProperty("--persona-transcript-gap",$e.style.gap),Pe()){Ve.style.width="100%",Ve.style.maxWidth="100%";let et=o.launcher?.composerBar??{},Ct=ot.dataset.state==="expanded",at=et.expandedSize??"anchored";if(!(Ct&&at!=="fullscreen")){Be.style.background="",Be.style.border="",Be.style.borderRadius="",Be.style.overflow="",Be.style.boxShadow="";return}let Tn=o.theme?.components?.panel,vo=Jr(o),Vr=($r,bi)=>$r==null||$r===""?bi:zn(vo,$r)??$r,Rm="1px solid var(--persona-border)",yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Wm="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Be.style.background="var(--persona-surface, #ffffff)",Be.style.border=Vr(Tn?.border,Rm),Be.style.borderRadius=Vr(Tn?.borderRadius,Wm),Be.style.boxShadow=Vr(Tn?.shadow,yi),Be.style.overflow="hidden";return}let u=un(o),y=o.launcher?.sidebarMode??!1,M=u||y||(o.launcher?.fullHeight??!1),H=o.launcher?.enabled===!1,O=o.launcher?.detachedPanel===!0,se=o.theme?.components?.panel,ge=o.darkTheme?.components?.panel,ce=ac(o)==="dark"?Zo(se??{},ge??{}):se,be=Jr(o),Ce=(et,Ct)=>et==null||et===""?Ct:zn(be,et)??et,Ae=e.ownerDocument.defaultView??window,Ke=o.launcher?.mobileFullscreen??!0,Pt=o.launcher?.mobileBreakpoint??640,Ft=Ae.innerWidth<=Pt,Dt=Ke&&Ft&&ve,bo=u&&Ke&&Ft,an=o.launcher?.position??"bottom-left",mn=an==="bottom-left"||an==="top-left",io=o.launcher?.zIndex??Jn,bn=(et,Ct,at)=>`var(--persona-components-panel-modes-${et}-${Ct}, ${at})`,zt=ce?.modes?.floating,mr=Ce(zt?.border??ce?.border,bn("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),gr=Ce(zt?.shadow??ce?.shadow,bn("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),Bo=Ce(zt?.borderRadius??ce?.borderRadius,bn("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),Do=O&&!Dt&&!bo,Ss=Dt||bo?"mobile":Do?"floating":u?"docked":y?"sidebar":H?"inline":"floating",hr=ce?.modes?.[Ss];Do?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Xo=Do?mr:y||Dt?"none":mr,As=Do?gr:Dt?"none":y?mn?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":H?"none":gr;u&&!Dt&&!Do&&(As="none",Xo="none");let Tl=Do?Bo:y||Dt?"0":Bo,hi=Ce(hr?.border??ce?.border,bn(Ss,"border",Xo)),q=Ce(hr?.shadow??ce?.shadow,bn(Ss,"shadow",As)),rt=Ce(hr?.borderRadius??ce?.borderRadius,bn(Ss,"borderRadius",Tl)),st=id(),he=st==="detached",qt=st==="welded";e.classList.toggle("persona-artifact-detached-split",he),e.classList.toggle("persona-artifact-welded-split",qt);let Sn="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)))))",Xt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&po(o)&&Ty(o)&&H&&!u;e.classList.toggle("persona-artifact-chat-flush",Xt);let vn=he||Xt?"none":q,Rn=he?mr:qt?"none":hi,Qe=he?Bo:rt;Xt&&(Rn="none",Qe="0");let Qt=hr?.borderRadius!=null&&hr.borderRadius!==""||ce?.borderRadius!=null&&ce.borderRadius!=="",it=Xt&&!Qt?"0":rt,Wn=ye.scrollTop;e.style.cssText="",ot.style.cssText="",Ve.style.cssText="",Be.style.cssText="",ye.style.cssText="",Qi||(gt.style.cssText=""),Ee&&(ye.style.display="none"),(M||H)&&(e.style.minWidth="0");let _o=()=>{if(Wn<=0)return;(ye.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ye.scrollTop===Wn)return;let Ct=ye.scrollHeight-ye.clientHeight;Ct<=0||(ye.scrollTop=Math.min(Wn,Ct))})};if(Dt){ot.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"),ot.style.cssText=`
1192
+ `,Y.addEventListener("click",()=>{f=z,A.forEach((T,W)=>{let L=W<z;T.classList.toggle("selected",L),T.setAttribute("aria-checked",W===z-1?"true":"false")})}),A.push(Y),C.appendChild(Y)}m.appendChild(C);let S=null;if(c){let z=document.createElement("div");z.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),z.appendChild(S),m.appendChild(z)}let E=document.createElement("div");E.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=l,k.addEventListener("click",()=>{n?.(),p.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=i,D.addEventListener("click",async()=>{if(f===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let z=S?.value.trim()||void 0;await t(f,z),p.remove()}catch(z){D.disabled=!1,D.textContent=i,console.error("[CSAT Feedback] Failed to submit:",z)}}),E.appendChild(k),E.appendChild(D),m.appendChild(E),p.appendChild(m),p}function e0(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:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:p="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,h.appendChild(C),g.appendChild(h);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=d;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,S.appendChild(E),S.appendChild(k);let D=document.createElement("div");D.className="persona-feedback-numbers";let z=[];for(let w=0;w<=10;w++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-number-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`Rating ${w} out of 10`),x.textContent=String(w),x.dataset.rating=String(w),w<=6?x.classList.add("persona-feedback-detractor"):w<=8?x.classList.add("persona-feedback-passive"):x.classList.add("persona-feedback-promoter"),x.addEventListener("click",()=>{m=w,z.forEach((P,I)=>{P.classList.toggle("selected",I===w),P.setAttribute("aria-checked",I===w?"true":"false")})}),z.push(x),D.appendChild(x)}A.appendChild(S),A.appendChild(D),g.appendChild(A);let Y=null;if(c){let w=document.createElement("div");w.className="persona-feedback-comment-container",Y=document.createElement("textarea"),Y.className="persona-feedback-comment",Y.placeholder=s,Y.rows=3,Y.setAttribute("aria-label","Additional comments"),w.appendChild(Y),g.appendChild(w)}let T=document.createElement("div");T.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=l,W.addEventListener("click",()=>{n?.(),f.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=i,L.addEventListener("click",async()=>{if(m===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=Y?.value.trim()||void 0;await t(m,w),f.remove()}catch(w){L.disabled=!1,L.textContent=i,console.error("[NPS Feedback] Failed to submit:",w)}}),T.appendChild(W),T.appendChild(L),g.appendChild(T),f.appendChild(g),f}var Qa="persona-chat-history",T_=30*1e3,E_="Tap the mic to resume your voice call",k_=641,Ja="data-persona-composer-reason",qc="data-persona-composer-notice",L_={"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 P_(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=L_[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 yf(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 I_(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 H_(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Yy=e=>!e||typeof e!="object"?{}:{...e},t0=e=>e.map(t=>({...t,streaming:!1})),n0=(e,t,n)=>{let o=e?.markdown?ip(e.markdown):null,r=lp(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,i=l=>{let c=l.text??"",d=l.message.rawContent??null;if(t){let m=t.process({text:c,raw:d??c,message:l.message,streaming:l.streaming});m!==null&&(c=m.text,m.persist||(l.message.__skipPersist=!0),m.resubmit&&!l.streaming&&n&&n())}let p=Oo()!==null,f;if(e?.postprocessMessage){let m=e.postprocessMessage({...l,text:c,raw:d??l.text??""});f=r?r(m):m}else if(o){let m=l.streaming?UC(c):c,g=o(m);f=r&&p?r(g):g}else f=jr(c);return f};return l=>{try{return i(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),jr(l.text??"")}}};function o0(e){let t=v("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,i=We(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var R_=(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},W_=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:R_(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),r0=(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=jd(t),r=new Set,s=new Set,i=PC((a,u)=>{Yn.delete(a);let y=Array.from($e.querySelectorAll("[data-message-id]")).find(M=>M.dataset.messageId===a);y&&(u==="tool"?Zh(a,y,r,o):Yh(a,y,s))}),l=new Map,c=()=>{bx({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let d=o.features;o=ky(o);let p=Iy.getForInstance(o.plugins),f=NA(e),m=[],g=!1,h=GM(()=>o),b=null,C=null,A=null,S=!1,E=null,k=a=>{b=a,a.initApprovalUi({webMcpToolTitle:cp});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},D=()=>{if(b)return b;let a=cT();return a?(k(a),a):(lT().then(u=>{S||b||(k(u),E?.())}).catch(()=>{}),null)},z=!1,Y=!1,T=null,W=(a,u,y,M)=>{if(!a.querySelector("[data-tv-form]"))return;let H=pE();if(H){H.enhanceWithForms(a,u,y,M);return}dE().then(()=>{z||Y||!T||(Y=!0,T())}).catch(()=>{})};o.components&&sr.registerAll(o.components);let L=gE(),x=o.persistState===!1?null:o.storageAdapter??yE(),P=!!o.clientToken&&typeof o.reconnectStream!="function",I={},J=null,_,j=new Promise(a=>{_=a}),te=()=>{},K=new Promise(a=>{te=a}),X,oe=!1,de=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:y,open:M}=u;return M&&(oe=!0),y}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(x?.load)try{let a=x.load();if(a&&typeof a.then=="function")J=a.then(u=>de(u??{messages:[],metadata:{}}));else{let y=de(a??{messages:[],metadata:{}});y.metadata&&(I=Yy(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null}),X=y.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=de({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}J||_();let xe=()=>I,Te=a=>{I=a({...I})??{},na()},re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ry],N=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Nc.message,Nc.messageAndClick],ke=Wy({parsers:re,handlers:N,getSessionMetadata:xe,updateSessionMetadata:Te,emit:L.emit,documentRef:typeof document<"u"?document:null});ke.syncFromMetadata();let ve=o.launcher?.enabled??!0,tt=o.launcher?.autoExpand??!1,xt=o.autoFocusInput??!1,ht=tt,lt=ve,Ye=o.layout?.header?.layout,dt=!1,Pe=()=>Cc(o),Se=()=>ve||Pe(),U=Pe()?!1:ve?tt:!0,R=!1,G=null,ne=()=>{R=!0,G&&clearTimeout(G),G=setTimeout(()=>{R&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),R=!1)},1e4)},Z=n0(o,ke,ne),le=o.features?.showReasoning??!0,Me=o.features?.showToolCalls??!0,Ie=o.features?.showEventStreamToggle??!1,_e=o.features?.scrollToBottom??{},ct=o.features?.scrollBehavior??{},Tt=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",nt=`${Tt()}event-stream`,Ut=null,tn=o.features?.eventStream?.maxEvents??2e3,ee=null,Re=null,Fe=null,yt=!1,bt=null,Ee=!1,He=null,je=0,It=(a,u)=>{ee?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},wn=(a,u)=>{Re?.processEvent(a,u),ee?It(a,u):Fe&&(Fe.length>=tn&&Fe.shift(),Fe.push({type:a,payload:u}))},nn=()=>{ee||!Ie||(Fe??=[],dy().then(a=>{if(yt||ee||!Ie)return;Ut=new a.EventStreamStore(nt),ee=new a.EventStreamBuffer(tn,Ut),Re=Re??new a.ThroughputTracker,Ut.open().then(()=>ee?.restore()).catch(y=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",y)});let u=Fe??[];Fe=null;for(let y of u)Re?.processEvent(y.type,y.payload),It(y.type,y.payload)}).catch(()=>{}))};Ie&&nn();let Ot=!1,mt=null,Ht=()=>{},St=()=>{},Kt=()=>{},gn=()=>{},Zn=()=>{},ss=()=>Ee||Ot&&mt==="panel",jn={onCopy:a=>{L.emit("message:copy",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{L.emit("message:feedback",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},qs=o.statusIndicator??{},oo=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Cn.idle:a==="connecting"?u.connectingText??Cn.connecting:a==="connected"?u.connectedText??Cn.connected:a==="error"?u.errorText??Cn.error:a==="paused"?u.pausedText??Cn.paused:a==="resuming"?u.resumingText??Cn.resuming:Cn[a];function Tr(a,u,y,M){if(!Pe()&&(y.mode==="transient"||a.classList.contains("persona-mb-2"))&&(Ym(a,Pn,y),xi(a,y,M)),!(a.hasAttribute(Ja)||a.hasAttribute(qc)))if(M==="idle"&&y.idleLink){a.textContent="";let H=document.createElement("a");H.href=y.idleLink,H.target="_blank",H.rel="noopener noreferrer",H.textContent=u,H.style.color="inherit",H.style.textDecoration="none",a.appendChild(H)}else a.textContent=u}let At=KM({config:o,showClose:Se()}),{wrapper:ot,panel:Ve,pillRoot:cn}=At.shell,wt=At.panelElements,{container:Be,body:ye,messagesWrapper:$e,starterSuggestions:uo,transcriptSuggestions:fo,suggestions:eo,textarea:we,sendButton:ze,composerForm:Pn,statusText:Mt,welcomeHost:$,welcomeIconHolder:me,greetingHost:Ne,introKicker:ft,introTitle:pt,introSubtitle:An,closeButton:Ze,iconHolder:Nt,headerTitle:mo,headerSubtitle:ir,header:Vt,footer:gt,actionsRow:zi}=wt,Kn=wt.leftActions,js=wt.rightActions,ro=wt.sendButtonWrapper,Kc=wt.setSendButtonMode,De=wt.micButton,Dn=wt.micButtonWrapper,Zt=wt.attachmentButton,In=wt.attachmentButtonWrapper,Gt=wt.attachmentInput,_n=wt.attachmentPreviewsContainer;Be.classList.add("persona-relative"),ye.classList.add("persona-relative");let Gc=12,is=()=>_e.label??"",vf=()=>_e.iconName??"arrow-down",Cf=()=>_e.enabled!==!1,Gn=()=>ct.mode??"anchor-top",zo=()=>Gn()==="follow"||Gn()==="anchor-top"&&dl,Ks=()=>ct.anchorTopOffset??16,Yc=()=>ct.restorePosition??"bottom",el=()=>ct.pauseOnInteraction===!0,tl=()=>ct.showActivityWhilePinned!==!1,qi=()=>ct.announce===!0,Gs=()=>ct.scrollbar??"on-scroll",fn=v("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");fn.type="button",fn.style.display="none",fn.setAttribute("data-persona-scroll-to-bottom","true");let Ys=v("span","persona-flex persona-items-center"),nl=v("span",""),Mn=v("span","");Mn.setAttribute("data-persona-scroll-to-bottom-count",""),Mn.style.display="none",fn.append(Ys,nl,Mn),Be.appendChild(fn);let xn=v("div","persona-stream-anchor-spacer");xn.setAttribute("aria-hidden","true"),xn.setAttribute("data-persona-anchor-spacer",""),xn.style.flexShrink="0",xn.style.pointerEvents="none",xn.style.height="0px",xn.style.display="none",ye.appendChild(xn);let qo=v("div","persona-sr-only");qo.setAttribute("aria-live","polite"),qo.setAttribute("aria-atomic","true"),qo.setAttribute("role","status"),qo.setAttribute("data-persona-live-region",""),Object.assign(qo.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"}),Be.appendChild(qo);let as=null,Er=null,Xs=a=>{!qi()||!a||(Er=a,as===null&&(as=setTimeout(()=>{as=null,Er&&qi()&&(qo.textContent=Er),Er=null},400)))},go=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(ve||un(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!un(o)},B=()=>Ku(o,go()),Q="empty",fe=0,Le=()=>fe||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Xe=()=>{let u=gt.style.display==="none"?0:gt.offsetHeight;fn.style.bottom=`${u+Le()+Gc}px`};Xe();let dn=()=>{Qi||(gt.style.marginBottom=fe>0?`${fe}px`:"")},on=()=>{let a=vh(o,Pe()),u=B();e.setAttribute("data-persona-welcome-fullscreen",String(go())),e.setAttribute("data-persona-welcome-layout",u.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom");let M=gt.style.display==="none"?0:gt.offsetHeight,H=u.anchor==="center"&&Q==="empty"?cc(u.anchorComposerTop)??cc("44%"):null,O=H!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,se=O?getComputedStyle(ye):null,ge=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,ce=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,be=Math.max(0,(parseFloat(se?.paddingBottom??"")||0)-(a==="overlay"?ge+ce:0)),Ce=O?ye.getBoundingClientRect().top-Be.getBoundingClientRect().top:0,Ae=!O||$.hidden?0:($.querySelector("[data-persona-welcome-plugin]")??$).offsetHeight,Ke=H===null||Pe()?0:O?Math.max(0,Math.round((Be.clientHeight-Ce-Ae-be-M)/2)):DA({columnHeight:Be.clientHeight,footerHeight:M,fraction:H});e.style.setProperty("--persona-composer-overlay-height",`${M}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?Ke:0}px`),fe=a==="block"?Ke:0,dn(),Xe()},rn=()=>{let a=!!is();fn.setAttribute("aria-label",is()||"Jump to latest"),fn.title=is(),fn.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ys.innerHTML="";let u=We(vf(),"14px","currentColor",2);u?(Ys.appendChild(u),Ys.style.display=""):Ys.style.display="none",nl.textContent=is(),nl.style.display=a?"":"none"};rn();let ut=null,Rt=null,Oe=QS(),ji=a=>{try{Be.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};Oe.subscribe(ji);let ko=()=>{Oe.setText(we?.value??"")},kr=()=>{Oe.setMentionRefs(Rt?.getMentionRefs()??[])},y0=a=>({id:a.id,name:a.file.name,mimeType:a.file.type,size:a.file.size,status:a.status,progress:a.progress,error:a.error}),nb=a=>{let u=Object.freeze(a.map(y0));Oe.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(y){console.error("[AgentWidget] attachments.onChange failed:",y)}Zf()};Oe.setSelectedModelId(o.composer?.selectedModelId);let ol=()=>o.composer?.modes??[],Ki=()=>fA(ol(),o.composer?.modeGroups);{let a=vu(o.composer?.defaultActiveModeIds??[],ol());a.length&&Oe.setActiveModeIds(a)}function ob(a){if(Oe.getState().selectedModelId!==a){Oe.setSelectedModelId(a),ls?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function Xc(a){Oe.setActiveModeIds(a),Lr?.render(a,Ki()),Gi.forEach(u=>u.repaint()),jo?.resolve(),Sd(),Ko()}function wf(a){Xc(mA(Oe.getState().activeModeIds,a,ol(),o.composer?.modeGroups))}let ls=null,xf=null,Lr=null,Gi=new Map,cs=null;function ar(a){Oe.setQuote(a),cs?.render(Oe.getState().quote),Ko(),Xb()}let rb=!1;function Sf(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!rb&&o.debug===!0&&(rb=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ds=null;function Yi(a){Oe.setPendingSubmission(a),ds?.render(Oe.getState().pendingSubmission),Ko()}let b0=a=>{let u=Gi.get(a);if(u)return u;let y=yA({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(M=>M.id===a),getModes:()=>ol().filter(M=>M.groupId===a),getActiveIds:()=>Oe.getState().activeModeIds,onSelect:M=>wf(M)});return Gi.set(a,y),y},v0=()=>{let a=[],u=Oe.getState().activeModeIds,y=new Set;if(ol().forEach((M,H)=>{if(bu(M.groupId,o.composer?.modeGroups)){let O=M.groupId;if(y.has(O))return;y.add(O);let se=b0(O);se.action.order=uh(H),se.action.label=o.composer?.modeGroups?.find(ge=>ge.id===O)?.label??O,a.push(se.action);return}a.push({id:pA(M.id),kind:"button",placement:"start",order:uh(H),presentation:M.presentation??"auto",label:M.label,shortLabel:M.shortLabel,iconName:M.iconName,pressed:u.includes(M.id),onSelect:()=>wf(M.id)})}),o.composer?.models?.length&&!p.some(M=>M.renderComposer)){let M=o.composer?.modelPicker?.presentation??"native";(!ls||xf!==M)&&(xf=M,ls=cA({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Oe.getState().selectedModelId,onSelect:H=>ob(H),presentation:M,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push(ls.action)}return a},Af=null,sb=p.find(a=>a.renderHeader);if(sb?.renderHeader){let a=sb.renderHeader({config:o,defaultRenderer:()=>{let u=Ii({config:o,showClose:Se()});return xc(Be,u,o),u.header},onClose:()=>Yt(!1,"user")});if(a){let u=Vt;u&&(u.replaceWith(a),Vt=a,At.header.element=a)}}let ib=()=>{bt&&(ye.style.display="none",gt.parentNode?.insertBefore(bt.element,gt),bt.update())},Mf=()=>{if(!ee){nn();return}if(Ee=!0,bt?ib():dy().then(u=>{bt||!Ee||!ee||(bt=u.createEventStreamView({buffer:ee,getFullHistory:()=>ee.getAllFromStore(),onClose:()=>Xi(),config:o,plugins:p,getThroughput:()=>Re?.getMetric()??{status:"idle"},renderIconByName:We}),ib())}).catch(()=>{Xi()}),$t){$t.style.boxShadow=`inset 0 0 0 1.5px ${lo.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(y=>y&&$t.classList.add(y))}let a=()=>{if(!Ee)return;let u=Date.now();u-je>=200&&(bt?.update(),je=u),He=requestAnimationFrame(a)};je=0,He=requestAnimationFrame(a),Xn(),L.emit("eventStream:opened",{timestamp:Date.now()})},Xi=()=>{if(Ee){if(Ee=!1,bt&&bt.element.remove(),ye.style.display="",$t){$t.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&$t.classList.remove(u))}He!==null&&(cancelAnimationFrame(He),He=null),Xn(),L.emit("eventStream:closed",{timestamp:Date.now()})}},$t=null;if(Ie){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");$t=v("button",u),$t.style.width="28px",$t.style.height="28px",$t.style.color=lo.actionIconColor,$t.type="button",$t.setAttribute("aria-label","Event Stream"),$t.title="Event Stream";let y=Je(rs.Activity,"18px","currentColor",1.5);y&&$t.appendChild(y);let M=wt.clearChatButtonWrapper,H=wt.closeButtonWrapper,O=M||H;O&&O.parentNode===Vt?Vt.insertBefore($t,O):Vt.appendChild($t),$t.addEventListener("click",()=>{Ee?Xi():Mf()})}let ab=a=>{let u=o.attachments;if(!u?.enabled)return;let y=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!y){y=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let H=a.querySelector("[data-persona-composer-form]");H?.parentNode?H.parentNode.insertBefore(y,H):a.insertBefore(y,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let H=v("input");H.type="file",H.setAttribute("data-persona-composer-attachment-input",""),H.accept=(u.allowedTypes??Qr).join(","),H.multiple=(u.maxFiles??4)>1,H.style.display="none",H.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(H)}},Qi=!1,lb=a=>{let u=p.find(H=>H.renderComposer);if(!u?.renderComposer)return null;let y=o.composer,M=g?V.isStreaming():!1;return u.renderComposer({config:o,defaultRenderer:a,requestRender:()=>sC(),storage:h(u.id),onSubmit:H=>{!V||V.isStreaming()||Hd(H.trim(),{consumeDraft:!1})},streaming:M,disabled:M,openAttachmentPicker:()=>{pr()||Gt?.click()},models:y?.models,selectedModelId:Oe.getState().selectedModelId??y?.selectedModelId,onModelChange:H=>ob(H),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Af?.()}:void 0})},cb=lb(()=>Ac({config:o}).footer);cb&&(At.replaceComposer(cb),gt=At.composer.footer,Qi=!0);let Bt=null,C0=a=>{Pn=a.form,we=a.input,ro=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(ze=a.sendButton),a.micButton&&(De=a.micButton,Dn=a.micButton.parentElement),a.found.status&&(Mt=a.found.status),a.found.suggestions&&(eo=a.found.suggestions),a.attachmentButton&&(Zt=a.attachmentButton,In=a.attachmentButton.parentElement),Gt=a.attachmentInput??null,_n=a.attachmentPreviews??null,a.found.actionsRow&&(zi=a.found.actionsRow),Kn=a.found.actionsStart,js=a.found.actionsEnd};function Tf(){let a=we;if(!a)return;let u=o.composer?.inputAttributes,y=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Rp(a,u),y&&a.setAttribute("aria-label",y),Hp(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(a)}),wx(a,Ip(o.composer?.maxLines,Pe()?5:3))}let db=a=>{Bt=ZS(a,{debug:o.debug===!0}),Bt&&C0(Bt),Tf()};ab(gt),db(gt),ko();let rl=Os(o,Pe());rl&&($e.style.maxWidth=rl,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ne.style.maxWidth=rl,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%",uo.style.maxWidth=rl,fo.style.maxWidth=rl,fo.style.marginLeft="auto",fo.style.marginRight="auto",fo.style.width="100%");let pb=()=>{let a=Os(o,Pe());if(!(!a||Pe()))for(let u of[Pn,eo,_n,Mt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};pb();let ub=()=>{!o.attachments?.enabled||!Gt||!_n||(ut?ut.remountPreviews(_n):(ut=rc.fromConfig(o.attachments,nb),ut.setPreviewsContainer(_n)),Bt?.addListener(Gt,"change",a=>{let u=a.target;ut?.handleFileSelect(u.files),u.value=""}),Be.querySelector(".persona-attachment-drop-overlay")||Be.appendChild(o0(o.attachments.dropOverlay)))};ub();let w0=()=>Rt?.prefetch(),Ef=()=>{if(!o.contextMentions?.enabled||!we)return;let a=qg();if(!a){let M=we;iu().then(()=>{Rt||we!==M||!M.isConnected||(Ef(),jo?.resolve())},()=>{});return}let u=Bt?.header??null,y=u?Pg(u):void 0;if(Rt=a.createContextMentionOrchestrator({deps:{loadContextMentions:Zp,loadContextMentionsInline:su,renderLucideIcon:We,createMentionButton:Vp},config:o,textarea:we,anchor:Pn??we,getMessages:()=>V.getMessages(),liveRegionHost:Be,chipRow:y}),Rt&&!y){let M=we;M.parentElement?.insertBefore(Rt.contextRow,M)}};Ef();let jo=null,x0={getState:()=>Oe.getState(),getValue:()=>we?.value??"",setValue:a=>{we&&(we.value=a,we.dispatchEvent(new Event("input",{bubbles:!0})),ko())},submit:()=>{Gl(Bt?.form??null)},openAttachmentPicker:()=>{pr()||Gt?.click()},toggleVoice:()=>{Af?.()},requestRender:()=>jo?.resolve()},S0=()=>{let a=[];return(Rt?.affordanceButtons??[]).forEach((y,M)=>{a.push({id:`core:mention-${M}`,placement:"start",order:wr.mention+M,element:y,managed:!0})}),In&&a.push({id:"core:attachment",placement:"start",order:wr.attachment,element:In}),Dn&&a.push({id:"core:mic",placement:"end",order:wr.mic,element:Dn}),ro&&a.push({id:"core:send",placement:"end",order:wr.send,element:ro}),a},fb=()=>{jo?.destroy(),jo=iA({getBindings:()=>Bt,collect:()=>({builtIns:S0(),configActions:[...v0(),...o.composer?.actions??[]],plugins:p,contributionContext:{config:o,getState:()=>Oe.getState(),requestRender:()=>jo?.resolve()},debug:o.debug===!0}),actionContext:x0,getState:()=>Oe.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),jo.resolve()};fb();let kf=()=>{if(Lr?.destroy(),Lr=null,!Ki().length)return;let a=Bt?.header;a&&(Lr=dA({row:Pg(a),onRemove:u=>wf(u),initialIds:Oe.getState().activeModeIds}),Lr.render(Oe.getState().activeModeIds,Ki()))};kf();let mb=()=>{cs?.destroy(),cs=null,ds?.destroy(),ds=null;let a=Bt?.header;a&&(cs=bA({onDismiss:()=>ar(void 0)}),a.appendChild(cs.element),cs.render(Oe.getState().quote),Sf()==="defer-one"&&(ds=vA({onEdit:()=>vk(),onRemove:()=>Yi(void 0)}),a.appendChild(ds.element),ds.render(Oe.getState().pendingSubmission)))};mb();let Lf=MA(),A0=()=>{let a=Bt?.header?.querySelector(Lg);if(a)return a.childElementCount>0;let u=Oe.getState();return u.mentionRefs.length>0||vu(u.activeModeIds,Ki()).length>0};function Ko(){let a=Oe.getState(),u=Lf.observe(TA(we),a.text);gt.toggleAttribute("data-persona-composer-compact",AA({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:A0(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function gb(){o.composer?.layout==="single-row"&&!Pe()?gt.setAttribute("data-persona-composer-layout","single-row"):gt.removeAttribute("data-persona-composer-layout")}gb(),Oe.subscribe(()=>{jo?.sync(),Zf(),Cd(),Ko(),Xb()}),Cd();let hb=!1,M0=a=>{if(hb||o.debug!==!0)return;let u=["messages","composer"].filter(y=>a[y]);u.length&&(hb=!0,console.warn(`[persona] layout.slots.${u.join(" and layout.slots.")} ${u.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 a=o.layout?.slots??{};M0(a);let u=M=>{switch(M){case"body-top":return ye.querySelector("[data-persona-intro-card]");case"messages":return $e;case"footer-top":return eo;case"composer":return Pn;case"footer-bottom":return Mt;default:return null}},y=(M,H)=>{switch(M){case"header-left":case"header-center":case"header-right":if(M==="header-left")Vt.insertBefore(H,Vt.firstChild);else if(M==="header-right")Vt.appendChild(H);else{let O=Vt.querySelector(".persona-flex-col");O?O.parentNode?.insertBefore(H,O.nextSibling):Vt.appendChild(H)}break;case"body-top":{let O=ye.querySelector("[data-persona-intro-card]");O?O.replaceWith(H):ye.insertBefore(H,ye.firstChild);break}case"body-bottom":ye.appendChild(H);break;case"footer-top":eo.replaceWith(H);break;case"footer-bottom":Mt.replaceWith(H);break;default:break}};for(let[M,H]of Object.entries(a))if(H)try{let O=H({config:o,defaultContent:()=>u(M)});O&&y(M,O)}catch(O){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${M}":`,O)}})(),$e.addEventListener("click",a=>{let u=a.target;if(!(u instanceof Element))return;let y=u.closest("button[data-persona-copy-tool-detail]");y&&(a.preventDefault(),a.stopPropagation(),QM(y))});let Pf=a=>{let y=a.target.closest('button[data-expand-header="true"]');if(!y)return;let M=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!M)return;let H=M.getAttribute("data-message-id");if(!H)return;gs(),sa();let O=y.getAttribute("data-bubble-type");if(M.classList.contains("persona-activity-row")){i.manual(H);let se=M.parentElement?.closest("[data-persona-tool-group]");se?.dataset.messageId&&i.manual(se.dataset.messageId)}if(O==="reasoning")s.has(H)?s.delete(H):s.add(H),Yh(H,M,s);else if(O==="tool")r.has(H)?r.delete(H):r.add(H),Zh(H,M,r,o);else if(O==="approval"&&b){let ge=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",ce=l.get(H)??ge;l.set(H,!ce),b.updateApprovalDetailsUI(H,M,o,l)}Yn.delete(H)};$e.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Pf(a))}),$e.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&Pf(a)}),$e.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Pf(a))}),$e.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let y=$e.getRootNode(),M=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!M||M.isCollapsed)return;let H=M.toString(),O=VA(H);!O||O===H||(u.setData("text/plain",O),a.preventDefault())});let If=new Map,yb=null,bb="idle",T0={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},E0=(a,u)=>{let{icon:y,label:M}=T0[u];a.setAttribute("aria-label",M),a.title=M,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let H=We(y,14,"currentColor",2);H&&(a.innerHTML="",a.appendChild(H))},vb=()=>{$e.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let M=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;E0(u,M&&M===yb?bb:"idle")})};$e.addEventListener("click",a=>{let y=a.target.closest(".persona-message-action-btn[data-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.closest("[data-actions-for]");if(!M)return;let H=M.getAttribute("data-actions-for");if(!H)return;let O=y.getAttribute("data-action");if(O==="copy"){let ge=V.getMessages().find(ce=>ce.id===H);if(ge&&jn.onCopy){let ce=ge.content||"";navigator.clipboard.writeText(ce).then(()=>{y.classList.add("persona-message-action-success");let be=Je(rs.Check,14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Ce=Je(rs.Copy,14,"currentColor",2);Ce&&(y.innerHTML="",y.appendChild(Ce))},2e3)}).catch(be=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",be)}),jn.onCopy(ge)}}else if(O==="read-aloud")V.toggleReadAloud(H);else if(O==="upvote"||O==="downvote"){let ge=(If.get(H)??null)===O,ce=O==="upvote"?"thumbs-up":"thumbs-down";if(ge){If.delete(H),y.classList.remove("persona-message-action-active");let be=We(ce,14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be))}else{let be=O==="upvote"?"downvote":"upvote",Ce=M.querySelector(`[data-action="${be}"]`);if(Ce){Ce.classList.remove("persona-message-action-active");let Dt=We(be==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Dt&&(Ce.innerHTML="",Ce.appendChild(Dt))}If.set(H,O),y.classList.add("persona-message-action-active");let Ae=We(ce,14,"currentColor",2);Ae&&(Ae.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(Ae)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Pt=V.getMessages().find(Ft=>Ft.id===H);Pt&&jn.onFeedback&&jn.onFeedback({type:O,messageId:Pt.id,message:Pt})}}else if(O==="regenerate")Qc?.regenerate(H);else if(O==="edit")Qc?.edit(H);else if(O==="quote")Qc?.quote(H);else if(O?.startsWith(Uu)){let se=O.slice(Uu.length),ge=o.messageActions?.custom?.find(be=>be.id===se),ce=V.getMessages().find(be=>be.id===H);if(!ge||!ce)return;try{ge.onSelect(ce)}catch(be){console.error(`[AgentWidget] messageActions.custom "${se}" onSelect failed:`,be)}}});let Qc=null;$e.addEventListener("click",a=>{let y=a.target.closest("button[data-approval-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.closest(".persona-approval-bubble");if(!M)return;let H=M.getAttribute("data-message-id");if(!H)return;let O=y.getAttribute("data-approval-action");if(!O)return;let se=O==="approve"?"approved":"denied",ce=V.getMessages().find(Ce=>Ce.id===H);if(!ce?.approval)return;let be=M.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(Ae=>{Ae.disabled=!0,Ae.style.opacity="0.5",Ae.style.cursor="not-allowed"}),ce.approval.toolType==="webmcp"?V.resolveWebMcpApproval(H,se):V.resolveApproval(ce.approval,se)});let Et=null,Cb=!1,sl=null,Qs=()=>{},il="none",Jc=null,Lo={artifacts:[],selectedId:null},Pr=!1,Go=!1,al=!1,Ji=!1,wb=()=>Ji||Lo.artifacts.some(a=>ks(o.features?.artifacts,a)==="panel"),Zc=()=>Lo.artifacts.length>0&&!Pr&&wb(),Po={current:null},Hf=(a,u)=>{let y=V.getArtifactById(u),M=y?.markdown,H=y?.title||"artifact",O=y?.file,se=y?.artifactType??"markdown";if(!M){let be=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(be){let Ae=V.getMessages().find(Ke=>Ke.id===be);if(Ae?.rawContent)try{let Ke=JSON.parse(Ae.rawContent);M=Ke?.props?.markdown,H=Ke?.props?.title||H,Ke?.props?.file&&typeof Ke.props.file=="object"&&(O=Ke.props.file),!y&&typeof Ke?.props?.artifactType=="string"&&(se=Ke.props.artifactType)}catch{}}}return{markdown:M,title:H,file:O,artifactType:se}};$e.addEventListener("click",a=>{let y=a.target.closest("[data-download-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-download-artifact");if(!M||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:M})===!0)return;let{markdown:O,title:se,file:ge}=Hf(y,M);if(!O)return;let ce=ts();ce&&ce.triggerArtifactDownload(ce.downloadInfoFor({title:se,markdown:O,file:ge}))}),$e.addEventListener("click",a=>{let y=a.target.closest("[data-artifact-custom-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-artifact-custom-action");if(!M)return;let H=y.closest("[data-artifact-inline]"),O=H?null:y.closest("[data-open-artifact]"),se=H?H.getAttribute("data-artifact-inline"):O?.getAttribute("data-open-artifact")??null,ce=(H?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ft=>Ft.id===M);if(!ce)return;let{markdown:be,title:Ce,file:Ae,artifactType:Ke}=Hf(y,se??""),Pt={artifactId:se,title:Ce,artifactType:Ke,markdown:be,file:Ae};try{Promise.resolve(ce.onClick(Pt)).catch(()=>{})}catch{}}),$e.addEventListener("click",a=>{let y=a.target.closest("[data-copy-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-copy-artifact");if(!M)return;let H=V.getArtifactById(M),O=ts();if(!O)return;let se="";if(H)se=O.artifactCopyText(H);else{let{markdown:ge,file:ce,artifactType:be}=Hf(y,M);be==="markdown"&&(se=O.artifactCopyText({id:M,artifactType:"markdown",status:"complete",markdown:ge??"",...ce?{file:ce}:{}}))}se&&navigator.clipboard.writeText(se).then(()=>{let ge=Je(rs.Check,16,"currentColor",2);ge&&(y.replaceChildren(ge),setTimeout(()=>{let ce=Je(rs.Copy,16,"currentColor",2);ce&&y.replaceChildren(ce)},1500))}).catch(()=>{})}),$e.addEventListener("click",a=>{let y=a.target.closest("[data-expand-artifact-inline]");if(!y)return;a.preventDefault(),a.stopPropagation();let M=y.getAttribute("data-expand-artifact-inline");!M||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:M})===!0||(Pr=!1,Ji=!0,Go=!0,al=!0,V.selectArtifact(M),Yo())}),$e.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let y=u.closest("[data-open-artifact]");if(!y)return;let M=y.getAttribute("data-open-artifact");!M||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:M})===!0||(a.preventDefault(),a.stopPropagation(),Pr=!1,Ji=!0,V.selectArtifact(M),Yo())}),$e.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let ll=wt.composerOverlay,Rf=a=>{iu().catch(()=>{}),bw(a,o,ll)},xb=null,k0={mount:e,overlay:ll,sessionRef:Po,config:()=>o},ed=!1,Sb=a=>u=>{let y=u.target,M=y?.closest?.("[data-persona-ask-sheet-for]");if(!M||!(a==="click"?!!y?.closest("[data-ask-user-action]"):u.key==="Enter"&&!!y?.matches?.('[data-ask-free-text-input="true"]')))return;let O=ge=>{xb??=ge.createAskUserSheetHandlers(k0),xb[a](u)},se=qg();if(se){O(se);return}ed||(ed=!0,iu().then(ge=>{ed=!1,M.isConnected&&O(ge)},()=>{ed=!1}))};ll.addEventListener("click",Sb("click")),ll.addEventListener("keydown",Sb("keydown"));let Ab=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let y=ll.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let M=Number(a.key),O=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[M-1];O&&(a.preventDefault(),O.click())};document.addEventListener("keydown",Ab);let Ir=null,pn=null,cl=null,td=null,nd=()=>{},Mb=!1,od="",rd="";function Wf(){td?.(),td=null}let L0=()=>{let a=sn?.railShell?sn.railHost:null,u=a?.isConnected?a:null,y=u?u.getBoundingClientRect().width:0;return y<=0?200:y+360},Tb=()=>{if(!Ir||!pn)return;let a=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,y=u.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||y){pn.style.removeProperty("position"),pn.style.removeProperty("left"),pn.style.removeProperty("top"),pn.style.removeProperty("bottom"),pn.style.removeProperty("width"),pn.style.removeProperty("z-index");return}let M=Ir.firstElementChild;if(!M||M===pn)return;let H=10;pn.style.position="absolute",pn.style.top="0",pn.style.bottom="0",pn.style.width=`${H}px`,pn.style.zIndex="5";let O=Ly(Ir,u),se=M.offsetWidth+O/2-H/2;pn.style.left=`${Math.max(0,se)}px`},sd=()=>{},Eb=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>y?!1:ve||un(o)},id=()=>!po(o)||!Zc()||e.classList.contains("persona-artifact-narrow-host")||Eb()||(e.ownerDocument.defaultView??window).innerWidth<k_?"none":Ty(o)?"detached":"welded",Yo=()=>{if(!Et||!po(o))return;_c(e,o),Oc(e,o),sd();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=Ve.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let y=Zc();Et.setVisible(y),Et.update(Lo),Pr?(Et.setMobileOpen(!1),Et.element.classList.add("persona-hidden"),Et.backdrop?.classList.add("persona-hidden"),Go=!1,al=!1):Lo.artifacts.length>0&&wb()?(Et.element.classList.remove("persona-hidden"),Et.setMobileOpen(!0)):(Et.setMobileOpen(!1),Et.element.classList.add("persona-hidden"),Et.backdrop?.classList.add("persona-hidden"),Go=!1,al=!1);let M=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Et.setExpandToggleVisible(M),Et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Et.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Et.setTabFade(o.features?.artifacts?.layout?.tabFade),Et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!M&&!al&&(Go=!1),Go!==Mb){let O=Et.element;Go?(od=O.style.width,rd=O.style.maxWidth,O.style.removeProperty("width"),O.style.removeProperty("max-width")):(od&&(O.style.width=od),rd&&(O.style.maxWidth=rd),od="",rd=""),Mb=Go}e.classList.toggle("persona-artifact-expanded",Go),Et.setExpanded(Go);let H=id();H!==il&&(il=H,Qs()),nd()};if(po(o)){Ve.style.position="relative";let a=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(Be),Ir=u,u.appendChild(a),Ve.appendChild(u);let y=H=>{Cb||Et||(Et=H.createArtifactPane(o,{onSelect:O=>Po.current?.selectArtifact(O),onDismiss:()=>{Pr=!0,Yo()},onToggleExpand:()=>{let O=!Go,se=Lo.selectedId??Lo.artifacts[Lo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:se,expanded:O})!==!0&&(Go=O,O||(al=!1),Yo())}}),Et.element.classList.add("persona-hidden"),u.appendChild(Et.element),Et.backdrop&&Ve.appendChild(Et.backdrop),nd(),Yo())},M=ts();M?y(M):(Ay(()=>{let H=ts();H&&y(H)}),lf().catch(()=>{})),nd=()=>{if(!Ir||!Et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){cl?.(),cl=null,Wf(),pn&&(pn.remove(),pn=null),Et.element.style.removeProperty("width"),Et.element.style.removeProperty("maxWidth");return}if(!pn){let O=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let se=e.ownerDocument,ge=se.defaultView??window,ce=be=>{if(!Et||be.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||ge.innerWidth<=640)return;be.preventDefault(),Wf();let Ce=be.clientX,Ae=Et.element.getBoundingClientRect().width,Ke=o.features?.artifacts?.layout,Pt=Dt=>{let bo=Ir.getBoundingClientRect().width,an=e.classList.contains("persona-artifact-welded-split"),mn=Ly(Ir,ge),io=an?0:O.getBoundingClientRect().width||6,bn=Ae-(Dt.clientX-Ce),zt=sE(bn,bo,mn,io,Ke?.resizableMinWidth,Ke?.resizableMaxWidth,L0());Et.element.style.width=`${zt}px`,Et.element.style.maxWidth="none",Tb()},Ft=()=>{se.removeEventListener("pointermove",Pt),se.removeEventListener("pointerup",Ft),se.removeEventListener("pointercancel",Ft),td=null;try{O.releasePointerCapture(be.pointerId)}catch{}};td=Ft,se.addEventListener("pointermove",Pt),se.addEventListener("pointerup",Ft),se.addEventListener("pointercancel",Ft);try{O.setPointerCapture(be.pointerId)}catch{}};O.addEventListener("pointerdown",ce),pn=O,Ir.insertBefore(O,Et.element),cl=()=>{O.removeEventListener("pointerdown",ce)}}if(pn){let O=Zc();pn.classList.toggle("persona-hidden",!O),Tb()}},sd=()=>{if(!ve||!Et||(o.launcher?.sidebarMode??!1)||un(o)&&$o(o).reveal==="emerge")return;let O=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640;if(se&&O.innerWidth<=ge||!ZT(o,ve))return;let ce=Wi(o).width,be=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Zc()?(Ve.style.width=be,Ve.style.maxWidth=be):(Ve.style.width=ce,Ve.style.maxWidth=ce)},typeof ResizeObserver<"u"&&(sl=new ResizeObserver(()=>{Yo()}),sl.observe(Ve))}else Ve.appendChild(Be);Pe()&&cn&&(wt.peekBanner&&cn.appendChild(wt.peekBanner),cn.appendChild(gt)),e.appendChild(ot),cn&&e.appendChild(cn);let Bf=()=>{let a=Eb()||Pe()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!un(o);if($e.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",$e.style.setProperty("--persona-transcript-gap",$e.style.gap),Pe()){Ve.style.width="100%",Ve.style.maxWidth="100%";let et=o.launcher?.composerBar??{},Ct=ot.dataset.state==="expanded",at=et.expandedSize??"anchored";if(!(Ct&&at!=="fullscreen")){Be.style.background="",Be.style.border="",Be.style.borderRadius="",Be.style.overflow="",Be.style.boxShadow="";return}let Tn=o.theme?.components?.panel,vo=Jr(o),Vr=($r,bi)=>$r==null||$r===""?bi:zn(vo,$r)??$r,Rm="1px solid var(--persona-border)",yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Wm="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Be.style.background="var(--persona-surface, #ffffff)",Be.style.border=Vr(Tn?.border,Rm),Be.style.borderRadius=Vr(Tn?.borderRadius,Wm),Be.style.boxShadow=Vr(Tn?.shadow,yi),Be.style.overflow="hidden";return}let u=un(o),y=o.launcher?.sidebarMode??!1,M=u||y||(o.launcher?.fullHeight??!1),H=o.launcher?.enabled===!1,O=o.launcher?.detachedPanel===!0,se=o.theme?.components?.panel,ge=o.darkTheme?.components?.panel,ce=ac(o)==="dark"?Zo(se??{},ge??{}):se,be=Jr(o),Ce=(et,Ct)=>et==null||et===""?Ct:zn(be,et)??et,Ae=e.ownerDocument.defaultView??window,Ke=o.launcher?.mobileFullscreen??!0,Pt=o.launcher?.mobileBreakpoint??640,Ft=Ae.innerWidth<=Pt,Dt=Ke&&Ft&&ve,bo=u&&Ke&&Ft,an=o.launcher?.position??"bottom-left",mn=an==="bottom-left"||an==="top-left",io=o.launcher?.zIndex??Jn,bn=(et,Ct,at)=>`var(--persona-components-panel-modes-${et}-${Ct}, ${at})`,zt=ce?.modes?.floating,mr=Ce(zt?.border??ce?.border,bn("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),gr=Ce(zt?.shadow??ce?.shadow,bn("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),Bo=Ce(zt?.borderRadius??ce?.borderRadius,bn("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),Do=O&&!Dt&&!bo,Ss=Dt||bo?"mobile":Do?"floating":u?"docked":y?"sidebar":H?"inline":"floating",hr=ce?.modes?.[Ss];Do?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Xo=Do?mr:y||Dt?"none":mr,As=Do?gr:Dt?"none":y?mn?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":H?"none":gr;u&&!Dt&&!Do&&(As="none",Xo="none");let Tl=Do?Bo:y||Dt?"0":Bo,hi=Ce(hr?.border??ce?.border,bn(Ss,"border",Xo)),q=Ce(hr?.shadow??ce?.shadow,bn(Ss,"shadow",As)),rt=Ce(hr?.borderRadius??ce?.borderRadius,bn(Ss,"borderRadius",Tl)),st=id(),he=st==="detached",qt=st==="welded";e.classList.toggle("persona-artifact-detached-split",he),e.classList.toggle("persona-artifact-welded-split",qt);let Sn="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)))))",Xt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&po(o)&&Ty(o)&&H&&!u;e.classList.toggle("persona-artifact-chat-flush",Xt);let vn=he||Xt?"none":q,Rn=he?mr:qt?"none":hi,Qe=he?Bo:rt;Xt&&(Rn="none",Qe="0");let Qt=hr?.borderRadius!=null&&hr.borderRadius!==""||ce?.borderRadius!=null&&ce.borderRadius!=="",it=Xt&&!Qt?"0":rt,Wn=ye.scrollTop;e.style.cssText="",ot.style.cssText="",Ve.style.cssText="",Be.style.cssText="",ye.style.cssText="",Qi||(gt.style.cssText=""),Ee&&(ye.style.display="none"),(M||H)&&(e.style.minWidth="0");let _o=()=>{if(Wn<=0)return;(ye.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ye.scrollTop===Wn)return;let Ct=ye.scrollHeight-ye.clientHeight;Ct<=0||(ye.scrollTop=Math.min(Wn,Ct))})};if(Dt){ot.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"),ot.style.cssText=`
1193
1193
  position: fixed !important;
1194
1194
  inset: 0 !important;
1195
1195
  width: 100% !important;
@@ -1283,7 +1283,7 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1283
1283
  border-top: none !important;
1284
1284
  padding: 8px 16px 12px 16px !important;
1285
1285
  ${Xt?"background: transparent !important;":""}
1286
- `)}if(!H&&!u){let et="max-height: -moz-available !important; max-height: stretch !important;",Ct=y?"":"padding-top: 1.25em !important;",at=y?"":`z-index: ${o.launcher?.zIndex??Jn} !important;`;ot.style.cssText+=et+Ct+at}dn(),_o()},Df=()=>{e.style.setProperty("--persona-content-max-width",Os(o,Pe()))},kb=!1;function Lb(){o.layout?.topFade&&ye.scrollTop>1?ye.setAttribute("data-persona-top-fade","true"):ye.removeAttribute("data-persona-top-fade")}let _f=()=>{Lb();let a=vh(o,Pe());Pe()&&o.composer?.placement&&o.debug===!0&&!kb&&(kb=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let u=B();e.setAttribute("data-persona-composer-placement",a),e.setAttribute("data-persona-conversation-state",Q),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",u.composerGap??Tu),on()},Pb=()=>{if(Pe())return;let a=un(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!ve)return;let M=e.ownerDocument.defaultView??window,H=o.launcher?.mobileFullscreen??!0,O=o.launcher?.mobileBreakpoint??640;if(H&&M.innerWidth<=O)return;let se=Wi(o);Ve.style.height=se.height,Ve.style.maxHeight=se.maxHeight};Bf(),lc(e,o),_c(e,o),Oc(e,o),Df(),_f(),Qs=()=>{Bf(),Pb(),lc(e,o),_c(e,o),Oc(e,o),Df(),_f(),Jc?e.style.setProperty("--persona-artifact-welded-outer-radius",Jc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),St(),Ht()};let Ue=[];Ue.push(()=>{Cb=!0}),Ue.push(()=>{m.forEach(a=>a()),f.destroy()}),Ue.push(()=>{document.removeEventListener("keydown",Ab)}),Ue.push(()=>{as!==null&&clearTimeout(as)});let lr=null,cr=null;Ue.push(()=>{lr?.(),lr=null,cr?.(),cr=null}),sl&&Ue.push(()=>{sl?.disconnect(),sl=null}),Ue.push(()=>{cl?.(),cl=null,Wf(),pn&&(pn.remove(),pn=null),Et?.element.style.removeProperty("width"),Et?.element.style.removeProperty("maxWidth"),Et?.destroy()}),Ie&&Ue.push(()=>{yt=!0,Fe=null,He!==null&&(cancelAnimationFrame(He),He=null),bt?.destroy(),bt=null,ee?.destroy(),ee=null,Ut=null});let Js=null,Ib=()=>{Js&&(Js(),Js=null),o.colorScheme==="auto"&&(Js=Mu(()=>{lc(e,o)}))};Ib(),Ue.push(()=>{Js&&(Js(),Js=null)}),Ue.push(()=>{S=!0,A?.()}),Ue.push(()=>{z=!0});let Hb=!1;Ue.push(()=>{Hb=!0});let Of=(a,u)=>{let y=uc(a,u);return y||!QA.includes(a)?y:(hM().then(M=>{if(Hb)return;Pi(M.wipe),Pi(M.glyphCycle);let H=uc(a,u);H&&gc(H,e)}).catch(()=>{}),null)},ad=o.features?.streamAnimation;if(ad?.type&&ad.type!=="none"){let a=Of(ad.type,ad.plugins);a&&gc(a,e),Ue.push(()=>JA(e))}let Hr=wc(eo),Rb=wc(uo),Wb=wc(fo),Zs=[Hr,Rb,Wb];Ue.push(()=>{Zs.forEach(a=>a.destroy())});let ei=null,V,ti=null,Bb=!1,Db=0,_b=null,Ob=a=>a.reduce((u,y)=>y.role==="user"?u+1:u,0),Nb=a=>{for(let u=a.length-1;u>=0;u--)if(Ol(a[u]))return a[u].id??null;return null},Fb=!1,L0=()=>{Fb||o.debug!==!0||(Fb=!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".'))},Vb=!1,$b=!1,Ub=(a,u)=>{Vb||o.debug!==!0||!u.enabled||u.expose||Bb||$b&&(V.isStreaming()||a.some(Ol)||(Vb=!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.")))},ni=a=>{if(!V)return;let u=a??V.getMessages(),y=Ae=>{Ae.render([],V,we,u)},M=Ae=>{Zs.forEach(Ke=>{Ke!==Ae&&y(Ke)})};ti&&(Ob(u)>Db||Nb(u)!==_b)&&(ti=null);let H=Hs(o);Ub(u,H);let O=H.enabled?xw(u):null,se=ti??O,ge=ti?"host":"agent";if(se){let Ae=o.suggestions?.followUps,Ke=Ae?.placement??(Ae?"auto":"composer"),Ft=(Ke==="auto"?Pe()?"composer":"after-message":Ke)==="after-message"?Wb:Hr;M(Ft),Ft.render(se,V,we,u,o.suggestionChipsConfig,{source:ge,surface:"followUp",variant:Ae?.variant??"chip",behavior:Ae?.behavior??"send",overflow:Ae?.overflow??"wrap",maxItems:Ae?.maxItems??4,config:o,plugins:p,submitPrompt:Id});return}if(u.some(Ae=>Ae.role==="user")){Zs.forEach(y);return}let ce=o.future?.v5Defaults===!0,be=go(),Ce=o.suggestions?.starters??(ce?{}:void 0);if(Ce){let Ae=Ua(B(),u),Ke=Ce.placement??"auto",Pt=Ke==="auto"?Ae?"welcome":"composer":Ke;if(Pt==="welcome"&&!Ae){L0(),Zs.forEach(y);return}let Ft=Pt==="welcome"?Rb:Hr;M(Ft),Ft.render(Ce.items??o.suggestionChips,V,we,u,o.suggestionChipsConfig,{surface:"starter",variant:Ce.variant??(ce&&!be?"chip":"card"),behavior:Ce.behavior??"send",overflow:Ce.overflow??"wrap",maxItems:Ce.maxItems??(ce&&!be?3:4),config:o,plugins:p,submitPrompt:Id});return}M(Hr),Hr.render(o.suggestionChips,V,we,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:p,submitPrompt:Id})},zb=()=>{ti&&(ti=null,ni())},P0=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){zb();return}let y=V?V.getMessages():[];ti=u,Bb=!0,Db=Ob(y),_b=Nb(y),ni(y)},xo=!1,Yn=UA(),Zi=new Map,oi=new Map,ps=new Map,ri=null,us=null;function si(){if(!ri)return;let a=ri;ri=null,us?.destroy(),us=null,Yn.delete(a),Be.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),V&&Io($e,V.getMessages(),Z)}let ii=0,I0=Oo()!==null,So=Hu(),Ao=0,fs=null,ho=!1,ld=!1,ms=0,Hn=null,ai=null,Nf=!1,ea=!1,li=null,dl=!0,cd=!1,ta=null,dd=!1,gs=()=>{dd=!0,B0()},Ff=null,H0=4,Rr=24,R0=80,W0=1e3,Wr=null,qb=()=>{e.setAttribute("data-persona-scrollbar",Gs()),Gs()!=="on-scroll"&&(Wr!==null&&clearTimeout(Wr),Wr=null,ye.removeAttribute("data-persona-scrollbar-visible"))},B0=()=>{Gs()==="on-scroll"&&(ye.setAttribute("data-persona-scrollbar-visible",""),Wr!==null&&clearTimeout(Wr),Wr=setTimeout(()=>{Wr=null,Zr(ye,Rr)&&ye.removeAttribute("data-persona-scrollbar-visible")},W0))};qb(),Ue.push(()=>{Wr!==null&&clearTimeout(Wr)});let Vf=new Map,$f=!1,pd=null,vt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Ko();let jb=o.voiceRecognition?.autoResume??!1,Uf=()=>V.isVoiceActive()||V.isBargeInActive(),Kb=!1,Br=a=>{L.emit("voice:state",{active:vt.active,source:a,timestamp:Date.now()})},yo=()=>{Te(a=>({...a,voiceState:{active:vt.active,timestamp:Date.now(),manuallyDeactivated:vt.manuallyDeactivated}}))},D0=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Yy(I.voiceState),u=!!a.active,y=Number(a.timestamp??0);vt.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-y<M_&&setTimeout(()=>{vt.active||(vt.manuallyDeactivated=!1,no(o.voiceRecognition?.provider)?V.toggleVoice().then(()=>{vt.active=Uf(),Br("restore"),vt.active?ma():(yo(),Pd(T_,1e4))}):Bd("restore"))},no(o.voiceRecognition?.provider)?0:1e3)},Gb=a=>{Kb=!a.persisted,vt.active&&yo()};typeof window<"u"&&(window.addEventListener("pagehide",Gb),Ue.push(()=>window.removeEventListener("pagehide",Gb)));let _0=()=>V?e0(V.getMessages()).filter(a=>!a.__skipPersist):[],ud=null,Yb=(a,u)=>{typeof console<"u"&&console.error(a,u)},fd=(a,u)=>{let y=()=>{try{let se=a();return!se||typeof se.then!="function"?null:Promise.resolve(se).catch(ge=>{Yb(u,ge)})}catch(se){return Yb(u,se),null}},M=ud,H=M?M.then(()=>y()??void 0):y();if(!H)return;let O=H.finally(()=>{ud===O&&(ud=null)});ud=O};function na(a){if(!x?.save)return;let u=a?e0(a):V?_0():[],y=P&&V?.getResumableHandle();y&&(I={...I,durableResume:{executionId:y.executionId,after:y.lastEventId}});let M={messages:u,metadata:I,artifacts:Lo.artifacts,selectedArtifactId:Lo.selectedId,...ci?{draft:ci}:{}};fd(()=>x.save(M),"[AgentWidget] Failed to persist state:")}let ci,md=()=>!x?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,pl=xA({write:()=>{if(!md())return;let a=Oe.getState(),u=CA({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Cm(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify(ci)&&(ci=u,na())}});function Xb(){md()&&pl.schedule()}function zf(){pl.flush()}function Qb(a){if(!md())return;let u=wA(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(y=>y.id),modelIds:(o.composer?.models??[]).map(y=>y.id),modes:o.composer?.modes??[]});u&&(ci=a,we&&!we.value&&(we.value=u.text,we.dispatchEvent(new Event("input",{bubbles:!0})),ko()),u.selectedModelId&&(Oe.setSelectedModelId(u.selectedModelId),ls?.repaint()),Xc(u.activeModeIds??[]),u.quote&&ar(u.quote),pl.cancel())}function gd(){pl.cancel(),ci&&(ci=void 0,md()&&na())}let oa=null,Jb=()=>ot.querySelector("#persona-scroll-container")||ye,ra=()=>{oa!==null&&(cancelAnimationFrame(oa),oa=null),ho=!1},Zb=()=>{fs!==null&&(cancelAnimationFrame(fs),fs=null),ld=!1,ra()},O0=()=>xo&&jf()&&(Gn()!=="anchor-top"||tl()),qf=()=>{let a=is()||"Jump to latest",u=O0();fn.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),ms>0?(Mn.textContent=String(ms),Mn.style.display="",fn.setAttribute("aria-label",`${a} (${ms} new)`)):(Mn.textContent="",Mn.style.display="none",fn.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},ev=()=>{ms!==0&&(ms=0,qf())},N0=()=>{let a=Hn?.spacerHeight??0;return a<=0?Zr(ye,Rr):bd(a)-ye.scrollTop-ye.clientHeight<=Rr},jf=()=>zo()?!So.isFollowing():!N0(),Kf=()=>!!V&&V.getMessages().length>0,Xn=()=>{if(!Cf()||ss()){fn.parentNode&&fn.remove(),fn.style.display="none";return}fn.parentNode!==Be&&Be.appendChild(fn),Xe();let u=xr(ye)>0&&jf()&&Kf();u?qf():ev(),fn.style.display=u?"":"none"},sa=()=>{So.pause()&&(Zb(),Xn())},dr=()=>{So.resume(),ev(),Xn()},hs=(a=!1)=>{zo()&&Kf()&&So.isFollowing()&&(!a&&!xo||(fs!==null&&(cancelAnimationFrame(fs),fs=null),ld=!0,fs=requestAnimationFrame(()=>{fs=null,ld=!1,So.isFollowing()&&F0(Jb(),a?220:140)})))},tv=(a,u,y,M=()=>!0)=>{let H=a.scrollTop,O=u(),se=O-H;if(ra(),Math.abs(se)<1){ho=!0,a.scrollTop=O,Ao=a.scrollTop,ho=!1;return}let ge=performance.now();ho=!0;let ce=Ce=>1-Math.pow(1-Ce,3),be=Ce=>{if(!M()){ra();return}let Ae=u();Ae!==O&&(O=Ae,se=O-H);let Ke=Ce-ge,Pt=Math.min(Ke/y,1),Ft=ce(Pt),Dt=H+se*Ft;a.scrollTop=Dt,Ao=a.scrollTop,Pt<1?oa=requestAnimationFrame(be):(a.scrollTop=O,Ao=a.scrollTop,oa=null,ho=!1)};oa=requestAnimationFrame(be)},F0=(a,u=500)=>{let y=xr(a)-a.scrollTop;if(Math.abs(y)<1){Ao=a.scrollTop;return}if(Math.abs(y)>=R0){ra(),ho=!0,a.scrollTop=xr(a),Ao=a.scrollTop,ho=!1;return}tv(a,()=>xr(a),u,()=>So.isFollowing())},Gf=()=>{if(!Kf()){Xn();return}let a=Jb();ho=!0,a.scrollTop=xr(a),Ao=a.scrollTop,ho=!1,Xn()},di=a=>{let u=0,y=a;for(;y&&y!==ye;)u+=y.offsetTop,y=y.offsetParent;return u},V0=()=>{let a=ye.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ye.ownerDocument.getSelection()},hd=()=>GA(V0(),ye),Yf=()=>{if(Yc()!=="last-user-turn")return!1;let a=V?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(O=>O.role==="user");if(!u)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),M=ye.querySelector(`[data-message-id="${y}"]`);if(!M)return!1;let H=Math.min(Math.max(0,di(M)-Ks()),xr(ye));return ho=!0,ye.scrollTop=H,Ao=ye.scrollTop,ho=!1,Gn()==="follow"&&!Zr(ye,Rr)&&So.pause(),Xn(),!0},yd=a=>{let u=Math.max(0,Math.round(a));xn.style.height=`${u}px`,xn.style.display=u>0?"":"none",Hn&&(Hn.spacerHeight=Math.max(0,a))},bd=a=>{let u=parseFloat(getComputedStyle(ye).paddingBottom)||0,y=0;for(let H of Array.from(ye.children)){if(H===xn||H.offsetHeight===0)continue;let O=di(H)+H.offsetHeight;O>y&&(y=O)}let M=ye.scrollHeight-a;return y>0?Math.min(y+u,M):M},$0=()=>{if(!Hn||Hn.spacerHeight<=0)return;let a=bd(Hn.spacerHeight),u=Math.max(0,Math.round(ye.scrollTop)+ye.clientHeight-a+Rr);u<Hn.spacerHeight&&(yd(u),Xn())},pi=()=>{ai!==null&&(cancelAnimationFrame(ai),ai=null),ra(),Hn=null,xn.style.height="0px",xn.style.display="none"},nv=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xf=a=>ye.querySelector(`[data-message-id="${nv(a)}"]`),ov=a=>{ai!==null&&cancelAnimationFrame(ai),ai=requestAnimationFrame(()=>{ai=null;let u=nv(a),y=ye.querySelector(`[data-message-id="${u}"]`);if(!y)return;let M=di(y),H=Hn?.spacerHeight??0,O=bd(H),{targetScrollTop:se,spacerHeight:ge}=xh({anchorOffsetTop:M,topOffset:Ks(),viewportHeight:ye.clientHeight,contentHeight:O,slack:Rr});Hn={initialSpacerHeight:ge,contentHeightAtAnchor:O,spacerHeight:ge},yd(ge),tv(ye,()=>y.isConnected?Math.max(0,di(y)-Ks()):se,220)})},ia=()=>{if(Gn()!=="anchor-top"||!Hn||!ta)return;let a=Xf(ta);if(!a)return;ra();let u=Hn.spacerHeight,y=bd(u),{targetScrollTop:M,spacerHeight:H}=xh({anchorOffsetTop:di(a),topOffset:Ks(),viewportHeight:ye.clientHeight,contentHeight:y,slack:Rr});Hn={initialSpacerHeight:H,contentHeightAtAnchor:y,spacerHeight:H},yd(H),ho=!0,ye.scrollTop=M,Ao=ye.scrollTop,ho=!1,Xn()},U0=()=>{if(zo()){if(!So.isFollowing()||Zr(ye,1))return;hs(!xo);return}if(Hn&&Hn.initialSpacerHeight>0){let a=ye.scrollHeight-Hn.spacerHeight,u=YA({initialSpacerHeight:Hn.initialSpacerHeight,contentHeightAtAnchor:Hn.contentHeightAtAnchor,currentContentHeight:a});u!==Hn.spacerHeight&&yd(u)}Xn()},z0=a=>{let u=Gn();u==="follow"?(dr(),hs(!0)):u==="anchor-top"&&(dl=!1,cd=!0,dd=!1,ta=a,ov(a))},q0=()=>{if(Gn()==="anchor-top"){if(cd){dl=!1;return}dl=!0,pi(),dr(),hs(!0)}},j0=96,K0=a=>{if(li===null)return!0;let u=Xf(li),y=Xf(a);if(!u||!y)return!0;let M=di(y)-di(u);return Ks()+M>ye.clientHeight-j0},G0=a=>{if(Gn()!=="anchor-top"||!cd||dd||hd())return;let u=li===null;for(let y of a){if(!u){y.id===li&&(u=!0);continue}if(KA(y)){if(y.id===ta||!K0(y.id))return;ta=y.id,ov(y.id);return}}},Y0=a=>{let u=new Map;a.forEach(y=>{let M=Vf.get(y.id);u.set(y.id,{streaming:y.streaming,role:y.role}),!M&&y.role==="assistant"&&(L.emit("assistant:message",y),!ea&&(Gn()!=="anchor-top"||tl())&&jf()&&(ms+=1,qf(),Xn(),Xs(ms===1?"1 new message below.":`${ms} new messages below.`))),y.role==="assistant"&&M?.streaming&&y.streaming===!1&&L.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(M?y.approval.status!=="pending"&&L.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):L.emit("approval:requested",{approval:y.approval,message:y}))}),Vf.clear(),u.forEach((y,M)=>{Vf.set(M,y)})},ul=(a,u)=>{let y=u==="user"?"user":"assistant",M=o.layout?.messages?.[y],H=M?.width??"content",O=M?.maxWidth??(H==="full"?`var(--persona-message-${y}-max-width, 100%)`:void 0);a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${H}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",H),O?a.style.setProperty("--persona-message-row-max-width",O):a.style.removeProperty("--persona-message-row-max-width")},Dr=(a,u)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${a}`,y.setAttribute("data-wrapper-id",a),ul(y,u),y},X0=(a,u,y)=>{let M=new Set;for(let q of u){let rt=q.variant==="tool"?"tool":q.variant==="reasoning"?"reasoning":null;if(!rt||Es(o,rt)!=="row")continue;let st=rt==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;st?.expandable!==!1&&(M.add(q.id),i.observe(q,rt,rt==="tool"?r:s,st))}let H=document.createElement("div"),se=(()=>{let q=p.find(rt=>rt.renderLoadingIndicator);if(q?.renderLoadingIndicator)return q.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),ge=(q,rt)=>rt==null?!1:typeof rt=="string"?(q.textContent=rt,!0):(q.appendChild(rt),!0),ce=new Set,be=new Map,Ce=new Set,Ae=p.some(q=>q.renderAskUserQuestion),Ke=[],Pt=[],Ft=o.enableComponentStreaming!==!1,Dt=o.approval!==!1,bo=[],an=o.messageActions,mn=an?.showRegenerate===!0&&an.enabled!==!1&&Po.current?.isStreaming()!==!0?gS(u):null,io=an?.showEdit===!0&&an.enabled!==!1,bn=an?.showQuote===!0&&an.enabled!==!1,zt=null,mr=o.features?.reasoningDisplay?.completedVisibility,gr=q=>mr==="removed"?!0:mr==="removed-when-short"?tw(q,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Bo=o.features?.toolCallDisplay?.completedVisibility==="removed",Do=q=>q.variant==="reasoning"&&q.reasoning?.status==="complete"?gr(q.reasoning):Bo&&q.variant==="tool"&&q.toolCall?.status==="complete";if(u.forEach(q=>{if(Do(q))return;if(ce.add(q.id),be.set(q.id,q.role),ri===q.id&&us){let it=Dr(q.id,q.role);it.setAttribute("data-persona-message-edit-stub","true"),it.setAttribute("data-preserve-runtime","true"),H.appendChild(it),zt={messageId:q.id,element:us.element};return}let rt=Ae&&Mi(q),st=Dt&&q.variant==="approval"&&!!q.approval,he=!rt&&q.role==="assistant"&&!q.variant&&Ft&&Gy(q);!st&&ps.has(q.id)&&(a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime"),ps.delete(q.id)),!he&&oi.has(q.id)&&(a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime"),oi.delete(q.id));let qt=Mi(q)?`:${q.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${q.agentMetadata?.askUserQuestionAnswers?Object.keys(q.agentMetadata.askUserQuestionAnswers).length:0}`:"",Sn={canRegenerate:mn===q.id,canEdit:io&&Yg(q),canQuote:bn&&!q.variant&&(q.content?.trim().length??0)>0},to=`${Sn.canRegenerate?"r":""}${Sn.canEdit?"e":""}${Sn.canQuote?"q":""}`,On=$A(q,ii)+qt+`:${to}`,Xt=rt||st||he?null:zA(Yn,q.id,On);if(Xt){H.appendChild(Xt.cloneNode(!0)),Mi(q)&&q.toolCall?.id&&q.agentMetadata?.awaitingLocalTool===!0&&!q.agentMetadata?.askUserQuestionAnswered&&(Ce.add(q.toolCall.id),Rf(q));return}let vn=null,Rn=p.find(it=>!!(q.variant==="reasoning"&&it.renderReasoning||q.variant==="tool"&&it.renderToolCall||!q.variant&&it.renderMessage)),Qe=o.layout?.messages;if(Mi(q)&&q.agentMetadata?.askUserQuestionAnswered===!0){Zi.delete(q.id),a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ol(q)&&Hs(o).enabled)return;if(Mi(q)&&o.features?.askUserQuestion?.enabled!==!1){let it=p.find(Wn=>typeof Wn.renderAskUserQuestion=="function");if(it&&Po.current){let Wn=Zi.get(q.id),_o=Wn!==On,Nn=null;if(_o){let{payload:Ct,complete:at}=Aa(q),Ms=q.id,Tn=()=>Po.current?.getMessages().find(vo=>vo.id===Ms);Nn=it.renderAskUserQuestion({message:q,payload:Ct,complete:at,resolve:vo=>{let Vr=Tn();Vr&&Po.current?.resolveAskUserQuestion(Vr,vo)},dismiss:()=>{let vo=Tn();vo?.agentMetadata?.awaitingLocalTool&&(Po.current?.markAskUserQuestionResolved(vo),Po.current?.resolveAskUserQuestion(vo,"(dismissed)"))},config:o})}let jt=Wn!=null;if(_o&&Nn===null&&!jt){q.agentMetadata?.awaitingLocalTool===!0&&!q.agentMetadata?.askUserQuestionAnswered&&(Ce.add(q.toolCall.id),Rf(q));return}let et=Dr(q.id,q.role);et.setAttribute("data-ask-plugin-stub","true"),et.setAttribute("data-preserve-runtime","true"),H.appendChild(et),Ke.push({messageId:q.id,fingerprint:On,bubble:Nn});return}else{q.agentMetadata?.awaitingLocalTool===!0&&!q.agentMetadata?.askUserQuestionAnswered&&(Ce.add(q.toolCall.id),Rf(q));return}}else if(st){let it=D();if(!it){H.appendChild(Dr(q.id,q.role));return}let Wn=p.find(et=>typeof et.renderApproval=="function")??C,Nn=ps.get(q.id)!==On,jt=null;if(Nn&&Wn?.renderApproval){let et=q.id,Ct=(at,Ms)=>{let Tn=Po.current?.getMessages().find(vo=>vo.id===et);Tn?.approval&&(Tn.approval.toolType==="webmcp"?Po.current?.resolveWebMcpApproval(Tn.id,at):Po.current?.resolveApproval(Tn.approval,at,Ms))};jt=Wn.renderApproval({message:q,defaultRenderer:()=>it.createApprovalBubble(q,o,l),config:o,approve:at=>Ct("approved",at),deny:at=>Ct("denied",at)})}if(Nn&&jt===null)a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime"),ps.delete(q.id),vn=it.createApprovalBubble(q,o,l);else{let et=Dr(q.id,q.role);et.setAttribute("data-approval-plugin-stub","true"),et.setAttribute("data-preserve-runtime","true"),H.appendChild(et),bo.push({messageId:q.id,fingerprint:On,bubble:jt});return}}else if(Rn)if(q.variant==="reasoning"&&q.reasoning&&Rn.renderReasoning){if(!le)return;vn=Rn.renderReasoning({message:q,defaultRenderer:()=>Xh(q,o,s),config:o})}else if(q.variant==="tool"&&q.toolCall&&Rn.renderToolCall){if(!Me)return;vn=Rn.renderToolCall({message:q,defaultRenderer:()=>ey(q,o,r),config:o})}else Rn.renderMessage&&(vn=Rn.renderMessage({message:q,defaultRenderer:()=>{let it=Nh(q,y,Qe,o.messageActions,jn,{loadingIndicatorRenderer:se,widgetConfig:o,actionEligibility:Sn});return q.role!=="user"&&W(it,q,o,V),it},config:o}));if(!vn&&he){let it=QE(q);if(it){let Wn=oi.get(q.id),_o=Wn!==On,Nn=o.wrapComponentDirectiveInBubble!==!1&&sr.getOptions(it.component)?.bubbleChrome!==!1,jt=null;if(_o){let et=YE(it,{config:o,message:q,transform:y});if(et&&it.component==="PersonaArtifactInline"){let Ct=et.hasAttribute("data-artifact-inline")?et:et.querySelector("[data-artifact-inline]"),at=Ct?.getAttribute("data-artifact-inline")??"",Ms=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(at):at,Tn=at?a.querySelector(`#wrapper-${q.id}`)?.querySelector(`[data-artifact-inline="${Ms}"]`)??null:null;Ct&&Tn&&Tn!==Ct&&ts()?.hasLiveInlineArtifactBlock(Tn)&&(Ct===et?et=Tn:Ct.replaceWith(Tn))}if(et)if(Nn){let Ct=document.createElement("div");if(Ct.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ct.id=`bubble-${q.id}`,Ct.setAttribute("data-message-id",q.id),q.content&&q.content.trim()){let at=document.createElement("div");at.className="persona-mb-3 persona-text-sm persona-leading-relaxed",at.innerHTML=y({text:q.content,message:q,streaming:!!q.streaming,raw:q.rawContent}),Ct.appendChild(at)}Ct.appendChild(et),jt=Ct}else{let Ct=document.createElement("div");if(Ct.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ct.id=`bubble-${q.id}`,Ct.setAttribute("data-message-id",q.id),Ct.setAttribute("data-persona-component-directive","true"),q.content&&q.content.trim()){let at=document.createElement("div");at.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",at.innerHTML=y({text:q.content,message:q,streaming:!!q.streaming,raw:q.rawContent}),Ct.appendChild(at)}Ct.appendChild(et),jt=Ct}}if(jt||Wn!=null){let et=Dr(q.id,q.role);et.setAttribute("data-component-directive-stub","true"),et.setAttribute("data-preserve-runtime","true"),H.appendChild(et),Pt.push({messageId:q.id,fingerprint:On,bubble:jt});return}}}if(!vn)if(q.variant==="reasoning"&&q.reasoning){if(!le)return;vn=Xh(q,o,s)}else if(q.variant==="tool"&&q.toolCall){if(!Me)return;vn=ey(q,o,r)}else if(q.variant==="approval"&&q.approval){if(o.approval===!1)return;let it=D();if(!it)return;vn=it.createApprovalBubble(q,o,l)}else{let it=o.layout?.messages;it?.renderUserMessage&&q.role==="user"?vn=it.renderUserMessage({message:q,config:o,streaming:!!q.streaming}):it?.renderAssistantMessage&&q.role==="assistant"?vn=it.renderAssistantMessage({message:q,config:o,streaming:!!q.streaming}):vn=Nh(q,y,it,o.messageActions,jn,{loadingIndicatorRenderer:se,widgetConfig:o,actionEligibility:Sn}),q.role!=="user"&&vn&&W(vn,q,o,V)}let Qt=Dr(q.id,q.role);Qt.appendChild(vn),qA(Yn,q.id,On,Qt),H.appendChild(Qt)}),wt.composerOverlay&&wt.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(rt=>{let st=rt.getAttribute("data-persona-ask-sheet-for");st&&!Ce.has(st)&&Ei(wt.composerOverlay,st)}),o.features?.toolCallDisplay?.grouped){let q=[],rt=[],st=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(he=>{if(he.variant==="tool"&&he.toolCall&&Me){if(Bo&&he.toolCall.status==="complete")return;rt.push(he);return}he.variant==="reasoning"&&(!le||he.reasoning?.status==="complete"&&gr(he.reasoning))||((rt.length>1||st&&rt.length>0)&&q.push(rt),rt=[])}),(rt.length>1||st&&rt.length>0)&&q.push(rt),q.forEach(he=>{let qt=he.map(Qe=>Array.from(H.children).find(Qt=>Qt instanceof HTMLElement&&Qt.getAttribute("data-wrapper-id")===Qe.id)).filter(Qe=>!!Qe);if(qt.length<(st?1:2))return;let Sn=Dr(`tool-group-${he[0].id}`,"assistant");if(Sn.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Qe=`tool-group-${he[0].id}`,Qt=he.some(jt=>jt.toolCall?.status!=="complete"),it={...he[0],id:Qe,toolCall:{id:Qe,name:`${he.length} tools`,status:Qt?"running":"complete",chunks:he.flatMap(jt=>jt.toolCall?.chunks??[]),success:!he.some(jt=>jt.toolCall?.success===!1)}};M.add(Qe),i.observe(it,"tool",r,o.features.toolCallDisplay);let Wn=`${Qt?"Using":"Used"} ${he.length} tools`,_o=o.toolCall?.renderGroupedSummary?.({messages:he,toolCalls:he.map(jt=>jt.toolCall),defaultSummary:Wn,config:o}),Nn=IC(it,o,r.has(Qe),_o??Wn);Nn.bubble.classList.add("persona-tool-group"),Nn.body.dataset.personaToolGroupStack="true",qt[0].before(Sn),Sn.appendChild(Nn.bubble),qt.forEach((jt,et)=>{jt.style.setProperty("--persona-message-row-max-width","100%"),jt.style.setProperty("--persona-activity-stagger",`${et*40}ms`),jt.classList.add("persona-activity-group-child"),Nn.body.appendChild(jt)});return}let to=document.createElement("div");to.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",to.setAttribute("data-persona-tool-group","true");let On=document.createElement("div");On.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",On.id=`tool-group-summary-${he[0].id}`;let Xt=`Called ${he.length} ${he.length===1?"tool":"tools"}`,vn=o.toolCall?.renderGroupedSummary?.({messages:he,toolCalls:he.map(Qe=>Qe.toolCall).filter(Qe=>!!Qe),defaultSummary:Xt,config:o});ge(On,vn)||(On.textContent=Xt);let Rn=document.createElement("div");Rn.className="persona-tool-group-stack persona-flex persona-flex-col",Rn.id=`tool-group-stack-${he[0].id}`,Rn.setAttribute("data-persona-tool-group-stack","true"),to.appendChild(On),st||to.appendChild(Rn),Sn.appendChild(to),qt[0].before(Sn),qt.forEach((Qe,Qt)=>{if(st){Qe.remove();return}Qe.style.setProperty("--persona-message-row-max-width","100%");let it=document.createElement("div");it.className="persona-tool-group-item persona-relative",it.setAttribute("data-persona-tool-group-item","true"),Qt<qt.length-1&&it.setAttribute("data-persona-tool-group-connector","true"),it.appendChild(Qe),Rn.appendChild(it)})})}i.prune(M),jA(Yn,ce);let Ss=q=>q.variant==="tool"&&!Me||q.variant==="reasoning"&&!le||Do(q),hr=u.some(q=>q.role==="assistant"&&q.streaming&&!Ss(q)),Xo=u.length-1;for(;Xo>=0&&Ss(u[Xo]);)Xo--;let As=Xo>=0?u[Xo]:void 0,Tl=Xo<u.length-1,hi=As?.role==="assistant"&&!As.streaming&&As.variant!=="approval"&&!Tl;if(xo&&u.some(q=>q.role==="user")&&!hr&&!hi){let q={config:o,streaming:!0,location:"standalone",defaultRenderer:Mc},rt=p.find(he=>he.renderLoadingIndicator),st=null;if(rt?.renderLoadingIndicator&&(st=rt.renderLoadingIndicator(q)),st===null&&o.loadingIndicator?.render&&(st=o.loadingIndicator.render(q)),st===null&&(st=Mc()),st){let he=document.createElement("div"),qt=o.loadingIndicator?.showBubble!==!1,Sn=o.layout?.messages?.layout??"bubble";he.className=qt?Tc("assistant",Sn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),he.setAttribute("data-typing-indicator","true"),qt&&(he.style.color="var(--persona-message-assistant-text, var(--persona-text))",Sn!=="flat"&&(he.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),he.appendChild(st);let to=Dr("typing-indicator","assistant");to.appendChild(he),H.appendChild(to)}}if(!xo&&u.length>0){let q=u[u.length-1],rt={config:o,lastMessage:q,messageCount:u.length},st=p.find(qt=>qt.renderIdleIndicator),he=null;if(st?.renderIdleIndicator&&(he=st.renderIdleIndicator(rt)),he===null&&o.loadingIndicator?.renderIdle&&(he=o.loadingIndicator.renderIdle(rt)),he){let qt=document.createElement("div"),Sn=o.loadingIndicator?.showBubble!==!1;qt.className=Sn?["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(" "),qt.setAttribute("data-idle-indicator","true"),qt.appendChild(he);let to=Dr("idle-indicator","assistant");to.appendChild(qt),H.appendChild(to)}}if(KC(H),Iu(a,H),tg(a),zt){let{messageId:q,element:rt}=zt,st=a.querySelector(`#wrapper-${q}`);st&&rt.parentElement!==st&&(ul(st,be.get(q)??"user"),st.replaceChildren(rt))}if(Ke.length>0)for(let{messageId:q,fingerprint:rt,bubble:st}of Ke){let he=a.querySelector(`#wrapper-${q}`);he&&(ul(he,be.get(q)??"assistant"),st!==null&&(he.replaceChildren(st),he.setAttribute("data-bubble-fp",rt),Zi.set(q,rt)))}if(Zi.size>0)for(let q of Zi.keys())ce.has(q)||Zi.delete(q);if(Pt.length>0)for(let{messageId:q,fingerprint:rt,bubble:st}of Pt){let he=a.querySelector(`#wrapper-${q}`);he&&(ul(he,be.get(q)??"assistant"),st!==null&&(he.replaceChildren(st),he.setAttribute("data-bubble-fp",rt),oi.set(q,rt)))}if(oi.size>0)for(let q of oi.keys())ce.has(q)||oi.delete(q);if(bo.length>0)for(let{messageId:q,fingerprint:rt,bubble:st}of bo){let he=a.querySelector(`#wrapper-${q}`);he&&(ul(he,be.get(q)??"assistant"),st!==null&&(he.replaceChildren(st),he.setAttribute("data-bubble-fp",rt),ps.set(q,rt)))}if(ps.size>0)for(let q of ps.keys())ce.has(q)||ps.delete(q)},Qf=!1,vd=()=>{Qf||(Qf=!0,ki().catch(()=>{}),NC().catch(()=>{Qf=!1}))},Io=(a,u,y)=>{u.length>0&&vd(),X0(a,u,y),vb()},fl=null,Q0=()=>{if(fl)return;let a=y=>{let M=y.composedPath();M.includes(ot)||cn&&M.includes(cn)||Yt(!1,"user")};fl=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},rv=()=>{if(!fl)return;(e.ownerDocument??document).removeEventListener("pointerdown",fl,!0),fl=null};Ue.push(()=>rv());let ml=null,J0=()=>{if(ml)return;let a=y=>{y.key==="Escape"&&(y.isComposing||Yt(!1,"user"))};ml=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},sv=()=>{if(!ml)return;(e.ownerDocument??document).removeEventListener("keydown",ml,!0),ml=null};Ue.push(()=>sv());let gl=!1,iv=new Set,Z0=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},aa=()=>{if(!Pe())return;let a=wt.peekBanner,u=wt.peekTextNode;if(!a||!u)return;if(U){a.classList.remove("persona-pill-peek--visible");return}let y=V?.getMessages()??[],M;for(let an=y.length-1;an>=0;an--){let mn=y[an];if(mn.role==="assistant"&&mn.content){M=mn;break}}if(!M){a.classList.remove("persona-pill-peek--visible");return}let H=M.content,O=!!M.streaming,se=Z0(),ge=Bu(se),ce=ge.type!=="none"?Of(ge.type,se?.plugins):null,be=ce?.isAnimating?.(M)===!0,Ce=ce!==null&&(O||be);Ce&&ce&&!iv.has(ce.name)&&(gc(ce,e),iv.add(ce.name));let Ae=Ce&&ce?.containerClass?ce.containerClass:null,Ke=u.dataset.personaPeekStreamClass??null;Ke&&Ke!==Ae&&(u.classList.remove(Ke),delete u.dataset.personaPeekStreamClass),Ae&&Ke!==Ae&&(u.classList.add(Ae),u.dataset.personaPeekStreamClass=Ae),Ce?(u.style.setProperty("--persona-stream-step",`${ge.speed}ms`),u.style.setProperty("--persona-stream-duration",`${ge.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Pt=Ce?Du(H,ge.buffer,ce,M,O):H;if(Ce&&ge.placeholder==="skeleton"&&O&&(!Pt||!Pt.trim())){let an=document.createElement("div"),mn=mc();mn.classList.add("persona-pill-peek__skeleton"),an.appendChild(mn),Iu(u,an)}else{let an=Math.max(0,Pt.length-100),mn=Pt.length>100?Pt.slice(-100):Pt,io=jr(mn);if(!Ce||!ce){let bn=Pt.length>100?`\u2026${mn}`:mn;u.textContent!==bn&&(u.textContent=bn)}else{let bn=io;(ce.wrap==="char"||ce.wrap==="word")&&(bn=fc(io,ce.wrap,`peek-${M.id}`,{skipTags:ce.skipTags,startIndex:an}));let zt=document.createElement("div");if(zt.innerHTML=bn,ce.useCaret&&mn.length>0){let mr=_u(),gr=zt.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bo=gr[gr.length-1];Bo?.parentNode?Bo.parentNode.insertBefore(mr,Bo.nextSibling):zt.appendChild(mr)}Iu(u,zt),ce.onAfterRender?.({container:u,bubble:a,messageId:M.id,message:M,speed:ge.speed,duration:ge.duration})}}let bo=xo||gl;a.classList.toggle("persona-pill-peek--visible",bo)};if(Pe()){let a=wt.peekBanner;if(a){let M=H=>{H.preventDefault(),H.stopPropagation(),Yt(!0,"user")};a.addEventListener("pointerdown",M),Ue.push(()=>{a.removeEventListener("pointerdown",M)})}let u=()=>{gl||(gl=!0,aa())},y=()=>{gl&&(gl=!1,aa())};Ve.addEventListener("pointerenter",u),Ve.addEventListener("pointerleave",y),Ue.push(()=>{Ve.removeEventListener("pointerenter",u),Ve.removeEventListener("pointerleave",y)}),cn&&(cn.addEventListener("pointerenter",u),cn.addEventListener("pointerleave",y),Ue.push(()=>{cn.removeEventListener("pointerenter",u),cn.removeEventListener("pointerleave",y)}))}let ek=a=>{let u=o.launcher?.composerBar??{},y=u.expandedSize??"anchored",M=u.bottomOffset??"16px",H=u.collapsedMaxWidth,O=u.expandedMaxWidth??"880px",se=u.expandedTopOffset??"5vh",ge=u.modalMaxWidth??"880px",ce=u.modalMaxHeight??"min(90vh, 800px)",be="calc(100vw - 32px)",Ce="var(--persona-pill-area-height, 80px)",Ae=ot.style;if(Ae.left="",Ae.right="",Ae.top="",Ae.bottom="",Ae.transform="",Ae.width="",Ae.maxWidth="",Ae.height="",Ae.maxHeight="",cn){let Ke=cn.style;Ke.bottom=M,Ke.width=H??""}if(a&&y!=="fullscreen"){if(y==="modal"){Ae.top="50%",Ae.left="50%",Ae.transform="translate(-50%, -50%)",Ae.bottom="auto",Ae.right="auto",Ae.width=ge,Ae.maxWidth=be,Ae.maxHeight=ce,Ae.height=ce;return}Ae.left="50%",Ae.transform="translateX(-50%)",Ae.bottom=`calc(${M} + ${Ce})`,Ae.top=se,Ae.width=O,Ae.maxWidth=be}},hl=()=>{if(U&&vd(),!Se())return;if(Pe()){let be=(o.launcher?.composerBar??{}).expandedSize??"anchored",Ce=U?"expanded":"collapsed";ot.dataset.state=Ce,ot.dataset.expandedSize=be,cn&&(cn.dataset.state=Ce,cn.dataset.expandedSize=be),ot.style.removeProperty("display"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ek(U),Be.style.display=U?"flex":"none",Qs(),U?(Q0(),J0()):(rv(),sv()),aa();return}let a=un(o),u=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,M=o.launcher?.mobileFullscreen??!0,H=u.innerWidth<=y,O=M&&H&&ve,se=$o(o).reveal;U?(ot.style.removeProperty("display"),ot.style.display=a?"flex":"",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-95","persona-opacity-0"),Ve.classList.add("persona-scale-100","persona-opacity-100"),hn?(hn.setPanelOpen(!0),hn.element.style.display="none"):so&&(so.style.display="none")):(a?a&&(se==="overlay"||se==="push")&&!O?(ot.style.removeProperty("display"),ot.style.display="flex",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.setProperty("display","none","important"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.display="",ot.classList.add("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-100","persona-opacity-100"),Ve.classList.add("persona-scale-95","persona-opacity-0")),hn?(hn.setPanelOpen(!1),hn.element.style.display=a?"none":""):so&&(so.style.display=a?"none":""))},Yt=(a,u="user")=>{if(!Se()||U===a)return;let y=U;U=a,hl();let M=(()=>{let O=o.launcher?.sidebarMode??!1,se=e.ownerDocument.defaultView??window,ge=o.launcher?.mobileFullscreen??!0,ce=o.launcher?.mobileBreakpoint??640,be=se.innerWidth<=ce,Ce=un(o)&&ge&&be,Ae=Pe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return O||ge&&be&&ve||Ce||Ae})();if(U&&M){if(!lr){let O=e.getRootNode(),se=O instanceof ShadowRoot?O.host:e.closest(".persona-host");se&&(lr=Lh(se,o.launcher?.zIndex??Jn))}cr||(cr=Ph(e.ownerDocument))}else U||(lr?.(),lr=null,cr?.(),cr=null);U&&(Sl(),Yf()||(Gn()==="follow"?hs(!0):Gf()));let H={open:U,source:u,timestamp:Date.now()};U&&!y?L.emit("widget:opened",H):!U&&y&&L.emit("widget:closed",H),L.emit("widget:state",{open:U,launcherEnabled:ve,voiceActive:vt.active,streaming:V.isStreaming()})},ys={inputDisabled:!1,sendDisabled:!1},pr=()=>ys.inputDisabled,Jf=()=>no(o.voiceRecognition?.provider)&&!!V&&(V.isBargeInActive()||["listening","processing","speaking"].includes(V.getVoiceStatus())),ui=()=>ys.inputDisabled||ys.sendDisabled,tk=()=>(ys.inputDisabled?ys.inputReason:void 0)??(ys.sendDisabled?ys.sendReason:void 0);function Zf(){if(!ze)return;if(Oe.getState().phase==="streaming"){ze.disabled=!1;return}let a=ut?!ut.isReady():!1;ze.disabled=ui()||a}function Cd(){if(!ro)return;let a=Oe.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;ro.toggleAttribute("data-persona-send-hidden",u)}function nk(){let a=tk();if(Pe()){let u=Pn??gt;a?u.setAttribute("title",a):u.removeAttribute("title"),gt.toggleAttribute(Ja,!!a);return}if(a){Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.setAttribute(Ja,""),Mt.removeAttribute(qc),Mt.textContent=a,xi(Mt,o.statusIndicator??{},"idle");return}if(Mt.hasAttribute(Ja)&&(Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),Mt.removeAttribute(Ja),g)){let u=V.getStatus();Tr(Mt,oo(u),o.statusIndicator??{},u)}}function em(){let a=Sg(o.composer?.inputDisabled),u=Sg(o.composer?.sendDisabled);ys={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},Oe.setInputDisabled(a.disabled),Oe.setSendDisabled(u.disabled);let y=Oe.getState().phase==="streaming",M=a.disabled,H=y||M;we&&(we instanceof HTMLTextAreaElement?we.disabled=M:we.setAttribute("contenteditable",M?"false":"true"),we.setAttribute("aria-disabled",M?"true":"false")),Zt&&(Zt.disabled=M),Gt&&(Gt.disabled=M);for(let O of Rt?.affordanceButtons??[])O.querySelectorAll("button").forEach(se=>{se.disabled=M});De&&(De.disabled=M||y&&!Jf()),Zs.forEach(O=>{O.elements.forEach(se=>{se.toggleAttribute("data-disabled",H),se instanceof HTMLButtonElement||se.setAttribute("aria-disabled",H?"true":"false")}),O.buttons.forEach(se=>{se.disabled=H})}),im.forEach(O=>{O.toggleAttribute("data-disabled",H),O instanceof HTMLButtonElement?O.disabled=H:O.setAttribute("aria-disabled",H?"true":"false"),O.querySelectorAll("button").forEach(se=>{se.disabled=H})}),gt.dataset.personaComposerStreaming=y?"true":"false",gt.dataset.personaComposerInputDisabled=M?"true":"false",gt.dataset.personaComposerSendDisabled=ui()?"true":"false",gt.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(O=>{(O instanceof HTMLButtonElement||O instanceof HTMLInputElement||O instanceof HTMLTextAreaElement||O instanceof HTMLSelectElement)&&(O.disabled=y)}),Zf(),nk()}let yl=a=>{Oe.setStreaming(a),Kc(a?"stop":"send"),em()},wd=()=>{vt.active||we&&we.focus()};L.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>wd(),200)});let av=null,tm=!1,nm=!$.hidden,bs=null,om=!J,xd=null;Ue.push(()=>{xd?.cancel(),xd=null});let ok=a=>{let u=_M(a);if(u===Q)return;Q=u,e.setAttribute("data-persona-conversation-state",u);let y=Le();on(),om&&(xd?.cancel(),xd=BM(gt,u==="active"?y:Le(),u==="active"?"drop":"rise",B().layout==="centered"?320:260)),ia()},lv=null,cv,dv=null,la=null,rm=!1,bl=a=>{let u=B(),y=`${u.variant}|${u.layout}|${u.dismiss}|${u.anchor??"bottom"}|${u.align??""}|${u.iconPlacement}|${u.kicker??""}|${u.title}|${u.subtitle}`;(y!==lv||u.icon!==cv)&&(lv=y,cv=u.icon,qu({host:$,iconHolder:me,kicker:ft,title:pt,subtitle:An,starterSuggestions:uo},u));let M=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;M!==dv&&(dv=M,ju(Ne,u.message,o));let H=a??(V?V.getMessages():o.initialMessages);ok(H);let O=tm,se=!O&&Ua(u,H),ge=se!==nm;if(nm=se,la){bs?.cancel(),bs=null,O!==rm&&(rm=O,O?$h(ye,$,null):Vh(ye,$,la)),$a(ye,$,!O);return}if(ge&&!se&&!O&&u.dismiss==="on-first-message"&&om){bs=WM($,be=>{bs===be&&(bs=null),!nm&&!la&&($a(ye,$,!1),ia()),be?.cancel()});return}if(bs){if(!se&&!O)return;bs.cancel(),bs=null}let ce=!$.hidden;$a(ye,$,se),!se&&ce&&ia()},sm=[],im=[],am=!1,pv=null,uv,fv=()=>{im.length=0;let a=sm.splice(0,sm.length);for(let u of a)try{u()}catch(y){console.warn("[persona] renderWelcome cleanup threw",y)}};Ue.push(fv);let rk=(a,u)=>{let y=Hh(a,u);if(!y)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let M=o.suggestions?.starters,H=Rh({item:{...y,behavior:y.behavior??M?.behavior??"send"},index:u,surface:"starter",source:"config",variant:M?.variant??"card",streaming:g?V.isStreaming():!1,config:o,plugins:p,chipsConfig:o.suggestionChipsConfig,session:V,getTextarea:()=>we,eventTarget:$,submitPrompt:Id});return im.push(H),H},lm=()=>{if(am)return;am=!0;let a=B();pv=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,uv=a.icon;try{fv(),$h(ye,$,la),la=null,rm=!1;let u=V?V.getMessages():o.initialMessages,y=Ua(a,u),M=0,H=null;for(let O of p)if(O.renderWelcome&&(H=O.renderWelcome({config:a,variant:a.variant,visible:y,defaultRenderer:()=>$,sendMessage:se=>{if(!V||V.isStreaming())return;let ge=se.trim();ge&&V.sendMessage(ge)},requestRender:()=>lm(),renderStarter:se=>rk(se,M++),storage:h(O.id),onCleanup:se=>{sm.push(se)}}),H))break;H&&H!==$&&(la=H,Vh(ye,$,H))}finally{am=!1}bl()},sk=()=>{let a=B();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===pv&&a.icon===uv||lm()},Sd=()=>{bl(),Qi||(we.placeholder=gA(Oe.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(ze.textContent=o.copy?.sendButtonLabel??"Send")),we.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',we.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},ik=!!o.setStoredConversationId,ca=a=>Te(u=>{let y={...u};return delete y[a],y}),Ad=a=>{let u=I[a];return typeof u=="string"?u:null},mv=()=>{let a=I.durableResume;if(!a||typeof a!="object")return null;let u=a;return typeof u.executionId=="string"&&u.executionId.length>0&&typeof u.after=="string"&&u.after.length>0?{executionId:u.executionId,after:u.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:a=>{Te(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ca("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{Te(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ca("conversationId"))});let gv=()=>o.clientToken??null,hv=a=>bE(a,Tt(),o.persistState===!1),yv=gv(),Ho=yv?hv(yv):null,ak=()=>{let a=I.pendingDisplayProjections;if(!a||typeof a!="object")return null;let u=a;return typeof u.conversationId!="string"||!Array.isArray(u.messageIds)?null:{conversationId:u.conversationId,messageIds:u.messageIds.filter(y=>typeof y=="string")}},vs={...Ho?{visitorStore:Ho}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!hf()?Promise.all([j,K]).then(()=>{}):j,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){ca("historyMessageCursor");return}Te(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:ak,setPendingDisplayProjections:a=>{if(!a){ca("pendingDisplayProjections");return}Te(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:mv,setStoredResumableHandle:a=>{if(!a){ca("durableResume");return}Te(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>P&&mv()!==null,...ik?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){ca("conversationRevision");return}Te(u=>({...u,conversationRevision:a}))}}};if(P){let a=o.onExecutionState,u=e.ownerDocument.defaultView,y=!1,M=()=>y=!0,H=()=>y=!1;u?.addEventListener("pagehide",M),u?.addEventListener("pageshow",H),Ue.push(()=>{u?.removeEventListener("pagehide",M),u?.removeEventListener("pageshow",H)}),o={...o,reconnectStream:o.reconnectStream??(O=>V.getClient().reconnectClientTokenStream(O)),onExecutionState:O=>{(O||!y)&&vs.setStoredResumableHandle?.(O?{executionId:O.executionId,after:O.lastEventId}:null),a?.(O)}}}let lk=()=>{let a=gv();if(a&&Ho?.matches(a,Tt(),o.persistState===!1)||!a&&!Ho)return;Ho?.destroy(),Ho=a?hv(a):null;let u={...vs};Ho?u.visitorStore=Ho:delete u.visitorStore,vs=u,V.setHistoryInternals(vs)},fi=null,ck=()=>{fi==null&&(fi=setInterval(()=>{let a=$e.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(fi),fi=null;return}let u=Date.now();a.forEach(y=>{let M=Number(y.getAttribute("data-tool-elapsed"));M&&(y.textContent=y.closest(".persona-activity-row")?Pl(u-M):dp(u-M))})},100))},cm=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((se,ge)=>cm(se,u[ge]));let y=a,M=u,H=Object.keys(y),O=Object.keys(M);return H.length===O.length&&H.every(se=>Object.prototype.hasOwnProperty.call(M,se)&&cm(y[se],M[se]))},bv=a=>{let{content:u,rawContent:y,llmContent:M,...H}=a;return H},dm=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Gy(a),dk=(a,u,y)=>{if(a.length!==u.length)return!1;let M=a[y.index],H=u[y.index];return!M||!H||M.id!==y.id||H.id!==y.id?!1:(!Object.is(M.content,H.content)||!Object.is(M.rawContent,H.rawContent)||!Object.is(M.llmContent,H.llmContent))&&dm(M)&&dm(H)&&cm(bv(M),bv(H))},Md=null,da=null,mi=null,_r=null,pm=null,pk=a=>{if(!P)return na(a);pm=a,queueMicrotask(()=>{pm===a&&(pm=null,na(a))})},Td=a=>{Md=a;let u,y;da=null;for(let H=a.length-1;H>=0;H-=1){let O=a[H];if(!u&&O.role==="user"&&(u=O),!y&&O.role==="assistant"&&(y=O),!da&&dm(O)&&(da={index:H,id:O.id}),u&&y&&da)break}Io($e,a,Z),ts()?.updateInlineArtifactBlocks($e,Lo.artifacts,{suppressTransition:xo}),ck(),bl(a),ni(a),hs(!xo),Y0(a),a.length===0&&(pi(),dl=!0,cd=!1,ta=null,dd=!1),!Nf||ea?(Nf=!0,li=u?.id??null,Ff=y?.id??null):u&&u.id!==li?(li=u.id,z0(u.id)):y&&y.id!==Ff&&q0(),y&&(Ff=y.id),G0(a);let M=vt.lastUserMessageId;u&&u.id!==M&&(vt.lastUserMessageId=u.id,L.emit("user:message",u)),vt.lastUserMessageWasVoice=!!u?.viaVoice,pk(a),aa()},um=()=>{_r!==null&&(cancelAnimationFrame(_r),_r=null);let a=mi;mi=null,a&&Td(a)},vv=()=>{_r!==null&&cancelAnimationFrame(_r),_r=null,mi=null},uk=a=>{let u=mi??Md;if(xo&&u&&da&&dk(u,a,da)){mi=a,_r===null&&(_r=requestAnimationFrame(()=>{_r=null;let y=mi;mi=null,y&&Td(y)}));return}if(a.length===0){vv(),Td(a);return}um(),Td(a)};V=new hu(o,{onMessagesChanged(a){uk(a)},onStatusChanged(a){let u=o.statusIndicator??{};Tr(Mt,(M=>M==="idle"?u.idleText??Cn.idle:M==="connecting"?u.connectingText??Cn.connecting:M==="connected"?u.connectedText??Cn.connected:M==="error"?u.errorText??Cn.error:M==="paused"?u.pausedText??Cn.paused:M==="resuming"?u.resumingText??Cn.resuming:Cn[M])(a),u,a),Zn()},onStreamingChanged(a){a||(V?.getMessages().length===0?vv():um()),xo=a,yl(a),Zn(),V&&Io($e,V.getMessages(),Z),a||(hs(!0),$0(),$b=!0,V&&Ub(V.getMessages(),Hs(o))),Xn(),Xs(a?"Responding\u2026":"Response complete."),aa()},onVoiceStatusChanged(a){if(L.emit("voice:status",{status:a,timestamp:Date.now()}),a!=="disconnected"&&!no(o.voiceRecognition?.provider))return;let u=V.getVoiceNotice();switch(u&&Pd(u,1e4),a){case"listening":if(!$f){let y=V.getVoiceDisclosure();y&&($f=!0,Pe()?(pd=we.placeholder,we.placeholder=y,Xs(y)):Pd(y,1e4))}Fr(),ma();break;case"processing":Fr(),Bk();break;case"speaking":Fr(),Dk();break;default:a==="idle"&&V.isBargeInActive()?(Fr(),ma(),De?.setAttribute("aria-label","End voice session")):(vt.active=!1,$f=!1,pd!==null&&(we.placeholder=pd,pd=null),Fr(),Br("system"),Kb||yo());break}},onArtifactsState(a){Lo=a,a.artifacts.length===0&&(Ji=!1),ts()?.updateInlineArtifactBlocks($e,a.artifacts,{suppressTransition:xo}),Yo(),na()},onHistoryStateChanged(a){Kt(a)},onHistoryNotice(a){gn(a)},onReconnect(a){let{executionId:u,lastEventId:y}=a.handle;a.phase==="paused"?L.emit("stream:paused",{executionId:u,after:y}):a.phase==="resuming"?L.emit("stream:resuming",{executionId:u,after:y,attempt:a.attempt??1}):L.emit("stream:resumed",{executionId:u,after:y})}},vs),Po.current=V,Ue.push(()=>V.cancel()),Ue.push(()=>{V.destroy(),Ho?.destroy(),Ho=null});let fm=null;if(V.onReadAloudChange((a,u)=>{yb=a,bb=u,vb();let y=a??fm;a&&(fm=a);let M=y?V.getMessages().find(H=>H.id===y)??null:null;L.emit("message:read-aloud",{messageId:y,message:M,state:u,timestamp:Date.now()}),u==="idle"&&(fm=null)}),g=!0,Nf=!0,o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider))try{V.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let sn=null,mm=null,Cv=!1,wv=V.getHistoryState(),vl=()=>o.features?.history?.enabled===!0,xv=a=>{a&&(qo.textContent="",qo.textContent=a)},gm=()=>{m.forEach(y=>y()),m=[];let a=sn,u=a?.railCollapseShortcut();a&&u&&m.push(f.register({id:"history-rail-collapse",combo:u.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ot&&mt==="rail"&&a.railCollapsible()||a.railTriggerApplies(),run:()=>a.railOverlayMode()?a.toggleRailPinned():a.toggleRailCollapsed()}));for(let y of o.layout?.header?.trailingActions??[])y.shortcut&&m.push(f.register({id:`header-action-${y.id}`,combo:y.shortcut,run:()=>{let M=e.querySelector(`[data-persona-header-action="${y.id}"]`);M?M.click():o.layout?.header?.onAction?.(y.id)}}));for(let y of p)for(let M of y.shortcuts??[])m.push(f.register({...M,id:`${y.id}:${M.id}`}))};gm();let Ed=null,Sv=!1,Cl=()=>{if(!mo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&Ed?.trim()||null;mo.textContent=u??o.launcher?.title??"Chat Assistant";let y=mo.closest(".persona-combo-btn");if(!y)return;let M=!a||V.getActiveConversationId()!==null;y.setAttribute("data-persona-menu-locked",M?"false":"true"),y.setAttribute("aria-haspopup",M?"true":"false"),M||y.setAttribute("aria-expanded","false"),y.style.cursor=M?"pointer":"default";let H=y.querySelector("svg");H&&(H.style.display=M?"":"none")},fk=a=>{a!==Ed&&(Ed=a,Cl())},mk=a=>{Sv=a?.starred===!0,fk(a&&a.title.trim()||null),Cl()};Cl(),Be.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,y=V.getActiveConversationId();y&&(u==="delete"?ur(M=>M.requestDeleteConversation(y)):u==="star"&&V.canUpdateConversations()&&ur(M=>M.updateHistoryConversation(y,{starred:!Sv})).catch(()=>{}))}),Kt=a=>{wv=a,sn?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),yl(a.sendBlocked||xo),sn?.syncEarlierMessagesPill()},gn=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(Yn.clear(),pi(),dr()),xv(a.message),sn?.historySurface?.view.refresh()};let gk={get actionManager(){return ke},get activeConversationTitle(){return Ed},announceHistory:xv,get applyRailChrome(){return St},set applyRailChrome(a){St=a},get artifactSplitRoot(){return Ir},get body(){return ye},get config(){return o},get container(){return Be},get conversationOpenPendingEl(){return av},set conversationOpenPendingEl(a){av=a},get conversationOpenTakeover(){return tm},set conversationOpenTakeover(a){tm=a},currentKeyPrefix:Tt,destroyCallbacks:Ue,eventBus:L,get footer(){return gt},get header(){return Vt},get historyChromeSync(){return Zn},set historyChromeSync(a){Zn=a},historyFeatureEnabled:vl,get historyInternals(){return vs},set historyInternals(a){vs=a},get historyPresentation(){return mt},set historyPresentation(a){mt=a},get historySessionState(){return wv},get historyVisible(){return Ot},set historyVisible(a){Ot=a},get isStreaming(){return xo},jumpToBottomInstant:Gf,get lastAppliedMessages(){return Md},set lastAppliedMessages(a){Md=a},get launcherEnabled(){return ve},get launcherSurfaceInstance(){return hn},maybeFocusInput:wd,messageCache:Yn,get messagesWrapper(){return $e},mount:e,get open(){return U},panel:Ve,panelElements:wt,get persistentMetadata(){return I},set persistentMetadata(a){I=a},plugins:p,get reapplyHistoryHostChrome(){return Ht},set reapplyHistoryHostChrome(a){Ht=a},repinAnchoredMessage:ia,resetAnchorState:pi,restoreScrollPosition:Yf,resumeAutoScroll:dr,runStorageMutation:fd,get session(){return V},setActiveConversationSummary:mk,storageAdapter:x,get suppressScrollSend(){return ea},set suppressScrollSend(a){ea=a},syncScrollToBottomButton:Xn,updateWelcome:bl,getHistoryProviderFactory:GE,historyErrors:{HistoryClientError:kn,HistoryProviderError:Li},isDockedMountMode:un,renderLucideIcon:We,loadHistoryView:OE,createHeaderIconButton:Na,attachTooltip:$n},hm=a=>(!sn&&!Cv&&(sn=a.createHistoryShell(gk),sn.railCollapseShortcut()&&gm()),sn),ym=()=>{if(sn)return Promise.resolve(sn);let a=hf();return a?Promise.resolve(hm(a)):(mm??=KE().then(hm,u=>{throw mm=null,u}),mm)},ur=a=>{let u=hf(),y=sn??(u?hm(u):null);return y?a(y):ym().then(M=>{if(!M)throw new Error("[AgentWidget] The widget was destroyed");return a(M)})},kd=()=>{sn?.syncHistoryPresentation()};Ue.push(()=>{Cv=!0}),vl()&&ym().catch(()=>{}).finally(te),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&V.initClientSession().then(()=>{let a=sn;if(a?.historyAvailable())return V.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{sn?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let bm=()=>V.warmClientSession(),Av=a=>{let u=o.sessionInit??"input",y=Bt?.input??we,M=a.target;y&&(a.type==="input"?(u==="input"||u==="focus")&&M===y&&a.inputType&&y.value.trim():u==="focus"&&(a.type==="keyup"?M===y&&a.key==="Tab":(Bt?.form??Pn)?.contains(M)))&&bm()},Mv=["input","pointerdown","keyup"];Mv.forEach(a=>e.addEventListener(a,Av));let Tv,vm,Ev=()=>{let a=vm;vm=void 0;try{typeof a=="function"&&a()}catch{}},kv=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==Tv){Ev(),Tv=a;try{vm=a?.({warm:bm,mount:e})}catch{}}};kv(),Ue.push(()=>{Mv.forEach(a=>e.removeEventListener(a,Av)),Ev()}),(Ie||o.onSSEEvent)&&V.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),wn(a,u)});let Lv=()=>{let a=o.resume??(P?vs.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(a)};J?J.then(a=>{if(a){if(a.metadata&&(I=Yy(a.metadata),ke.syncFromMetadata()),a.messages?.length){ea=!0;try{V.hydrateMessages(a.messages)}finally{ea=!1}vd()}a.artifacts?.length&&V.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),Qb(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{om=!0,_(),Lv()}):(Qb(X),Lv());let hk=()=>{!Pe()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Yt(!0,"auto")},yk=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[y,M]=await Promise.allSettled([a.finalize(),u.finalize()]),H=[];return y.status==="fulfilled"?H.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),M.status==="fulfilled"?H.push(M.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",M.reason),R_(H)}}:a:u,Cm=()=>{let u=we.getInlineMessageFields?.();return u&&u.contentSegments.some(M=>M.kind==="mention")?u.contentSegments:void 0},Or=!1,gi=null,Ld=()=>{we.value="",we.style.height="auto",ko(),xl()},pa=null;function Pd(a,u=4e3){Xs(a),!(Pe()||!Mt)&&(Mt.hasAttribute(Ja)||(Mt.setAttribute(qc,""),Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.textContent=a,xi(Mt,o.statusIndicator??{},"idle"),pa&&clearTimeout(pa),pa=setTimeout(()=>{if(pa=null,!!Mt?.hasAttribute(qc)&&(Mt.removeAttribute(qc),Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),g)){let y=V.getStatus();Tr(Mt,oo(y),o.statusIndicator??{},y)}},u)))}function bk(){let a=Oe.getState().pendingSubmission;a&&(Yi(void 0),we&&(we.value=a.text,we.dispatchEvent(new Event("input",{bubbles:!0})),ko()),a.options.selectedModelId&&(Oe.setSelectedModelId(a.options.selectedModelId),ls?.repaint()),a.options.activeModeIds?.length&&Xc(a.options.activeModeIds),a.options.quote&&ar(a.options.quote),we?.focus())}let vk=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},Pv=(a={})=>{let u=(a.overrideText??we?.value??"").trim();return a.resolveInlineCommand&&u?(Rt?.takeInlineCommand(u)??Promise.resolve(null)).then(y=>Iv(a,u,y)):Iv(a,u,null)},Iv=(a,u,y)=>{if(y?.kind==="action"){Ld(),Rt?.clear(),kr();return}let M=y?.kind==="server"?y.mentions:null,H=y?.kind==="prompt"?y.sendText:u,O=a.pending?.contentParts,se=(ut?.hasAttachments()??!1)||(O?.length??0)>0;if(!EA({text:H,hasAttachments:se,attachmentsReady:ut?.isReady()??!0,hasMentions:Rt?.hasMentions()??!1,hasServerMentions:!!M,inputDisabled:pr(),sendDisabled:ui()}))return;let ge=V.isStreaming()?Sf():"block";if(ge==="defer-one"&&!a.pending){if(Oe.getState().pendingSubmission){Pd("One message is already queued. Edit or remove it first.");return}Ck({intent:a,sendText:H,serverMentions:M});return}let ce={text:H,mentionRefs:[...Rt?.getMentionRefs()??[],...M?.refs??[]],contentSegments:y?.kind==="prompt"?void 0:Cm(),options:{...Oe.getState().selectedModelId&&{selectedModelId:Oe.getState().selectedModelId},...Oe.getState().activeModeIds.length>0&&{activeModeIds:[...Oe.getState().activeModeIds]},...Oe.getState().quote&&{quote:{...Oe.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(ce.options={...a.pending.options},ce.contentSegments=a.pending.contentSegments,ce.mentionRefs=[...a.pending.mentionRefs],ce.viaVoice=a.pending.viaVoice);let be=()=>{if(O?.length)return[...O];if(!ut?.hasAttachments())return;let Dt=[...ut.getContentParts()];return ce.text&&Dt.push(vr(ce.text)),Dt};ce.contentParts=be();let Ce=()=>{si(),hk();let Dt=Rt?.collectForSubmit()??null,bo=yk(Dt,M),an=be();a.consumeDraft!==!1&&Ld();let mn={selectedModelId:ce.options.selectedModelId,activeModeIds:ce.options.activeModeIds},io=ge==="interrupt";io&&V.cancel(),V.sendMessage(ce.text,{contentParts:an,mentions:bo??void 0,contentSegments:ce.contentSegments,viaVoice:ce.viaVoice,composerOptions:mn,...ce.options.quote&&{quote:ce.options.quote},...io&&{interrupt:!0}}),ut?.hasAttachments()&&ut.clearAttachments(),Dt&&Rt?.clear(),kr();let bn=Oe.getState().activeModeIds,zt=mA(bn,o.composer?.modes);zt.length!==bn.length&&Xc(zt),Oe.getState().quote&&ar(void 0),gd(),Lf.release(),Ko()},Ae=o.composer?.onBeforeSend;if(!Ae){Ce();return}let Ke=new AbortController;gi=Ke;let Pt=Dt=>{if(gi=null,Dt.status==="error"){vk(Dt.error);return}Dt.status==="proceed"&&Ce()},Ft=kA(Ae,ce,Ke.signal);if(!(Ft instanceof Promise)){Pt(Ft);return}return Oe.setPreparing(!0),Ft.then(Pt).finally(()=>Oe.setPreparing(!1))};function Ck(a){let u=Oe.getState(),y=ut?.hasAttachments()??!1,M=y?[...ut.getContentParts()]:[];y&&a.sendText&&M.push(vr(a.sendText));let H=fh({text:a.sendText,contentParts:M.length?M:void 0,mentionRefs:[...Rt?.getMentionRefs()??[],...a.serverMentions?.refs??[]],contentSegments:Cm(),options:{...u.selectedModelId&&{selectedModelId:u.selectedModelId},...u.activeModeIds.length>0&&{activeModeIds:[...u.activeModeIds]},...u.quote&&{quote:{...u.quote}}},viaVoice:a.intent.viaVoice});Yi(H),a.intent.consumeDraft!==!1&&Ld(),y&&ut.clearAttachments(),Rt?.clear(),kr(),u.quote&&ar(void 0),gd(),Lf.release(),Ko(),Xs("Message queued. It sends when the response finishes.")}function wk(){let a=Oe.getState().pendingSubmission;a&&(Yi(void 0),Hd(a.text,{consumeDraft:!1,pending:a}))}function xk(a){if(o.messageActions?.showEdit!==!0)return;let u=V.getMessages().find(y=>y.id===a);!u||!Yg(u)||ri!==a&&(si(),ri=a,us=vA({messageId:a,initialText:u.content,onSave:y=>Sk(a,y),onCancel:()=>si()}),Yn.delete(a),Io($e,V.getMessages(),Z),us.focus())}function Sk(a,u){let y=us;if(ri=null,us=null,y?.destroy(),Yn.delete(a),!V.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){Io($e,V.getMessages(),Z);return}ia()}function Ak(a){if(V.isStreaming())return;let u=Gg(V.getMessages(),a);u&&(si(),V.resubmitFrom(u,{reason:"retry"})&&ia())}Qc={regenerate:Ak,edit:xk,quote:a=>{let y=V.getMessages().find(M=>M.id===a)?.content?.trim();y&&(ar({text:y,messageId:a}),we?.focus())}};let wl=async a=>{if(!Or){Or=!0;try{await Pv({resolveInlineCommand:!0,...a})}finally{Or=!1}}};function Id(a){ui()||(Ld(),Hd(a,{consumeDraft:!1}))}let Hd=(a,u)=>{if(Or)return;Or=!0;let y=()=>{Or=!1};try{let M=Pv({...u,overrideText:a});M instanceof Promise?M.finally(y):y()}catch(M){throw y(),M}},Mk=a=>{if(a.preventDefault(),V.isStreaming()){V.cancel(),Re?.reset(),bt?.update();return}Or||wl()},Tk=()=>o.features?.composerHistory!==!1,wm={...wh},xm=!1,xl=()=>{wm={...wh}},Ek=()=>V.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),kk=a=>{if(!we)return;xm=!0,we.value=a,we.dispatchEvent(new Event("input",{bubbles:!0})),xm=!1;let u=we.value.length;we.setSelectionRange(u,u)},Lk=a=>{xm||(a.isComposing||Rt?.handleInput(a.inputType??void 0),xl())},Pk=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(we)}),Ik=a=>{if(we&&!pr()&&!(!a.isComposing&&Rt?.handleKeydown(a))){if(Tk()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=we.selectionStart===0&&we.selectionEnd===0,y=VA({direction:a.key==="ArrowUp"?"up":"down",history:Ek(),currentValue:we.value,atStart:u,state:wm});if(wm=y.state,y.handled){a.preventDefault(),y.value!==void 0&&kk(y.value);return}}if(xx(a,Pk())){if(V.isStreaming()){if(a.preventDefault(),Sf()==="block"||Or||ui())return;xl(),wl();return}if(Or){a.preventDefault();return}if(ui()){a.preventDefault();return}xl(),a.preventDefault(),ze.click()}}},Hv=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(Be)){if(gi){gi.abort(),gi=null,a.preventDefault(),a.stopImmediatePropagation();return}V.isStreaming()&&(V.cancel(),Re?.reset(),bt?.update(),xl(),a.preventDefault(),a.stopImmediatePropagation())}},Hk=async a=>{if(o.attachments?.enabled!==!0||!ut||pr())return;let u=L_(a.clipboardData);u.length!==0&&(a.preventDefault(),await ut.handleFiles(u))},Ro=null,fr=!1,ua=null,Nr=null,Sm=()=>o.voiceRecognition?.completionBehavior==="review";function Rd(a){De?.setAttribute("data-state",a),a==="recording"?Wk():Em()}let Rv="--persona-voice-level",Am=.5,fa=null,Mm=-1,Wd=0,Wv=()=>{let a=[],u=Dn??De?.parentElement??null;return u&&a.push(u),gt&&a.push(gt),a},Tm=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==Mm){Mm=u;for(let y of Wv())y.style.setProperty(Rv,String(u))}},Rk=()=>{Mm=-1,Wd=0;for(let a of Wv())a.style.removeProperty(Rv)};function Wk(){if(fa!==null)return;if(typeof requestAnimationFrame!="function"){Tm(g?V.getVoiceLevel()??Am:Am);return}let a=()=>{fa=requestAnimationFrame(a);let u=g?V.getVoiceLevel():null;if(u===null){Tm(Am);return}Wd+=(u-Wd)*.3,Tm(Wd)};fa=requestAnimationFrame(a)}function Em(){fa!==null&&(cancelAnimationFrame(fa),fa=null),Rk()}let Bv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Bd=(a="user")=>{if(fr||V.isStreaming())return;let u=Bv();if(!u)return;Ro=new u;let y=o.voiceRecognition??{},M=y.pauseDuration??2e3;Ro.continuous=y.provider?.browser?.continuous??!0,Ro.interimResults=!0,Ro.lang=y.provider?.browser?.language??"en-US";let H=we.value;Ro.onresult=O=>{let se="",ge="";for(let be=0;be<O.results.length;be++){let Ce=O.results[be],Ae=Ce[0].transcript;Ce.isFinal?se+=Ae+" ":ge=Ae}let ce=H+se+ge;we.value=ce,ko(),ua&&clearTimeout(ua),(se||ge)&&(ua=window.setTimeout(()=>{if(we.value.trim()&&Ro&&fr){if(Cs(),Sm())return;wl({viaVoice:!0})}},M))},Ro.onerror=O=>{O.error!=="no-speech"&&Cs()},Ro.onend=()=>{if(fr){let O=we.value.trim();!Sm()&&O&&O!==H.trim()&&wl({viaVoice:!0}),Cs()}};try{if(Ro.start(),fr=!0,vt.active=!0,a!=="system"&&(vt.manuallyDeactivated=!1),Br(a),yo(),Ko(),De){let O=o.voiceRecognition??{};Nr={backgroundColor:De.style.backgroundColor,color:De.style.color,borderColor:De.style.borderColor,iconName:O.iconName??"mic",iconSize:parseFloat(O.iconSize??"")||Co};let se=O.recordingBackgroundColor,ge=O.recordingIconColor,ce=O.recordingBorderColor;if(De.classList.add("persona-voice-recording"),Rd("recording"),De.style.backgroundColor=se??"var(--persona-voice-recording-bg, #ef4444)",De.style.color=ge??"var(--persona-voice-recording-indicator, #ffffff)",ge){let be=De.querySelector("svg");be&&be.setAttribute("stroke",ge)}ce&&(De.style.borderColor=ce),De.setAttribute("aria-label","Stop voice recognition")}}catch{Cs("system")}},Cs=(a="user")=>{if(fr){if(fr=!1,ua&&(clearTimeout(ua),ua=null),Ro){try{Ro.stop()}catch{}Ro=null}if(vt.active=!1,Br(a),yo(),Ko(),De){if(De.classList.remove("persona-voice-recording"),Rd("idle"),Nr){De.style.backgroundColor=Nr.backgroundColor,De.style.color=Nr.color,De.style.borderColor=Nr.borderColor;let u=De.querySelector("svg");u&&u.setAttribute("stroke",Nr.color||"currentColor"),Nr=null}De.setAttribute("aria-label","Start voice recognition")}}},Dv=null,Dd=a=>{let u=M=>{Dv??=M.createMicStateStyles({mic:()=>De,config:()=>o,session:()=>V,get original(){return Nr},set original(H){Nr=H},setMicState:Rd,renderIcon:We,iconFallbackPx:Co}),a(Dv)},y=OS();y?u(y):oc().then(u,()=>{})},ma=()=>Dd(a=>a.recording()),Bk=()=>Dd(a=>a.processing()),Dk=()=>Dd(a=>a.speaking()),Fr=()=>Dd(a=>a.reset()),km=()=>{if(!pr()){if(no(o.voiceRecognition?.provider)){let a=V.getVoiceStatus(),u=V.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,yo(),Br("user"),Fr()});return}V.toggleVoice().then(()=>{vt.active=Uf(),vt.manuallyDeactivated=!vt.active,yo(),Br("user"),vt.active?ma():Fr()});return}if(fr){let a=we.value.trim();vt.manuallyDeactivated=!0,yo(),Cs("user"),a&&!Sm()&&wl()}else vt.manuallyDeactivated=!1,yo(),Bd("user")}};Af=km;let _v=()=>V.prewarmVoice(),Ov=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Nv=a=>{Ov()==="hover"&&De?.contains(a.target)&&_v()},Fv=["pointerover","pointerdown","focusin"];Fv.forEach(a=>e.addEventListener(a,Nv));let Vv,$v=null,Lm,Uv=()=>{let a=Lm;Lm=void 0;try{typeof a=="function"&&a()}catch{}},Pm=()=>{let a=Ov(),u=typeof a=="function"&&De?a:void 0,y=u?De:null;if(!(u===Vv&&y===$v)&&(Uv(),Vv=u,$v=y,!(!u||!y)))try{Lm=u({warm:_v,micButton:y,mount:e})}catch{}};Pm(),Ue.push(()=>{Fv.forEach(a=>e.removeEventListener(a,Nv)),Uv()}),De&&Ue.push(()=>{no(o.voiceRecognition?.provider)?(V.isVoiceActive()&&V.toggleVoice(),Fr()):Cs("system")});let _k=L.on("assistant:complete",()=>{Oe.getState().pendingSubmission&&setTimeout(()=>{V.isStreaming()||wk()},0)});Ue.push(_k);let Ok=L.on("assistant:complete",()=>{jb&&(vt.active||vt.manuallyDeactivated||jb==="assistant"&&!vt.lastUserMessageWasVoice||setTimeout(()=>{!vt.active&&!vt.manuallyDeactivated&&(no(o.voiceRecognition?.provider)?V.toggleVoice().then(()=>{vt.active=V.isVoiceActive(),Br("auto"),V.isVoiceActive()&&ma()}):Bd("auto"))},600))});Ue.push(Ok);let Nk=L.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});Ue.push(Nk);let zv=()=>{Yt(!U,"user")},hn=null,so=null;if(ve&&!Pe()){let{instance:a,element:u}=Gh({config:o,plugins:p,onToggle:zv});hn=a,a||(so=u)}hn?e.appendChild(hn.element):so&&e.appendChild(so),hl(),ni(),Sd(),lm(),yl(V.isStreaming()),Yf()||(Gn()==="follow"?hs(!0):Gf()),D0(),xt&&(!ve||Pe()?setTimeout(()=>wd(),0):U&&setTimeout(()=>wd(),200));let ws=null,qv=()=>{ws&&(ws.disconnect(),ws.observe(gt),ws.observe(Be),ws.observe($))},jv=go(),Sl=()=>{if(Pe()){Xe(),hl();return}let a=un(o),u=o.launcher?.sidebarMode??!1,y=e.ownerDocument.defaultView??window,M=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640,O=y.innerWidth<=H,se=M&&O&&ve;try{if(se){Qs(),il=id();return}let ge=!1;dt&&(dt=!1,Qs(),ge=!0);let ce=id();if(!ge&&ce!==il&&(Qs(),ge=!0),il=ce,ge&&nd(),!ve&&!a){Ve.style.height="",Ve.style.width="";return}if(!u&&!a){let be=Wi(o);Ve.style.width=be.width,Ve.style.maxWidth=be.maxWidth}sd(),Pb()}finally{Xe(),on();let ge=go();if(ge!==jv&&(jv=ge,bl(),ni()),hl(),U&&ve){let be=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Ce=o.launcher?.sidebarMode??!1,Ae=o.launcher?.mobileFullscreen??!0,Ke=un(o)&&Ae&&be,Pt=Ce||Ae&&be&&ve||Ke;if(Pt&&!cr){let Ft=e.getRootNode(),Dt=Ft instanceof ShadowRoot?Ft.host:e.closest(".persona-host");Dt&&!lr&&(lr=Lh(Dt,o.launcher?.zIndex??Jn)),cr=Ph(e.ownerDocument)}else Pt||(lr?.(),lr=null,cr?.(),cr=null)}}};Sl();let _d=e.ownerDocument.defaultView??window;if(_d.addEventListener("resize",Sl),Ue.push(()=>_d.removeEventListener("resize",Sl)),typeof ResizeObserver<"u"){ws=new ResizeObserver(()=>{on()}),qv(),Ue.push(()=>{ws?.disconnect(),ws=null});let a=new ResizeObserver(()=>{kd()});a.observe(Be),Ue.push(()=>a.disconnect())}_d.addEventListener("resize",kd),Ue.push(()=>_d.removeEventListener("resize",kd)),Ao=ye.scrollTop;let Kv=xr(ye),Gv=()=>{Lb();let a=ye.scrollTop,u=xr(ye),y=u<Kv;if(Kv=u,!zo()){Ao=a,Xn();return}let{action:M,nextLastScrollTop:H}=Ru({following:So.isFollowing(),currentScrollTop:a,lastScrollTop:Ao,nearBottom:Zr(ye,Rr),userScrollThreshold:H0,isAutoScrolling:ho||ld||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Ao=H,M==="resume"){hd()||dr();return}M==="pause"&&sa()};if(ye.addEventListener("scroll",Gv,{passive:!0}),Ue.push(()=>ye.removeEventListener("scroll",Gv)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{U0(),tg($e)});a.observe($e),a.observe(ye),Ue.push(()=>a.disconnect())}let Yv=()=>{zo()&&So.isFollowing()&&hd()&&sa()},Xv=ye.ownerDocument;Xv.addEventListener("selectionchange",Yv),Ue.push(()=>{Xv.removeEventListener("selectionchange",Yv)});let Fk=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Qv=a=>{Fk.has(a.key)&&(gs(),el()&&zo()&&So.isFollowing()&&sa())},Jv=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(gs(),el()&&zo()&&So.isFollowing()&&sa())};ye.addEventListener("keydown",Qv),ye.addEventListener("focusin",Jv),Ue.push(()=>{ye.removeEventListener("keydown",Qv),ye.removeEventListener("focusin",Jv)});let Zv=a=>{if(a.deltaY!==0&&gs(),!zo())return;let u=Wu({following:So.isFollowing(),deltaY:a.deltaY,nearBottom:Zr(ye,Rr),resumeWhenNearBottom:!0});u==="pause"?sa():u==="resume"&&!hd()&&dr()};ye.addEventListener("wheel",Zv,{passive:!0}),ye.addEventListener("touchmove",gs,{passive:!0}),ye.addEventListener("pointerdown",gs,{passive:!0}),Ue.push(()=>{ye.removeEventListener("touchmove",gs),ye.removeEventListener("pointerdown",gs)}),Ue.push(()=>ye.removeEventListener("wheel",Zv)),fn.addEventListener("click",()=>{pi(),ye.scrollTop=ye.scrollHeight,Ao=ye.scrollTop,dr(),hs(!0),Xn()}),Ue.push(()=>fn.remove()),Ue.push(()=>{Zb(),pi()});let eC=()=>{Ze&&(ei&&(Ze.removeEventListener("click",ei),ei=null),Se()?(Ze.style.display="",ei=()=>{Yt(!1,"user")},Ze.addEventListener("click",ei)):Ze.style.display="none")};eC(),(()=>{let{clearChatButton:a}=wt;a&&a.addEventListener("click",()=>{let u=sn;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(M=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",M)});return}V.clearMessages(),o.layout?.topFade&&(ye.scrollTop=0),ye.removeAttribute("data-persona-top-fade"),Yn.clear(),dr(),Ei(wt.composerOverlay);try{localStorage.removeItem(Qa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qa}`)}catch(M){console.error("[AgentWidget] Failed to clear default localStorage:",M)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(M){console.error("[AgentWidget] Failed to clear custom localStorage:",M)}let y=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(y),x?.clear&&fd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},ke.syncFromMetadata(),ut?.clearAttachments(),gd(),Yi(void 0),ar(void 0),si(),ee?.clear(),Re?.reset(),bt?.update()})})();let tC=[["keydown",Ik],["input",Lk],["input",ko],["input",kr],["keyup",kr],["paste",Hk],["focus",C0]],nC=a=>{if(a)for(let[u,y]of tC)Bt?.addListener(a,u,y)},Vk=a=>{if(a)for(let[u,y]of tC)Bt?.removeListener(a,u,y)},oC=()=>{Bt&&(Bt.addListener(Bt.form,"submit",Mk),Bt.addListener(Bt.footer,"click",kr),nC(we),De&&Bt.addListener(De,"click",km),Pm())};oC();let rC=()=>{Rt?.onComposerSwap((a,u)=>{Vk(u),we=a,Bt&&(Bt.input=a),nC(a),Tf(),em(),ko()})};rC();let Im=!1;function sC(){if(!Im){Im=!0;try{let a=we?.value??"",u=gt.ownerDocument??document,y=we?u.activeElement===we:!1;Em(),Bt?.destroy(),Bt=null,Rt?.destroy(),Rt=null;let M=null,H=()=>(M=Pe()?$u({config:o}):Ac({config:o}),M.footer),O=lb(H)??H();At.replaceComposer(O),gt=At.composer.footer;let se=M!==null&&O===M.footer;Qi=!se,Kc=se?M.setSendButtonMode:()=>{},ab(gt),db(gt),pb(),ub(),Ef(),rC(),fb(),kf(),mb(),oC();let ge=Zs.indexOf(Hr);if(Hr.destroy(),Hr=wc(eo),ge>=0&&(Zs[ge]=Hr),we&&(we.value=a),ko(),kr(),Sd(),ni(),yl(V.isStreaming()),o.statusIndicator?.mode==="transient"&&!Pe()){let ce=V.getStatus();Tr(Mt,oo(ce),o.statusIndicator,ce)}vt.active&&Rd("recording"),Qs(),qv(),Xe(),Ko(),Cd(),y&&we?.focus()}finally{Im=!1}}}let Al=e.ownerDocument??document;Al.addEventListener("keydown",Hv,!0);let iC=()=>{zf()},aC=()=>{Al.visibilityState==="hidden"&&zf()};typeof window<"u"&&(window.addEventListener("pagehide",iC),Al.addEventListener("visibilitychange",aC),Ue.push(()=>{window.removeEventListener("pagehide",iC),Al.removeEventListener("visibilitychange",aC)}));let lC="persona-attachment-drop-active",Ml=0,Hm=()=>{Ml=0,Be.classList.remove(lC)},ga=()=>o.attachments?.enabled===!0&&ut!==null&&!pr(),cC=a=>{!yf(a.dataTransfer)||!ga()||(Ml++,Ml===1&&Be.classList.add(lC))},dC=a=>{!yf(a.dataTransfer)||!ga()||(Ml--,Ml<=0&&Hm())},pC=a=>{!yf(a.dataTransfer)||!ga()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},uC=a=>{if(!yf(a.dataTransfer)||!ga())return;a.preventDefault(),a.stopPropagation(),Hm();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&ut.handleFiles(u)},xs=!0;Be.addEventListener("dragenter",cC,xs),Be.addEventListener("dragleave",dC,xs),e.addEventListener("dragover",pC,xs),e.addEventListener("drop",uC,xs);let Od=e.ownerDocument,fC=a=>{ga()&&a.preventDefault()},mC=a=>{ga()&&a.preventDefault()};Od.addEventListener("dragover",fC),Od.addEventListener("drop",mC),Ue.push(()=>{Bt?.destroy(),Bt=null,Em(),jo?.destroy(),jo=null,Lr?.destroy(),Lr=null,cs?.destroy(),cs=null,ds?.destroy(),ds=null,ls=null,xf=null,zf(),pl.destroy(),pa&&clearTimeout(pa),si(),gi?.abort(),gi=null,ut?.destroy(),ut=null,Oe.destroy(),Al.removeEventListener("keydown",Hv,!0),Rt?.destroy()}),Ue.push(()=>{Be.removeEventListener("dragenter",cC,xs),Be.removeEventListener("dragleave",dC,xs),e.removeEventListener("dragover",pC,xs),e.removeEventListener("drop",uC,xs),Od.removeEventListener("dragover",fC),Od.removeEventListener("drop",mC),Hm()}),Ue.push(()=>{V.cancel()}),hn?Ue.push(()=>{hn?.destroy()}):so&&Ue.push(()=>{so?.remove()});let yn={update(a){let u=o.future?.v5Defaults===!0,y=o.toolCall,M=o.messageActions,H=o.layout?.messages,O=o.colorScheme,se=o.loadingIndicator,ge=o.iterationDisplay,ce=o.features?.showReasoning,be=o.features?.showToolCalls,Ce=o.features?.toolCallDisplay,Ae=o.features?.reasoningDisplay,Ke=o.features?.streamAnimation?.type,Pt=o.features?.history?.enabled===!0,Ft=o.features?.history?.provider,Dt=o.getIdentityProof,bo=o.clientToken,an=o.contextMentions;o=fE({...o,features:d},a),d=o.features,o=ky(o),c(),Bf(),lc(e,o),_c(e,o),Oc(e,o),St(),Yo(),o.colorScheme!==O&&Ib();let mn=Iy.getForInstance(o.plugins);p.length=0,p.push(...mn),gm(),ve=o.launcher?.enabled??!0,tt=o.launcher?.autoExpand??!1,le=o.features?.showReasoning??!0,Me=o.features?.showToolCalls??!0,_e=o.features?.scrollToBottom??{};let io=Gn();ct=o.features?.scrollBehavior??{},io!==Gn()&&(pi(),dr()),qb(),rn(),Xn();let bn=Ie;if(Ie=o.features?.showEventStreamToggle??!1,Ie&&!bn){if(ee||(nn(),V.setSSEEventCallback((pe,kt)=>{o.onSSEEvent?.(pe,kt),wn(pe,kt)})),!$t&&Vt){let pe=o.features?.eventStream?.classNames,kt="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"+(pe?.toggleButton?" "+pe.toggleButton:"");$t=v("button",kt),$t.style.width="28px",$t.style.height="28px",$t.style.color=lo.actionIconColor,$t.type="button",$t.setAttribute("aria-label","Event Stream"),$t.title="Event Stream";let Lt=Je(rs.Activity,"18px","currentColor",1.5);Lt&&$t.appendChild(Lt);let _t=wt.clearChatButtonWrapper,en=wt.closeButtonWrapper,Qn=_t||en;Qn&&Qn.parentNode===Vt?Vt.insertBefore($t,Qn):Vt.appendChild($t),$t.addEventListener("click",()=>{Ee?Xi():Mf()})}}else!Ie&&bn&&(Xi(),$t&&($t.remove(),$t=null),ee?.clear(),Ut?.destroy(),ee=null,Ut=null,Re?.reset(),Re=null,Fe=null);if(o.launcher?.enabled===!1&&hn&&(hn.destroy(),hn=null),o.launcher?.enabled===!1&&so&&(so.remove(),so=null),o.launcher?.enabled!==!1&&!hn&&!so){let{instance:pe,element:kt}=Gh({config:o,plugins:p,onToggle:zv});hn=pe,pe||(so=kt),e.appendChild(kt)}hn&&hn.update(o),Cl(),ir&&o.launcher?.subtitle!==void 0&&(ir.textContent=o.launcher.subtitle);let zt=o.layout?.header;if(zt?.layout!==Ye&&Vt){let pe=zt?Fu(o,zt,{showClose:Se(),onClose:()=>Yt(!1,"user")}):Ii({config:o,showClose:Se(),onClose:()=>Yt(!1,"user")});At.replaceHeader(pe),Vt=At.header.element,Nt=At.header.iconHolder,mo=At.header.headerTitle,ir=At.header.headerSubtitle,Ze=At.header.closeButton,Ye=zt?.layout,Cl()}else if(zt){if(Nt&&(Nt.style.display=zt.showIcon===!1?"none":""),mo&&(mo.style.display=zt.showTitle===!1?"none":""),ir&&(ir.style.display=zt.showSubtitle===!1?"none":""),Ze){let pe=Se()&&zt.showCloseButton!==!1;Ze.style.display=pe?"":"none"}if(wt.clearChatButtonWrapper){let pe=zt.showClearChat;if(pe!==void 0){wt.clearChatButtonWrapper.style.display=pe?"":"none";let{closeButtonWrapper:kt}=wt;kt&&!kt.classList.contains("persona-absolute")&&(pe?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}}let gr=o.layout?.showHeader!==!1;Vt&&(Vt.style.display=gr?"":"none");let Bo=o.layout?.showFooter!==!1;gt&&(gt.style.display=Bo?"":"none"),Xe(),Xn(),ve!==lt?ve?Yt(tt,"auto"):(U=!0,hl()):tt!==ht&&Yt(tt,"auto"),ht=tt,lt=ve,Sl(),eC();let hr=JSON.stringify(o.toolCall)!==JSON.stringify(y),Xo=JSON.stringify(o.messageActions)!==JSON.stringify(M),As=JSON.stringify(o.layout?.messages)!==JSON.stringify(H),Tl=o.loadingIndicator?.render!==se?.render||o.loadingIndicator?.renderIdle!==se?.renderIdle||o.loadingIndicator?.showBubble!==se?.showBubble,hi=o.iterationDisplay!==ge,q=(o.features?.showReasoning??!0)!==(ce??!0)||(o.features?.showToolCalls??!0)!==(be??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(Ae);(o.future?.v5Defaults===!0!==u||hr||Xo||As||Tl||hi||q)&&V&&(ii++,Io($e,V.getMessages(),Z));let st=o.features?.streamAnimation?.type;if(st!==Ke&&st&&st!=="none"){let pe=Of(st,o.features?.streamAnimation?.plugins);pe&&gc(pe,e)}let he=o.launcher??{},qt=he.headerIconHidden??!1,Sn=o.layout?.header?.showIcon,to=qt||Sn===!1,On=he.headerIconName,Xt=he.headerIconSize??Ll;if(Nt){let pe=Vt,kt=pe?.querySelector(".persona-flex-col");if(to)Nt.style.display="none",pe&&kt&&!pe.contains(kt)&&pe.insertBefore(kt,pe.firstChild);else{if(Nt.style.display="",Nt.style.height=Xt,Nt.style.width=Xt,pe&&kt&&(pe.contains(Nt)?Nt.nextSibling!==kt&&(Nt.remove(),pe.insertBefore(Nt,kt)):pe.insertBefore(Nt,kt)),On){let _t=parseFloat(Xt)||24,en=We(On,_t*.6,"currentColor",1);en?(en.style.width=`calc(${_t}px * var(--persona-components-header-iconScale, 0.6))`,en.style.height=`calc(${_t}px * var(--persona-components-header-iconScale, 0.6))`,Nt.replaceChildren(en)):Nt.textContent=he.agentIconText??"\u{1F4AC}"}else if(he.iconUrl){let _t=Nt.querySelector("img");if(_t)_t.src=he.iconUrl,_t.style.height=Xt,_t.style.width=Xt;else{let en=document.createElement("img");en.src=he.iconUrl,en.alt="",en.className="persona-rounded-xl persona-object-cover",en.style.height=Xt,en.style.width=Xt,Nt.replaceChildren(en)}}else{let _t=Nt.querySelector("svg"),en=Nt.querySelector("img");(_t||en)&&Nt.replaceChildren(),Nt.textContent=he.agentIconText??"\u{1F4AC}"}let Lt=Nt.querySelector("img");Lt&&(Lt.style.height=Xt,Lt.style.width=Xt)}}let vn=o.layout?.header?.showTitle,Rn=o.layout?.header?.showSubtitle;if(mo&&(mo.style.display=vn===!1?"none":""),ir&&(ir.style.display=Rn===!1?"none":""),Ze){let pe=Se()&&o.layout?.header?.showCloseButton!==!1;if(Ze.style.display=pe?"":"none",!Pe()){let Fn=he.closeButtonSize??"";Ze.style.height=Fn,Ze.style.width=Fn,Ze.style.minWidth=Fn,Ze.style.minHeight=Fn}let kt=he.closeButtonPlacement??"inline",{closeButtonWrapper:Lt}=wt,_t=kt==="top-right",en=Lt?.classList.contains("persona-absolute");if(Lt&&_t!==en)if(Lt.remove(),_t){Lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Fn=sn?.railColumn??Be;Fn.style.position="relative",Fn.appendChild(Lt)}else{let Fn=he.clearChat?.placement??"inline",Vn=he.clearChat?.enabled??!0;Lt.className=Vn&&Fn==="inline"?"":"persona-ml-auto",Vt&&Vt.appendChild(Lt)}if(Ze.style.color=he.closeButtonColor||lo.actionIconColor,he.closeButtonBackgroundColor?(Ze.style.backgroundColor=he.closeButtonBackgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let Fn=he.closeButtonBorderWidth||"0px",Vn=he.closeButtonBorderColor||"transparent";Ze.style.border=`${Fn} solid ${Vn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");he.closeButtonBorderRadius?(Ze.style.borderRadius=he.closeButtonBorderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(Ze.style.paddingLeft=he.closeButtonPaddingX,Ze.style.paddingRight=he.closeButtonPaddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),he.closeButtonPaddingY?(Ze.style.paddingTop=he.closeButtonPaddingY,Ze.style.paddingBottom=he.closeButtonPaddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom=""),Ou(Ze,he.closeButtonIconName??"x",{iconSize:Pe()?zh:void 0,iconText:he.closeButtonIconText??"\xD7"});let Qn=he.closeButtonTooltipText??"Close chat",Jo=he.closeButtonShowTooltip??!0;Ze.setAttribute("aria-label",Qn),Lt&&$n({anchor:Ze,trigger:Lt,text:()=>Ze?.getAttribute("aria-label")??Qn,enabled:Jo})}let{clearChatButton:Qe,clearChatButtonWrapper:Qt}=wt;if(Qe){let pe=he.clearChat??{},kt=pe.enabled??!0,Lt=o.layout?.header?.showClearChat,_t=Lt!==void 0?Lt:kt,en=pe.placement??"inline";if(Qt){Qt.style.display=_t?"":"none";let{closeButtonWrapper:Qn}=wt;!Pe()&&Qn&&!Qn.classList.contains("persona-absolute")&&(_t?Qn.classList.remove("persona-ml-auto"):Qn.classList.add("persona-ml-auto"));let Jo=en==="top-right",Fn=Qt.classList.contains("persona-absolute");if(!Pe()&&Jo!==Fn&&_t){if(Qt.remove(),Jo){Qt.className="persona-absolute persona-top-4 persona-z-50",Qt.style.right="48px";let yr=sn?.railColumn??Be;yr.style.position="relative",yr.appendChild(Qt)}else{Qt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qt.style.right="";let yr=wt.closeButtonWrapper;Vt&&yr&&yr.parentElement===Vt?Vt.insertBefore(Qt,yr):Vt&&Vt.appendChild(Qt)}let Vn=wt.closeButtonWrapper;Vn&&!Vn.classList.contains("persona-absolute")&&(Jo?Vn.classList.add("persona-ml-auto"):Vn.classList.remove("persona-ml-auto"))}}if(_t){if(!Pe()){let Vn=pe.size??"";Qe.style.height=Vn,Qe.style.width=Vn,Qe.style.minWidth=Vn,Qe.style.minHeight=Vn}let Qn=pe.iconColor??"";if(Qe.style.color=Qn||lo.actionIconColor,Ou(Qe,pe.iconName??"refresh-cw",{iconSize:Pe()?qh:void 0}),pe.backgroundColor?(Qe.style.backgroundColor=pe.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),pe.borderWidth||pe.borderColor){let Vn=pe.borderWidth||"0px",yr=pe.borderColor||"transparent";Qe.style.border=`${Vn} solid ${yr}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");pe.borderRadius?(Qe.style.borderRadius=pe.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),pe.paddingX?(Qe.style.paddingLeft=pe.paddingX,Qe.style.paddingRight=pe.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),pe.paddingY?(Qe.style.paddingTop=pe.paddingY,Qe.style.paddingBottom=pe.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Jo=pe.tooltipText??"Clear chat",Fn=pe.showTooltip??!0;Qe.setAttribute("aria-label",Jo),Qt&&$n({anchor:Qe,trigger:Qt,text:()=>Qe?.getAttribute("aria-label")??Jo,enabled:Fn})}}let it=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ry],Wn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Nc.message,Nc.messageAndClick];ke=Wy({parsers:it,handlers:Wn,getSessionMetadata:xe,updateSessionMetadata:Te,emit:L.emit,documentRef:typeof document<"u"?document:null}),Z=t0(o,ke,ne),lk(),V.updateConfig(o),kv(),(o.features?.history?.enabled===!0!==Pt||o.features?.history?.provider!==Ft||o.getIdentityProof!==Dt||o.clientToken!==bo)&&(sn?.closeHistory({restoreFocus:!1}),sn?.installHistoryProvider()),sn?.syncHistoryChromeImpl(),kd(),vl()&&!sn&&ym().catch(()=>{}),Io($e,V.getMessages(),Z),ni(),Sd(),sk(),yl(V.isStreaming()),an!==o.contextMentions&&sC();let _o=o.voiceRecognition?.enabled===!0,Nn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),jt=no(o.voiceRecognition?.provider);if(_o&&(Nn||jt))if(!De||!Dn){let pe=Ia(o);if(pe){De=pe.button,Dn=pe.wrapper;let kt=ro&&ro.parentElement===js?ro:null;js?js.insertBefore(Dn,kt):Pn?.appendChild(Dn),Bt&&(Bt.micButton=De),Bt?.addListener(De,"click",km),De.disabled=pr()||V.isStreaming()&&!Jf()}}else{let pe=o.voiceRecognition??{},kt=o.sendButton??{},Lt=pe.iconName??"mic",_t=pe.iconSize,en=parseFloat(_t??"")||Co;De.classList.add(Mo),De.classList.toggle(rr,!_t),De.style.width=_t??"",De.style.height=_t??"",De.style.minWidth=_t??"",De.style.minHeight=_t??"";let Qn=pe.iconColor??kt.textColor;De.innerHTML="";let Jo=We(Lt,en,Qn||"currentColor",1.5);Jo?De.appendChild(Jo):De.textContent="\u{1F3A4}";let Fn=pe.backgroundColor??kt.backgroundColor;Fn?De.style.backgroundColor=Fn:De.style.backgroundColor="",Qn?De.style.color=Qn:De.style.color="var(--persona-text, #111827)",pe.borderWidth?(De.style.borderWidth=pe.borderWidth,De.style.borderStyle="solid"):(De.style.borderWidth="",De.style.borderStyle=""),pe.borderColor?De.style.borderColor=pe.borderColor:De.style.borderColor="",pe.paddingX?(De.style.paddingLeft=pe.paddingX,De.style.paddingRight=pe.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),pe.paddingY?(De.style.paddingTop=pe.paddingY,De.style.paddingBottom=pe.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Vn=pe.tooltipText??"Start voice recognition",yr=pe.showTooltip??!1;De.setAttribute("aria-label",Vn),Dn&&$n({anchor:De,trigger:Dn,text:()=>De?.getAttribute("aria-label")??Vn,enabled:yr}),Dn.style.display="",De.disabled=pr()||V.isStreaming()&&!Jf()}else De&&Dn&&(Dn.style.display="none",no(o.voiceRecognition?.provider)?V.isVoiceActive()&&V.toggleVoice():fr&&Cs());if(Pm(),o.attachments?.enabled===!0){if(!In||!Zt){let pe=o.attachments??{};_n||(_n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),_n.style.display="none",(we.parentElement??Pn).insertBefore(_n,we)),Gt||(Gt=document.createElement("input"),Gt.type="file",Gt.accept=(pe.allowedTypes??Qr).join(","),Gt.multiple=(pe.maxFiles??4)>1,Gt.style.display="none",Gt.setAttribute("aria-label","Attach files"),(we.parentElement??Pn).insertBefore(Gt,we)),In=v("div","persona-send-button-wrapper"),Zt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Mo} ${rr}`),Zt.type="button",Zt.setAttribute("aria-label",pe.buttonTooltipText??"Attach file");let kt=pe.buttonIconName??"paperclip";Zt.style.fontSize="18px",Zt.style.lineHeight="1";let Lt=We(kt,Co,"currentColor",1.5);Lt?Zt.appendChild(Lt):Zt.textContent="\u{1F4CE}",Zt.addEventListener("click",en=>{en.preventDefault(),Gt?.click()}),In.appendChild(Zt);let _t=pe.buttonTooltipText??"Attach file";$n({anchor:Zt,trigger:In,text:()=>Zt?.getAttribute("aria-label")??_t}),Kn?Kn.append(In):Pn.appendChild(In),Bt&&(Bt.attachmentButton=Zt,Bt.attachmentInput=Gt??void 0,Bt.attachmentPreviews=_n??void 0),!ut&&Gt&&_n&&(ut=rc.fromConfig(pe,nb),ut.setPreviewsContainer(_n),Bt?.addListener(Gt,"change",async()=>{ut&&Gt?.files&&(await ut.handleFileSelect(Gt.files),Gt.value="")}))}else{In.style.display="";let pe=o.attachments??{};Gt&&(Gt.accept=(pe.allowedTypes??Qr).join(","),Gt.multiple=(pe.maxFiles??4)>1),ut&&ut.updateConfig({allowedTypes:pe.allowedTypes,maxFileSize:pe.maxFileSize,maxFiles:pe.maxFiles,adapter:pe.adapter})}if(Be.querySelector(".persona-attachment-drop-overlay")?.remove(),Be.appendChild(n0(o.attachments?.dropOverlay)),Zt){let pe=o.attachments??{},kt=pe.buttonTooltipText??"Attach file";Zt.setAttribute("aria-label",kt),Zt.textContent="";let Lt=We(pe.buttonIconName??"paperclip",Co,"currentColor",1.5);Lt?Zt.appendChild(Lt):Zt.textContent="\u{1F4CE}",In&&$n({anchor:Zt,trigger:In,text:()=>Zt?.getAttribute("aria-label")??kt})}}else In&&(In.style.display="none"),ut&&ut.clearAttachments(),Be.querySelector(".persona-attachment-drop-overlay")?.remove();let at=o.sendButton??{},Ms=at.useIcon??!1,Tn=at.iconText??"\u2191",vo=at.iconName,Vr=at.tooltipText??"Send message",Rm=at.showTooltip??!1,yi=at.size,Wm=parseFloat(yi??"")||Mg,$r=at.backgroundColor,bi=at.textColor;if(Ms){if(ze.style.width=yi??"",ze.style.height=yi??"",ze.style.minWidth=yi??"",ze.style.minHeight=yi??"",ze.style.fontSize="18px",ze.style.lineHeight="1",bi?ze.style.color=bi:ze.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!V.isStreaming())if(ze.innerHTML="",vo){let pe=parseFloat(at.iconSize??"")||Math.round(Wm*.5),kt=bi?.trim()||"currentColor",Lt=at.iconStrokeWidth??2,_t=We(vo,pe,kt,Lt),en=We(at.stopIconName??"square",pe,kt,Lt);_t&&en?ze.appendChild(Tg(_t,en)):_t?ze.appendChild(_t):ze.textContent=Tn}else ze.textContent=Tn;ze.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Mo}`,$r?(ze.style.backgroundColor=$r,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=o.copy?.sendButtonLabel??"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.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",$r?(ze.style.backgroundColor=$r,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),bi?ze.style.color=bi:ze.classList.add("persona-text-white");at.borderWidth?(ze.style.borderWidth=at.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),at.borderColor?ze.style.borderColor=at.borderColor:ze.style.borderColor="",at.paddingX?(ze.style.paddingLeft=at.paddingX,ze.style.paddingRight=at.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),at.paddingY?(ze.style.paddingTop=at.paddingY,ze.style.paddingBottom=at.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom=""),V.isStreaming()||ze.setAttribute("aria-label",Vr),Cd(),ro&&$n({anchor:ze,trigger:ro,text:()=>ze.getAttribute("aria-label")??Vr,enabled:Rm}),gb(),_f();let gC=vu(Oe.getState().activeModeIds,o.composer?.modes);Oe.setActiveModeIds(gC),Ki().length>0!==!!Lr&&kf(),Lr?.render(gC,Ki());for(let pe of[...Gi.keys()])bu(pe,o.composer?.modeGroups)||Gi.delete(pe);Gi.forEach(pe=>pe.repaint()),ls?.repaint(),jo?.resolve();let Nd=Os(o,Pe());if(Df(),Nd){$e.style.maxWidth=Nd,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ne.style.maxWidth=Nd,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%";for(let pe of[Pn,eo,_n,Mt])pe&&(pe.style.maxWidth=Nd,pe.style.marginLeft="auto",pe.style.marginRight="auto",pe.style.width="100%")}else{$e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ne.style.maxWidth="",Ne.style.marginLeft="",Ne.style.marginRight="",Ne.style.width="";for(let pe of[Pn,eo,_n,Mt])pe&&(pe.style.maxWidth="",pe.style.marginLeft="",pe.style.marginRight="",pe.style.width="")}let Qo=o.statusIndicator??{};if(Ym(Mt,Pn,Qo),xi(Mt,Qo,V?.getStatus()??"idle"),V){let pe=V.getStatus();Tr(Mt,(Lt=>Lt==="idle"?Qo.idleText??Cn.idle:Lt==="connecting"?Qo.connectingText??Cn.connecting:Lt==="connected"?Qo.connectedText??Cn.connected:Lt==="error"?Qo.errorText??Cn.error:Lt==="paused"?Qo.pausedText??Cn.paused:Lt==="resuming"?Qo.resumingText??Cn.resuming:Cn[Lt])(pe),Qo,pe)}Mt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let zk=Qo.align==="left"?"persona-text-left":Qo.align==="center"?"persona-text-center":"persona-text-right";Mt.classList.add(zk),Tf(),em(),Ko(),Ht()},open(){Se()&&Yt(!0,"api")},close(){Se()&&Yt(!1,"api")},toggle(){Se()&&Yt(!U,"api")},reconnect(){V.reconnectNow()},clearChat(){Pr=!1,i.clear(),r.clear(),s.clear(),l.clear(),V.clearMessages(),o.layout?.topFade&&(ye.scrollTop=0),ye.removeAttribute("data-persona-top-fade"),Yn.clear(),dr();try{localStorage.removeItem(Qa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qa}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),x?.clear&&fd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},ke.syncFromMetadata(),ut?.clearAttachments(),gd(),Yi(void 0),ar(void 0),si(),ee?.clear(),Re?.reset(),bt?.update()},setMessage(a){return!we||V.isStreaming()||pr()?!1:(!U&&Se()&&Yt(!0,"system"),we.value=a,we.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(V.isStreaming()||ui())return!1;let u=a?.trim()||we.value.trim();return u?(!U&&Se()&&Yt(!0,"system"),we.value="",we.style.height="auto",ko(),Hd(u,{consumeDraft:!1}),!0):!1},getComposerState(){return Oe.getState()},setQuote(a){let u=a?.text?.trim();u&&ar({...a,text:u})},clearQuote(){ar(void 0)},startVoiceRecognition(){return V.isStreaming()?!1:no(o.voiceRecognition?.provider)?(V.isVoiceActive()||V.isBargeInActive()||(!U&&Se()&&Yt(!0,"system"),vt.manuallyDeactivated=!1,yo(),V.toggleVoice().then(()=>{vt.active=Uf(),yo(),Br("user"),vt.active&&ma()})),!0):fr?!0:Bv()?(!U&&Se()&&Yt(!0,"system"),vt.manuallyDeactivated=!1,yo(),Bd("user"),!0):!1},stopVoiceRecognition(){return no(o.voiceRecognition?.provider)?!V.isVoiceActive()&&!V.isBargeInActive()?!1:((V.isBargeInActive()?V.deactivateBargeIn():V.toggleVoice()).then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,yo(),Br("user"),Fr()}),!0):fr?(vt.manuallyDeactivated=!0,yo(),Cs("user"),!0):!1},injectMessage(a){return!U&&Se()&&Yt(!0,"system"),V.injectMessage(a)},injectAssistantMessage(a){!U&&Se()&&Yt(!0,"system");let u=V.injectAssistantMessage(a);return R&&(R=!1,G&&(clearTimeout(G),G=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),u},injectUserMessage(a){return!U&&Se()&&Yt(!0,"system"),V.injectUserMessage(a)},injectSystemMessage(a){return!U&&Se()&&Yt(!0,"system"),V.injectSystemMessage(a)},injectMessageBatch(a){return!U&&Se()&&Yt(!0,"system"),V.injectMessageBatch(a)},injectComponentDirective(a){return!U&&Se()&&Yt(!0,"system"),V.injectComponentDirective(a)},injectTestMessage(a){!U&&Se()&&Yt(!0,"system"),V.injectTestEvent(a)},async connectStream(a,u){return V.connectStream(a,u)},__pushEventStreamEvent(a){Ie&&(nn(),wn(a.type,a.payload))},showEventStream(){Ie&&Mf()},hideEventStream(){Ee&&Xi()},isEventStreamVisible(){return Ee},listConversations(a){return V.listConversations(a)},getActiveConversationId(){return V.getActiveConversationId()},openConversation(a,u){return ur(y=>y.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return ur(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){bm()},deleteConversation(a){return ur(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return ur(y=>y.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return ur(y=>y.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return ur(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return ur(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=Ho;if(!a)return null;let u=await a.get();return a===Ho?u:null},getHistoryIdentityStatus(){let a=sn?.historyProvider;return a?a.getIdentityStatus():vl()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return vl()?ur(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){sn?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return Ot},showArtifacts(){po(o)&&(Pr=!1,Ji=!0,Yo(),Et?.setMobileOpen(!0))},hideArtifacts(){po(o)&&(Pr=!0,Yo())},upsertArtifact(a){return po(o)?(ks(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(Pr=!1,Ji=!0),V.upsertArtifact(a)):null},selectArtifact(a){po(o)&&V.selectArtifact(a)},clearArtifacts(){po(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return ve&&!U&&!Pe()||!we?!1:(we.focus(),!0)},async resolveApproval(a,u,y){let H=V.getMessages().find(O=>O.variant==="approval"&&O.approval?.id===a);if(!H?.approval)throw new Error(`Approval not found: ${a}`);if(H.approval.toolType==="webmcp"){V.resolveWebMcpApproval(H.id,u);return}return V.resolveApproval(H.approval,u,y)},setFollowUpSuggestions(a){P0(a)},clearFollowUpSuggestions(){zb()},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...I}},updatePersistentMetadata(a){Te(a)},on(a,u){return L.on(a,u)},off(a,u){L.off(a,u)},isOpen(){return Se()&&U},isVoiceActive(){return vt.active},toggleReadAloud(a){V.toggleReadAloud(a)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(a){return V.getReadAloudState(a)},onReadAloudChange(a){return V.onReadAloudChange(a)},getState(){return{open:Se()&&U,launcherEnabled:ve,voiceActive:vt.active,streaming:V.isStreaming()}},showCSATFeedback(a){!U&&Se()&&Yt(!0,"system");let u=$e.querySelector(".persona-feedback-container");u&&u.remove();let y=JE({onSubmit:async(M,H)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(M,H),a?.onSubmit?.(M,H)},onDismiss:a?.onDismiss,...a});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!U&&Se()&&Yt(!0,"system");let u=$e.querySelector(".persona-feedback-container");u&&u.remove();let y=ZE({onSubmit:async(M,H)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(M,H),a?.onSubmit?.(M,H)},onDismiss:a?.onDismiss,...a});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return V.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return V.submitNPSFeedback(a,u)},destroy(){um(),fi!=null&&(clearInterval(fi),fi=null),i.clear(),r.clear(),s.clear(),l.clear(),Ue.forEach(a=>a()),ot.remove(),cn?.remove(),hn?.destroy(),so?.remove(),ei&&Ze.removeEventListener("click",ei)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:yn,getMessages:yn.getMessages,getStatus:yn.getStatus,getMetadata:yn.getPersistentMetadata,updateMetadata:yn.updatePersistentMetadata,clearHistory:()=>yn.clearChat(),setVoiceActive:y=>y?yn.startVoiceRecognition():yn.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ue.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.focusInput()};if(window.addEventListener("persona:focusInput",u),Ue.push(()=>{window.removeEventListener("persona:focusInput",u)}),Ie){let be=Ae=>{let Ke=Ae.detail;(!Ke?.instanceId||Ke.instanceId===a)&&yn.showEventStream()},Ce=Ae=>{let Ke=Ae.detail;(!Ke?.instanceId||Ke.instanceId===a)&&yn.hideEventStream()};window.addEventListener("persona:showEventStream",be),window.addEventListener("persona:hideEventStream",Ce),Ue.push(()=>{window.removeEventListener("persona:showEventStream",be),window.removeEventListener("persona:hideEventStream",Ce)})}let y=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.showHistory()},M=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.hideHistory()};window.addEventListener("persona:showHistory",y),window.addEventListener("persona:hideHistory",M),Ue.push(()=>{window.removeEventListener("persona:showHistory",y),window.removeEventListener("persona:hideHistory",M)});let H=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.showArtifacts()},O=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.hideArtifacts()},se=be=>{let Ce=be.detail;Ce?.instanceId&&Ce.instanceId!==a||Ce?.artifact&&yn.upsertArtifact(Ce.artifact)},ge=be=>{let Ce=be.detail;Ce?.instanceId&&Ce.instanceId!==a||typeof Ce?.id=="string"&&yn.selectArtifact(Ce.id)},ce=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.clearArtifacts()};window.addEventListener("persona:showArtifacts",H),window.addEventListener("persona:hideArtifacts",O),window.addEventListener("persona:upsertArtifact",se),window.addEventListener("persona:selectArtifact",ge),window.addEventListener("persona:clearArtifacts",ce),Ue.push(()=>{window.removeEventListener("persona:showArtifacts",H),window.removeEventListener("persona:hideArtifacts",O),window.removeEventListener("persona:upsertArtifact",se),window.removeEventListener("persona:selectArtifact",ge),window.removeEventListener("persona:clearArtifacts",ce)})}let Wo=P_(o.persistState);if(Wo&&Se()){let a=I_(Wo.storage),u=`${Wo.keyPrefix}widget-open`,y=`${Wo.keyPrefix}widget-voice`,M=`${Wo.keyPrefix}widget-voice-mode`;if(a){let H=Wo.persist?.openState&&a.getItem(u)==="true",O=Wo.persist?.voiceState&&a.getItem(y)==="true",se=Wo.persist?.voiceState&&a.getItem(M)==="true";if(H&&(hn?.setPanelOpen(!0,"auto"),setTimeout(()=>{yn.open(),setTimeout(()=>{if(O||se)yn.startVoiceRecognition();else if(Wo.persist?.focusInput){let ge=e.querySelector("textarea");ge&&ge.focus()}},100)},0)),Wo.persist?.openState&&(L.on("widget:opened",()=>{a.setItem(u,"true")}),L.on("widget:closed",()=>{a.setItem(u,"false")})),Wo.persist?.voiceState&&(L.on("voice:state",ge=>{a.setItem(y,ge.active?"true":"false")}),L.on("user:message",ge=>{a.setItem(M,ge.viaVoice?"true":"false")})),Wo.clearOnChatClear){let ge=()=>{a.removeItem(u),a.removeItem(y),a.removeItem(M)},ce=()=>ge();window.addEventListener("persona:clear-chat",ce),Ue.push(()=>{window.removeEventListener("persona:clear-chat",ce)})}}}if(oe&&Se()&&(hn?.setPanelOpen(!0,"auto"),setTimeout(()=>{yn.open()},0)),aa(),!I0){let a=va(()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))});Ue.push(a)}E=()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))},V.getMessages().length>0&&vd(),T=()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))};let $k=LC(()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))});Ue.push($k);let Uk=Ay(()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z),ts()?.updateInlineArtifactBlocks($e,Lo.artifacts,{suppressTransition:!0}),Yo())});return Ue.push(Uk),yn};nr();var r0=(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},W_=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},B_=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},D_=(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.")},s0=(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"},Zy=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=""},i0=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Zy(e)},Xy=e=>{e.style.transition=""},Qy=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=""},Jy=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},bf=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},__=(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))},O_=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},N_=e=>{let t=Jr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:zn(t,r)??r;return{inset:o(n?.inset,Su),canvasBackground:o(n?.canvasBackground,Au)}},a0=(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},F_=(e,t,n,o,r,s,i,l)=>{let c=$o(s),d=c.reveal==="push",p=l!=null,f=l?.inset??"",m=l?.canvasBackground??"";__(e,t,n,o,d),O_(e,t,n,o,c.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"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 g=e.ownerDocument.defaultView,h=s?.launcher?.mobileFullscreen??!0,b=s?.launcher?.mobileBreakpoint??640,C=g!=null?g.innerWidth<=b:!1;if(h&&C&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Qy(t),Xy(o),i0(o),Jy(n),bf(r,o),a0(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??Jn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(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"),i0(o),W_(o,c.maxHeight),a0(o,p&&i,f,m),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Qy(t),Xy(o),Jy(n),bf(r,o);let S=c.animate?"transform 180ms ease":"none",E=c.side==="right"?"translateX(100%)":"translateX(-100%)",k=i?"translateX(0)":E;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=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=S,o.style.transform=k,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Xy(o),Zy(o),bf(r,o);let S=r0(c.width,e.clientWidth),E=Math.max(0,e.clientWidth),k=c.animate?"margin-left 180ms ease":"none",D=c.side==="right"?i?-S:0:i?0:-S;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=`${E+S}px`,t.style.transition=k,t.style.marginLeft=`${D}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Qy(t),Zy(o),Jy(n),bf(r,o);let S=c.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=i?c.width:"0px",k=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",D=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",B_(o,c.maxHeight),o.style.overflow=S||D?"hidden":"visible",o.style.transition=k,S){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let z=p?`calc(${r0(c.width,e.clientWidth)}px - (2 * ${f}))`:c.width;r.style.width=z,r.style.minWidth=z,r.style.maxWidth=z,r.style.boxSizing="border-box"}}},V_=(e,t)=>{let n=e.ownerDocument.createElement("div");return s0(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){s0(n,o)},destroy(){n.remove()}}},$_=(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,i=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),d=n.createElement("aside"),p=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",d.appendChild(p),o.insertBefore(i,e),c.appendChild(e);let m=null,g=()=>{m?.disconnect(),m=null},h=null,b=()=>{h=t?.launcher?.detachedPanel===!0?N_(t):null};b();let C=()=>{F_(i,l,c,d,p,t,f,h)},A=null,S=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Mu(()=>{b(),C()}))},E=()=>{g(),$o(t).reveal==="push"&&(typeof ResizeObserver>"u"||(m=new ResizeObserver(()=>{C()}),m.observe(i)))},k=!1,D=()=>{C(),E(),f&&!k&&i.dataset.personaDockMobileFullscreen!=="true"&&(k=!0,D_(i,$o(t)))},z=i.ownerDocument.defaultView,Y=()=>{D()};return z?.addEventListener("resize",Y),$o(t).reveal==="push"?(l.appendChild(c),l.appendChild(d),i.appendChild(l)):(i.appendChild(c),i.appendChild(d)),D(),S(),{mode:"docked",host:p,shell:i,syncWidgetState(T){let W=T.launcherEnabled?T.open:!0;f!==W&&(f=W,D())},updateConfig(T){t=T,(t?.launcher?.enabled??!0)===!1&&(f=!0),b(),D(),S()},destroy(){z?.removeEventListener("resize",Y),A?.(),A=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},l0=(e,t)=>un(t)?$_(e,t):V_(e,t);er();var jc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},c0=.15,d0=1.5,eb="persona-preview-shell-theme",U_={load:()=>null,save:()=>{},clear:()=>{}},z_=["How do I get started?","Pricing & plans","Talk to support"];function tb(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function q_(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function p0(e){let t=q_(e);return`* { box-sizing: border-box; }
1286
+ `)}if(!H&&!u){let et="max-height: -moz-available !important; max-height: stretch !important;",Ct=y?"":"padding-top: 1.25em !important;",at=y?"":`z-index: ${o.launcher?.zIndex??Jn} !important;`;ot.style.cssText+=et+Ct+at}dn(),_o()},Df=()=>{e.style.setProperty("--persona-content-max-width",Os(o,Pe()))},kb=!1;function Lb(){o.layout?.topFade&&ye.scrollTop>1?ye.setAttribute("data-persona-top-fade","true"):ye.removeAttribute("data-persona-top-fade")}let _f=()=>{Lb();let a=vh(o,Pe());Pe()&&o.composer?.placement&&o.debug===!0&&!kb&&(kb=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let u=B();e.setAttribute("data-persona-composer-placement",a),e.setAttribute("data-persona-conversation-state",Q),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",u.composerGap??Tu),on()},Pb=()=>{if(Pe())return;let a=un(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!ve)return;let M=e.ownerDocument.defaultView??window,H=o.launcher?.mobileFullscreen??!0,O=o.launcher?.mobileBreakpoint??640;if(H&&M.innerWidth<=O)return;let se=Wi(o);Ve.style.height=se.height,Ve.style.maxHeight=se.maxHeight};Bf(),lc(e,o),_c(e,o),Oc(e,o),Df(),_f(),Qs=()=>{Bf(),Pb(),lc(e,o),_c(e,o),Oc(e,o),Df(),_f(),Jc?e.style.setProperty("--persona-artifact-welded-outer-radius",Jc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),St(),Ht()};let Ue=[];Ue.push(()=>{Cb=!0}),Ue.push(()=>{m.forEach(a=>a()),f.destroy()}),Ue.push(()=>{document.removeEventListener("keydown",Ab)}),Ue.push(()=>{as!==null&&clearTimeout(as)});let lr=null,cr=null;Ue.push(()=>{lr?.(),lr=null,cr?.(),cr=null}),sl&&Ue.push(()=>{sl?.disconnect(),sl=null}),Ue.push(()=>{cl?.(),cl=null,Wf(),pn&&(pn.remove(),pn=null),Et?.element.style.removeProperty("width"),Et?.element.style.removeProperty("maxWidth"),Et?.destroy()}),Ie&&Ue.push(()=>{yt=!0,Fe=null,He!==null&&(cancelAnimationFrame(He),He=null),bt?.destroy(),bt=null,ee?.destroy(),ee=null,Ut=null});let Js=null,Ib=()=>{Js&&(Js(),Js=null),o.colorScheme==="auto"&&(Js=Mu(()=>{lc(e,o)}))};Ib(),Ue.push(()=>{Js&&(Js(),Js=null)}),Ue.push(()=>{S=!0,A?.()}),Ue.push(()=>{z=!0});let Hb=!1;Ue.push(()=>{Hb=!0});let Of=(a,u)=>{let y=uc(a,u);return y||!JA.includes(a)?y:(yM().then(M=>{if(Hb)return;Pi(M.wipe),Pi(M.glyphCycle);let H=uc(a,u);H&&gc(H,e)}).catch(()=>{}),null)},ad=o.features?.streamAnimation;if(ad?.type&&ad.type!=="none"){let a=Of(ad.type,ad.plugins);a&&gc(a,e),Ue.push(()=>ZA(e))}let Hr=wc(eo),Rb=wc(uo),Wb=wc(fo),Zs=[Hr,Rb,Wb];Ue.push(()=>{Zs.forEach(a=>a.destroy())});let ei=null,V,ti=null,Bb=!1,Db=0,_b=null,Ob=a=>a.reduce((u,y)=>y.role==="user"?u+1:u,0),Nb=a=>{for(let u=a.length-1;u>=0;u--)if(Ol(a[u]))return a[u].id??null;return null},Fb=!1,P0=()=>{Fb||o.debug!==!0||(Fb=!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".'))},Vb=!1,$b=!1,Ub=(a,u)=>{Vb||o.debug!==!0||!u.enabled||u.expose||Bb||$b&&(V.isStreaming()||a.some(Ol)||(Vb=!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.")))},ni=a=>{if(!V)return;let u=a??V.getMessages(),y=Ae=>{Ae.render([],V,we,u)},M=Ae=>{Zs.forEach(Ke=>{Ke!==Ae&&y(Ke)})};ti&&(Ob(u)>Db||Nb(u)!==_b)&&(ti=null);let H=Hs(o);Ub(u,H);let O=H.enabled?xw(u):null,se=ti??O,ge=ti?"host":"agent";if(se){let Ae=o.suggestions?.followUps,Ke=Ae?.placement??(Ae?"auto":"composer"),Ft=(Ke==="auto"?Pe()?"composer":"after-message":Ke)==="after-message"?Wb:Hr;M(Ft),Ft.render(se,V,we,u,o.suggestionChipsConfig,{source:ge,surface:"followUp",variant:Ae?.variant??"chip",behavior:Ae?.behavior??"send",overflow:Ae?.overflow??"wrap",maxItems:Ae?.maxItems??4,config:o,plugins:p,submitPrompt:Id});return}if(u.some(Ae=>Ae.role==="user")){Zs.forEach(y);return}let ce=o.future?.v5Defaults===!0,be=go(),Ce=o.suggestions?.starters??(ce?{}:void 0);if(Ce){let Ae=Ua(B(),u),Ke=Ce.placement??"auto",Pt=Ke==="auto"?Ae?"welcome":"composer":Ke;if(Pt==="welcome"&&!Ae){P0(),Zs.forEach(y);return}let Ft=Pt==="welcome"?Rb:Hr;M(Ft),Ft.render(Ce.items??o.suggestionChips,V,we,u,o.suggestionChipsConfig,{surface:"starter",variant:Ce.variant??(ce&&!be?"chip":"card"),behavior:Ce.behavior??"send",overflow:Ce.overflow??"wrap",maxItems:Ce.maxItems??(ce&&!be?3:4),config:o,plugins:p,submitPrompt:Id});return}M(Hr),Hr.render(o.suggestionChips,V,we,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:p,submitPrompt:Id})},zb=()=>{ti&&(ti=null,ni())},I0=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){zb();return}let y=V?V.getMessages():[];ti=u,Bb=!0,Db=Ob(y),_b=Nb(y),ni(y)},xo=!1,Yn=zA(),Zi=new Map,oi=new Map,ps=new Map,ri=null,us=null;function si(){if(!ri)return;let a=ri;ri=null,us?.destroy(),us=null,Yn.delete(a),Be.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),V&&Io($e,V.getMessages(),Z)}let ii=0,H0=Oo()!==null,So=Hu(),Ao=0,fs=null,ho=!1,ld=!1,ms=0,Hn=null,ai=null,Nf=!1,ea=!1,li=null,dl=!0,cd=!1,ta=null,dd=!1,gs=()=>{dd=!0,D0()},Ff=null,R0=4,Rr=24,W0=80,B0=1e3,Wr=null,qb=()=>{e.setAttribute("data-persona-scrollbar",Gs()),Gs()!=="on-scroll"&&(Wr!==null&&clearTimeout(Wr),Wr=null,ye.removeAttribute("data-persona-scrollbar-visible"))},D0=()=>{Gs()==="on-scroll"&&(ye.setAttribute("data-persona-scrollbar-visible",""),Wr!==null&&clearTimeout(Wr),Wr=setTimeout(()=>{Wr=null,Zr(ye,Rr)&&ye.removeAttribute("data-persona-scrollbar-visible")},B0))};qb(),Ue.push(()=>{Wr!==null&&clearTimeout(Wr)});let Vf=new Map,$f=!1,pd=null,vt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Ko();let jb=o.voiceRecognition?.autoResume??!1,Uf=()=>V.isVoiceActive()||V.isBargeInActive(),Kb=!1,Br=a=>{L.emit("voice:state",{active:vt.active,source:a,timestamp:Date.now()})},yo=()=>{Te(a=>({...a,voiceState:{active:vt.active,timestamp:Date.now(),manuallyDeactivated:vt.manuallyDeactivated}}))},_0=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Yy(I.voiceState),u=!!a.active,y=Number(a.timestamp??0);vt.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-y<T_&&setTimeout(()=>{vt.active||(vt.manuallyDeactivated=!1,no(o.voiceRecognition?.provider)?V.toggleVoice().then(()=>{vt.active=Uf(),Br("restore"),vt.active?ma():(yo(),Pd(E_,1e4))}):Bd("restore"))},no(o.voiceRecognition?.provider)?0:1e3)},Gb=a=>{Kb=!a.persisted,vt.active&&yo()};typeof window<"u"&&(window.addEventListener("pagehide",Gb),Ue.push(()=>window.removeEventListener("pagehide",Gb)));let O0=()=>V?t0(V.getMessages()).filter(a=>!a.__skipPersist):[],ud=null,Yb=(a,u)=>{typeof console<"u"&&console.error(a,u)},fd=(a,u)=>{let y=()=>{try{let se=a();return!se||typeof se.then!="function"?null:Promise.resolve(se).catch(ge=>{Yb(u,ge)})}catch(se){return Yb(u,se),null}},M=ud,H=M?M.then(()=>y()??void 0):y();if(!H)return;let O=H.finally(()=>{ud===O&&(ud=null)});ud=O};function na(a){if(!x?.save)return;let u=a?t0(a):V?O0():[],y=P&&V?.getResumableHandle();y&&(I={...I,durableResume:{executionId:y.executionId,after:y.lastEventId}});let M={messages:u,metadata:I,artifacts:Lo.artifacts,selectedArtifactId:Lo.selectedId,...ci?{draft:ci}:{}};fd(()=>x.save(M),"[AgentWidget] Failed to persist state:")}let ci,md=()=>!x?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,pl=SA({write:()=>{if(!md())return;let a=Oe.getState(),u=wA({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Cm(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify(ci)&&(ci=u,na())}});function Xb(){md()&&pl.schedule()}function zf(){pl.flush()}function Qb(a){if(!md())return;let u=xA(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(y=>y.id),modelIds:(o.composer?.models??[]).map(y=>y.id),modes:o.composer?.modes??[]});u&&(ci=a,we&&!we.value&&(we.value=u.text,we.dispatchEvent(new Event("input",{bubbles:!0})),ko()),u.selectedModelId&&(Oe.setSelectedModelId(u.selectedModelId),ls?.repaint()),Xc(u.activeModeIds??[]),u.quote&&ar(u.quote),pl.cancel())}function gd(){pl.cancel(),ci&&(ci=void 0,md()&&na())}let oa=null,Jb=()=>ot.querySelector("#persona-scroll-container")||ye,ra=()=>{oa!==null&&(cancelAnimationFrame(oa),oa=null),ho=!1},Zb=()=>{fs!==null&&(cancelAnimationFrame(fs),fs=null),ld=!1,ra()},N0=()=>xo&&jf()&&(Gn()!=="anchor-top"||tl()),qf=()=>{let a=is()||"Jump to latest",u=N0();fn.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),ms>0?(Mn.textContent=String(ms),Mn.style.display="",fn.setAttribute("aria-label",`${a} (${ms} new)`)):(Mn.textContent="",Mn.style.display="none",fn.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},ev=()=>{ms!==0&&(ms=0,qf())},F0=()=>{let a=Hn?.spacerHeight??0;return a<=0?Zr(ye,Rr):bd(a)-ye.scrollTop-ye.clientHeight<=Rr},jf=()=>zo()?!So.isFollowing():!F0(),Kf=()=>!!V&&V.getMessages().length>0,Xn=()=>{if(!Cf()||ss()){fn.parentNode&&fn.remove(),fn.style.display="none";return}fn.parentNode!==Be&&Be.appendChild(fn),Xe();let u=xr(ye)>0&&jf()&&Kf();u?qf():ev(),fn.style.display=u?"":"none"},sa=()=>{So.pause()&&(Zb(),Xn())},dr=()=>{So.resume(),ev(),Xn()},hs=(a=!1)=>{zo()&&Kf()&&So.isFollowing()&&(!a&&!xo||(fs!==null&&(cancelAnimationFrame(fs),fs=null),ld=!0,fs=requestAnimationFrame(()=>{fs=null,ld=!1,So.isFollowing()&&V0(Jb(),a?220:140)})))},tv=(a,u,y,M=()=>!0)=>{let H=a.scrollTop,O=u(),se=O-H;if(ra(),Math.abs(se)<1){ho=!0,a.scrollTop=O,Ao=a.scrollTop,ho=!1;return}let ge=performance.now();ho=!0;let ce=Ce=>1-Math.pow(1-Ce,3),be=Ce=>{if(!M()){ra();return}let Ae=u();Ae!==O&&(O=Ae,se=O-H);let Ke=Ce-ge,Pt=Math.min(Ke/y,1),Ft=ce(Pt),Dt=H+se*Ft;a.scrollTop=Dt,Ao=a.scrollTop,Pt<1?oa=requestAnimationFrame(be):(a.scrollTop=O,Ao=a.scrollTop,oa=null,ho=!1)};oa=requestAnimationFrame(be)},V0=(a,u=500)=>{let y=xr(a)-a.scrollTop;if(Math.abs(y)<1){Ao=a.scrollTop;return}if(Math.abs(y)>=W0){ra(),ho=!0,a.scrollTop=xr(a),Ao=a.scrollTop,ho=!1;return}tv(a,()=>xr(a),u,()=>So.isFollowing())},Gf=()=>{if(!Kf()){Xn();return}let a=Jb();ho=!0,a.scrollTop=xr(a),Ao=a.scrollTop,ho=!1,Xn()},di=a=>{let u=0,y=a;for(;y&&y!==ye;)u+=y.offsetTop,y=y.offsetParent;return u},$0=()=>{let a=ye.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ye.ownerDocument.getSelection()},hd=()=>YA($0(),ye),Yf=()=>{if(Yc()!=="last-user-turn")return!1;let a=V?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(O=>O.role==="user");if(!u)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),M=ye.querySelector(`[data-message-id="${y}"]`);if(!M)return!1;let H=Math.min(Math.max(0,di(M)-Ks()),xr(ye));return ho=!0,ye.scrollTop=H,Ao=ye.scrollTop,ho=!1,Gn()==="follow"&&!Zr(ye,Rr)&&So.pause(),Xn(),!0},yd=a=>{let u=Math.max(0,Math.round(a));xn.style.height=`${u}px`,xn.style.display=u>0?"":"none",Hn&&(Hn.spacerHeight=Math.max(0,a))},bd=a=>{let u=parseFloat(getComputedStyle(ye).paddingBottom)||0,y=0;for(let H of Array.from(ye.children)){if(H===xn||H.offsetHeight===0)continue;let O=di(H)+H.offsetHeight;O>y&&(y=O)}let M=ye.scrollHeight-a;return y>0?Math.min(y+u,M):M},U0=()=>{if(!Hn||Hn.spacerHeight<=0)return;let a=bd(Hn.spacerHeight),u=Math.max(0,Math.round(ye.scrollTop)+ye.clientHeight-a+Rr);u<Hn.spacerHeight&&(yd(u),Xn())},pi=()=>{ai!==null&&(cancelAnimationFrame(ai),ai=null),ra(),Hn=null,xn.style.height="0px",xn.style.display="none"},nv=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xf=a=>ye.querySelector(`[data-message-id="${nv(a)}"]`),ov=a=>{ai!==null&&cancelAnimationFrame(ai),ai=requestAnimationFrame(()=>{ai=null;let u=nv(a),y=ye.querySelector(`[data-message-id="${u}"]`);if(!y)return;let M=di(y),H=Hn?.spacerHeight??0,O=bd(H),{targetScrollTop:se,spacerHeight:ge}=xh({anchorOffsetTop:M,topOffset:Ks(),viewportHeight:ye.clientHeight,contentHeight:O,slack:Rr});Hn={initialSpacerHeight:ge,contentHeightAtAnchor:O,spacerHeight:ge},yd(ge),tv(ye,()=>y.isConnected?Math.max(0,di(y)-Ks()):se,220)})},ia=()=>{if(Gn()!=="anchor-top"||!Hn||!ta)return;let a=Xf(ta);if(!a)return;ra();let u=Hn.spacerHeight,y=bd(u),{targetScrollTop:M,spacerHeight:H}=xh({anchorOffsetTop:di(a),topOffset:Ks(),viewportHeight:ye.clientHeight,contentHeight:y,slack:Rr});Hn={initialSpacerHeight:H,contentHeightAtAnchor:y,spacerHeight:H},yd(H),ho=!0,ye.scrollTop=M,Ao=ye.scrollTop,ho=!1,Xn()},z0=()=>{if(zo()){if(!So.isFollowing()||Zr(ye,1))return;hs(!xo);return}if(Hn&&Hn.initialSpacerHeight>0){let a=ye.scrollHeight-Hn.spacerHeight,u=XA({initialSpacerHeight:Hn.initialSpacerHeight,contentHeightAtAnchor:Hn.contentHeightAtAnchor,currentContentHeight:a});u!==Hn.spacerHeight&&yd(u)}Xn()},q0=a=>{let u=Gn();u==="follow"?(dr(),hs(!0)):u==="anchor-top"&&(dl=!1,cd=!0,dd=!1,ta=a,ov(a))},j0=()=>{if(Gn()==="anchor-top"){if(cd){dl=!1;return}dl=!0,pi(),dr(),hs(!0)}},K0=96,G0=a=>{if(li===null)return!0;let u=Xf(li),y=Xf(a);if(!u||!y)return!0;let M=di(y)-di(u);return Ks()+M>ye.clientHeight-K0},Y0=a=>{if(Gn()!=="anchor-top"||!cd||dd||hd())return;let u=li===null;for(let y of a){if(!u){y.id===li&&(u=!0);continue}if(GA(y)){if(y.id===ta||!G0(y.id))return;ta=y.id,ov(y.id);return}}},X0=a=>{let u=new Map;a.forEach(y=>{let M=Vf.get(y.id);u.set(y.id,{streaming:y.streaming,role:y.role}),!M&&y.role==="assistant"&&(L.emit("assistant:message",y),!ea&&(Gn()!=="anchor-top"||tl())&&jf()&&(ms+=1,qf(),Xn(),Xs(ms===1?"1 new message below.":`${ms} new messages below.`))),y.role==="assistant"&&M?.streaming&&y.streaming===!1&&L.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(M?y.approval.status!=="pending"&&L.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):L.emit("approval:requested",{approval:y.approval,message:y}))}),Vf.clear(),u.forEach((y,M)=>{Vf.set(M,y)})},ul=(a,u)=>{let y=u==="user"?"user":"assistant",M=o.layout?.messages?.[y],H=M?.width??"content",O=M?.maxWidth??(H==="full"?`var(--persona-message-${y}-max-width, 100%)`:void 0);a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${H}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",H),O?a.style.setProperty("--persona-message-row-max-width",O):a.style.removeProperty("--persona-message-row-max-width")},Dr=(a,u)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${a}`,y.setAttribute("data-wrapper-id",a),ul(y,u),y},Q0=(a,u,y)=>{let M=new Set;for(let q of u){let rt=q.variant==="tool"?"tool":q.variant==="reasoning"?"reasoning":null;if(!rt||Es(o,rt)!=="row")continue;let st=rt==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;st?.expandable!==!1&&(M.add(q.id),i.observe(q,rt,rt==="tool"?r:s,st))}let H=document.createElement("div"),se=(()=>{let q=p.find(rt=>rt.renderLoadingIndicator);if(q?.renderLoadingIndicator)return q.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),ge=(q,rt)=>rt==null?!1:typeof rt=="string"?(q.textContent=rt,!0):(q.appendChild(rt),!0),ce=new Set,be=new Map,Ce=new Set,Ae=p.some(q=>q.renderAskUserQuestion),Ke=[],Pt=[],Ft=o.enableComponentStreaming!==!1,Dt=o.approval!==!1,bo=[],an=o.messageActions,mn=an?.showRegenerate===!0&&an.enabled!==!1&&Po.current?.isStreaming()!==!0?hS(u):null,io=an?.showEdit===!0&&an.enabled!==!1,bn=an?.showQuote===!0&&an.enabled!==!1,zt=null,mr=o.features?.reasoningDisplay?.completedVisibility,gr=q=>mr==="removed"?!0:mr==="removed-when-short"?tw(q,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Bo=o.features?.toolCallDisplay?.completedVisibility==="removed",Do=q=>q.variant==="reasoning"&&q.reasoning?.status==="complete"?gr(q.reasoning):Bo&&q.variant==="tool"&&q.toolCall?.status==="complete";if(u.forEach(q=>{if(Do(q))return;if(ce.add(q.id),be.set(q.id,q.role),ri===q.id&&us){let it=Dr(q.id,q.role);it.setAttribute("data-persona-message-edit-stub","true"),it.setAttribute("data-preserve-runtime","true"),H.appendChild(it),zt={messageId:q.id,element:us.element};return}let rt=Ae&&Mi(q),st=Dt&&q.variant==="approval"&&!!q.approval,he=!rt&&q.role==="assistant"&&!q.variant&&Ft&&Gy(q);!st&&ps.has(q.id)&&(a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime"),ps.delete(q.id)),!he&&oi.has(q.id)&&(a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime"),oi.delete(q.id));let qt=Mi(q)?`:${q.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${q.agentMetadata?.askUserQuestionAnswers?Object.keys(q.agentMetadata.askUserQuestionAnswers).length:0}`:"",Sn={canRegenerate:mn===q.id,canEdit:io&&Yg(q),canQuote:bn&&!q.variant&&(q.content?.trim().length??0)>0},to=`${Sn.canRegenerate?"r":""}${Sn.canEdit?"e":""}${Sn.canQuote?"q":""}`,On=UA(q,ii)+qt+`:${to}`,Xt=rt||st||he?null:qA(Yn,q.id,On);if(Xt){H.appendChild(Xt.cloneNode(!0)),Mi(q)&&q.toolCall?.id&&q.agentMetadata?.awaitingLocalTool===!0&&!q.agentMetadata?.askUserQuestionAnswered&&(Ce.add(q.toolCall.id),Rf(q));return}let vn=null,Rn=p.find(it=>!!(q.variant==="reasoning"&&it.renderReasoning||q.variant==="tool"&&it.renderToolCall||!q.variant&&it.renderMessage)),Qe=o.layout?.messages;if(Mi(q)&&q.agentMetadata?.askUserQuestionAnswered===!0){Zi.delete(q.id),a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ol(q)&&Hs(o).enabled)return;if(Mi(q)&&o.features?.askUserQuestion?.enabled!==!1){let it=p.find(Wn=>typeof Wn.renderAskUserQuestion=="function");if(it&&Po.current){let Wn=Zi.get(q.id),_o=Wn!==On,Nn=null;if(_o){let{payload:Ct,complete:at}=Aa(q),Ms=q.id,Tn=()=>Po.current?.getMessages().find(vo=>vo.id===Ms);Nn=it.renderAskUserQuestion({message:q,payload:Ct,complete:at,resolve:vo=>{let Vr=Tn();Vr&&Po.current?.resolveAskUserQuestion(Vr,vo)},dismiss:()=>{let vo=Tn();vo?.agentMetadata?.awaitingLocalTool&&(Po.current?.markAskUserQuestionResolved(vo),Po.current?.resolveAskUserQuestion(vo,"(dismissed)"))},config:o})}let jt=Wn!=null;if(_o&&Nn===null&&!jt){q.agentMetadata?.awaitingLocalTool===!0&&!q.agentMetadata?.askUserQuestionAnswered&&(Ce.add(q.toolCall.id),Rf(q));return}let et=Dr(q.id,q.role);et.setAttribute("data-ask-plugin-stub","true"),et.setAttribute("data-preserve-runtime","true"),H.appendChild(et),Ke.push({messageId:q.id,fingerprint:On,bubble:Nn});return}else{q.agentMetadata?.awaitingLocalTool===!0&&!q.agentMetadata?.askUserQuestionAnswered&&(Ce.add(q.toolCall.id),Rf(q));return}}else if(st){let it=D();if(!it){H.appendChild(Dr(q.id,q.role));return}let Wn=p.find(et=>typeof et.renderApproval=="function")??C,Nn=ps.get(q.id)!==On,jt=null;if(Nn&&Wn?.renderApproval){let et=q.id,Ct=(at,Ms)=>{let Tn=Po.current?.getMessages().find(vo=>vo.id===et);Tn?.approval&&(Tn.approval.toolType==="webmcp"?Po.current?.resolveWebMcpApproval(Tn.id,at):Po.current?.resolveApproval(Tn.approval,at,Ms))};jt=Wn.renderApproval({message:q,defaultRenderer:()=>it.createApprovalBubble(q,o,l),config:o,approve:at=>Ct("approved",at),deny:at=>Ct("denied",at)})}if(Nn&&jt===null)a.querySelector(`#wrapper-${q.id}`)?.removeAttribute("data-preserve-runtime"),ps.delete(q.id),vn=it.createApprovalBubble(q,o,l);else{let et=Dr(q.id,q.role);et.setAttribute("data-approval-plugin-stub","true"),et.setAttribute("data-preserve-runtime","true"),H.appendChild(et),bo.push({messageId:q.id,fingerprint:On,bubble:jt});return}}else if(Rn)if(q.variant==="reasoning"&&q.reasoning&&Rn.renderReasoning){if(!le)return;vn=Rn.renderReasoning({message:q,defaultRenderer:()=>Xh(q,o,s),config:o})}else if(q.variant==="tool"&&q.toolCall&&Rn.renderToolCall){if(!Me)return;vn=Rn.renderToolCall({message:q,defaultRenderer:()=>ey(q,o,r),config:o})}else Rn.renderMessage&&(vn=Rn.renderMessage({message:q,defaultRenderer:()=>{let it=Nh(q,y,Qe,o.messageActions,jn,{loadingIndicatorRenderer:se,widgetConfig:o,actionEligibility:Sn});return q.role!=="user"&&W(it,q,o,V),it},config:o}));if(!vn&&he){let it=JE(q);if(it){let Wn=oi.get(q.id),_o=Wn!==On,Nn=o.wrapComponentDirectiveInBubble!==!1&&sr.getOptions(it.component)?.bubbleChrome!==!1,jt=null;if(_o){let et=XE(it,{config:o,message:q,transform:y});if(et&&it.component==="PersonaArtifactInline"){let Ct=et.hasAttribute("data-artifact-inline")?et:et.querySelector("[data-artifact-inline]"),at=Ct?.getAttribute("data-artifact-inline")??"",Ms=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(at):at,Tn=at?a.querySelector(`#wrapper-${q.id}`)?.querySelector(`[data-artifact-inline="${Ms}"]`)??null:null;Ct&&Tn&&Tn!==Ct&&ts()?.hasLiveInlineArtifactBlock(Tn)&&(Ct===et?et=Tn:Ct.replaceWith(Tn))}if(et)if(Nn){let Ct=document.createElement("div");if(Ct.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ct.id=`bubble-${q.id}`,Ct.setAttribute("data-message-id",q.id),q.content&&q.content.trim()){let at=document.createElement("div");at.className="persona-mb-3 persona-text-sm persona-leading-relaxed",at.innerHTML=y({text:q.content,message:q,streaming:!!q.streaming,raw:q.rawContent}),Ct.appendChild(at)}Ct.appendChild(et),jt=Ct}else{let Ct=document.createElement("div");if(Ct.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ct.id=`bubble-${q.id}`,Ct.setAttribute("data-message-id",q.id),Ct.setAttribute("data-persona-component-directive","true"),q.content&&q.content.trim()){let at=document.createElement("div");at.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",at.innerHTML=y({text:q.content,message:q,streaming:!!q.streaming,raw:q.rawContent}),Ct.appendChild(at)}Ct.appendChild(et),jt=Ct}}if(jt||Wn!=null){let et=Dr(q.id,q.role);et.setAttribute("data-component-directive-stub","true"),et.setAttribute("data-preserve-runtime","true"),H.appendChild(et),Pt.push({messageId:q.id,fingerprint:On,bubble:jt});return}}}if(!vn)if(q.variant==="reasoning"&&q.reasoning){if(!le)return;vn=Xh(q,o,s)}else if(q.variant==="tool"&&q.toolCall){if(!Me)return;vn=ey(q,o,r)}else if(q.variant==="approval"&&q.approval){if(o.approval===!1)return;let it=D();if(!it)return;vn=it.createApprovalBubble(q,o,l)}else{let it=o.layout?.messages;it?.renderUserMessage&&q.role==="user"?vn=it.renderUserMessage({message:q,config:o,streaming:!!q.streaming}):it?.renderAssistantMessage&&q.role==="assistant"?vn=it.renderAssistantMessage({message:q,config:o,streaming:!!q.streaming}):vn=Nh(q,y,it,o.messageActions,jn,{loadingIndicatorRenderer:se,widgetConfig:o,actionEligibility:Sn}),q.role!=="user"&&vn&&W(vn,q,o,V)}let Qt=Dr(q.id,q.role);Qt.appendChild(vn),jA(Yn,q.id,On,Qt),H.appendChild(Qt)}),wt.composerOverlay&&wt.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(rt=>{let st=rt.getAttribute("data-persona-ask-sheet-for");st&&!Ce.has(st)&&Ei(wt.composerOverlay,st)}),o.features?.toolCallDisplay?.grouped){let q=[],rt=[],st=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(he=>{if(he.variant==="tool"&&he.toolCall&&Me){if(Bo&&he.toolCall.status==="complete")return;rt.push(he);return}he.variant==="reasoning"&&(!le||he.reasoning?.status==="complete"&&gr(he.reasoning))||((rt.length>1||st&&rt.length>0)&&q.push(rt),rt=[])}),(rt.length>1||st&&rt.length>0)&&q.push(rt),q.forEach(he=>{let qt=he.map(Qe=>Array.from(H.children).find(Qt=>Qt instanceof HTMLElement&&Qt.getAttribute("data-wrapper-id")===Qe.id)).filter(Qe=>!!Qe);if(qt.length<(st?1:2))return;let Sn=Dr(`tool-group-${he[0].id}`,"assistant");if(Sn.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Qe=`tool-group-${he[0].id}`,Qt=he.some(jt=>jt.toolCall?.status!=="complete"),it={...he[0],id:Qe,toolCall:{id:Qe,name:`${he.length} tools`,status:Qt?"running":"complete",chunks:he.flatMap(jt=>jt.toolCall?.chunks??[]),success:!he.some(jt=>jt.toolCall?.success===!1)}};M.add(Qe),i.observe(it,"tool",r,o.features.toolCallDisplay);let Wn=`${Qt?"Using":"Used"} ${he.length} tools`,_o=o.toolCall?.renderGroupedSummary?.({messages:he,toolCalls:he.map(jt=>jt.toolCall),defaultSummary:Wn,config:o}),Nn=IC(it,o,r.has(Qe),_o??Wn);Nn.bubble.classList.add("persona-tool-group"),Nn.body.dataset.personaToolGroupStack="true",qt[0].before(Sn),Sn.appendChild(Nn.bubble),qt.forEach((jt,et)=>{jt.style.setProperty("--persona-message-row-max-width","100%"),jt.style.setProperty("--persona-activity-stagger",`${et*40}ms`),jt.classList.add("persona-activity-group-child"),Nn.body.appendChild(jt)});return}let to=document.createElement("div");to.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",to.setAttribute("data-persona-tool-group","true");let On=document.createElement("div");On.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",On.id=`tool-group-summary-${he[0].id}`;let Xt=`Called ${he.length} ${he.length===1?"tool":"tools"}`,vn=o.toolCall?.renderGroupedSummary?.({messages:he,toolCalls:he.map(Qe=>Qe.toolCall).filter(Qe=>!!Qe),defaultSummary:Xt,config:o});ge(On,vn)||(On.textContent=Xt);let Rn=document.createElement("div");Rn.className="persona-tool-group-stack persona-flex persona-flex-col",Rn.id=`tool-group-stack-${he[0].id}`,Rn.setAttribute("data-persona-tool-group-stack","true"),to.appendChild(On),st||to.appendChild(Rn),Sn.appendChild(to),qt[0].before(Sn),qt.forEach((Qe,Qt)=>{if(st){Qe.remove();return}Qe.style.setProperty("--persona-message-row-max-width","100%");let it=document.createElement("div");it.className="persona-tool-group-item persona-relative",it.setAttribute("data-persona-tool-group-item","true"),Qt<qt.length-1&&it.setAttribute("data-persona-tool-group-connector","true"),it.appendChild(Qe),Rn.appendChild(it)})})}i.prune(M),KA(Yn,ce);let Ss=q=>q.variant==="tool"&&!Me||q.variant==="reasoning"&&!le||Do(q),hr=u.some(q=>q.role==="assistant"&&q.streaming&&!Ss(q)),Xo=u.length-1;for(;Xo>=0&&Ss(u[Xo]);)Xo--;let As=Xo>=0?u[Xo]:void 0,Tl=Xo<u.length-1,hi=As?.role==="assistant"&&!As.streaming&&As.variant!=="approval"&&!Tl;if(xo&&u.some(q=>q.role==="user")&&!hr&&!hi){let q={config:o,streaming:!0,location:"standalone",defaultRenderer:Mc},rt=p.find(he=>he.renderLoadingIndicator),st=null;if(rt?.renderLoadingIndicator&&(st=rt.renderLoadingIndicator(q)),st===null&&o.loadingIndicator?.render&&(st=o.loadingIndicator.render(q)),st===null&&(st=Mc()),st){let he=document.createElement("div"),qt=o.loadingIndicator?.showBubble!==!1,Sn=o.layout?.messages?.layout??"bubble";he.className=qt?Tc("assistant",Sn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),he.setAttribute("data-typing-indicator","true"),qt&&(he.style.color="var(--persona-message-assistant-text, var(--persona-text))",Sn!=="flat"&&(he.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),he.appendChild(st);let to=Dr("typing-indicator","assistant");to.appendChild(he),H.appendChild(to)}}if(!xo&&u.length>0){let q=u[u.length-1],rt={config:o,lastMessage:q,messageCount:u.length},st=p.find(qt=>qt.renderIdleIndicator),he=null;if(st?.renderIdleIndicator&&(he=st.renderIdleIndicator(rt)),he===null&&o.loadingIndicator?.renderIdle&&(he=o.loadingIndicator.renderIdle(rt)),he){let qt=document.createElement("div"),Sn=o.loadingIndicator?.showBubble!==!1;qt.className=Sn?["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(" "),qt.setAttribute("data-idle-indicator","true"),qt.appendChild(he);let to=Dr("idle-indicator","assistant");to.appendChild(qt),H.appendChild(to)}}if(KC(H),Iu(a,H),tg(a),zt){let{messageId:q,element:rt}=zt,st=a.querySelector(`#wrapper-${q}`);st&&rt.parentElement!==st&&(ul(st,be.get(q)??"user"),st.replaceChildren(rt))}if(Ke.length>0)for(let{messageId:q,fingerprint:rt,bubble:st}of Ke){let he=a.querySelector(`#wrapper-${q}`);he&&(ul(he,be.get(q)??"assistant"),st!==null&&(he.replaceChildren(st),he.setAttribute("data-bubble-fp",rt),Zi.set(q,rt)))}if(Zi.size>0)for(let q of Zi.keys())ce.has(q)||Zi.delete(q);if(Pt.length>0)for(let{messageId:q,fingerprint:rt,bubble:st}of Pt){let he=a.querySelector(`#wrapper-${q}`);he&&(ul(he,be.get(q)??"assistant"),st!==null&&(he.replaceChildren(st),he.setAttribute("data-bubble-fp",rt),oi.set(q,rt)))}if(oi.size>0)for(let q of oi.keys())ce.has(q)||oi.delete(q);if(bo.length>0)for(let{messageId:q,fingerprint:rt,bubble:st}of bo){let he=a.querySelector(`#wrapper-${q}`);he&&(ul(he,be.get(q)??"assistant"),st!==null&&(he.replaceChildren(st),he.setAttribute("data-bubble-fp",rt),ps.set(q,rt)))}if(ps.size>0)for(let q of ps.keys())ce.has(q)||ps.delete(q)},Qf=!1,vd=()=>{Qf||(Qf=!0,ki().catch(()=>{}),NC().catch(()=>{Qf=!1}))},Io=(a,u,y)=>{u.length>0&&vd(),Q0(a,u,y),vb()},fl=null,J0=()=>{if(fl)return;let a=y=>{let M=y.composedPath();M.includes(ot)||cn&&M.includes(cn)||Yt(!1,"user")};fl=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},rv=()=>{if(!fl)return;(e.ownerDocument??document).removeEventListener("pointerdown",fl,!0),fl=null};Ue.push(()=>rv());let ml=null,Z0=()=>{if(ml)return;let a=y=>{y.key==="Escape"&&(y.isComposing||Yt(!1,"user"))};ml=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},sv=()=>{if(!ml)return;(e.ownerDocument??document).removeEventListener("keydown",ml,!0),ml=null};Ue.push(()=>sv());let gl=!1,iv=new Set,ek=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},aa=()=>{if(!Pe())return;let a=wt.peekBanner,u=wt.peekTextNode;if(!a||!u)return;if(U){a.classList.remove("persona-pill-peek--visible");return}let y=V?.getMessages()??[],M;for(let an=y.length-1;an>=0;an--){let mn=y[an];if(mn.role==="assistant"&&mn.content){M=mn;break}}if(!M){a.classList.remove("persona-pill-peek--visible");return}let H=M.content,O=!!M.streaming,se=ek(),ge=Bu(se),ce=ge.type!=="none"?Of(ge.type,se?.plugins):null,be=ce?.isAnimating?.(M)===!0,Ce=ce!==null&&(O||be);Ce&&ce&&!iv.has(ce.name)&&(gc(ce,e),iv.add(ce.name));let Ae=Ce&&ce?.containerClass?ce.containerClass:null,Ke=u.dataset.personaPeekStreamClass??null;Ke&&Ke!==Ae&&(u.classList.remove(Ke),delete u.dataset.personaPeekStreamClass),Ae&&Ke!==Ae&&(u.classList.add(Ae),u.dataset.personaPeekStreamClass=Ae),Ce?(u.style.setProperty("--persona-stream-step",`${ge.speed}ms`),u.style.setProperty("--persona-stream-duration",`${ge.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Pt=Ce?Du(H,ge.buffer,ce,M,O):H;if(Ce&&ge.placeholder==="skeleton"&&O&&(!Pt||!Pt.trim())){let an=document.createElement("div"),mn=mc();mn.classList.add("persona-pill-peek__skeleton"),an.appendChild(mn),Iu(u,an)}else{let an=Math.max(0,Pt.length-100),mn=Pt.length>100?Pt.slice(-100):Pt,io=jr(mn);if(!Ce||!ce){let bn=Pt.length>100?`\u2026${mn}`:mn;u.textContent!==bn&&(u.textContent=bn)}else{let bn=io;(ce.wrap==="char"||ce.wrap==="word")&&(bn=fc(io,ce.wrap,`peek-${M.id}`,{skipTags:ce.skipTags,startIndex:an}));let zt=document.createElement("div");if(zt.innerHTML=bn,ce.useCaret&&mn.length>0){let mr=_u(),gr=zt.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bo=gr[gr.length-1];Bo?.parentNode?Bo.parentNode.insertBefore(mr,Bo.nextSibling):zt.appendChild(mr)}Iu(u,zt),ce.onAfterRender?.({container:u,bubble:a,messageId:M.id,message:M,speed:ge.speed,duration:ge.duration})}}let bo=xo||gl;a.classList.toggle("persona-pill-peek--visible",bo)};if(Pe()){let a=wt.peekBanner;if(a){let M=H=>{H.preventDefault(),H.stopPropagation(),Yt(!0,"user")};a.addEventListener("pointerdown",M),Ue.push(()=>{a.removeEventListener("pointerdown",M)})}let u=()=>{gl||(gl=!0,aa())},y=()=>{gl&&(gl=!1,aa())};Ve.addEventListener("pointerenter",u),Ve.addEventListener("pointerleave",y),Ue.push(()=>{Ve.removeEventListener("pointerenter",u),Ve.removeEventListener("pointerleave",y)}),cn&&(cn.addEventListener("pointerenter",u),cn.addEventListener("pointerleave",y),Ue.push(()=>{cn.removeEventListener("pointerenter",u),cn.removeEventListener("pointerleave",y)}))}let tk=a=>{let u=o.launcher?.composerBar??{},y=u.expandedSize??"anchored",M=u.bottomOffset??"16px",H=u.collapsedMaxWidth,O=u.expandedMaxWidth??"880px",se=u.expandedTopOffset??"5vh",ge=u.modalMaxWidth??"880px",ce=u.modalMaxHeight??"min(90vh, 800px)",be="calc(100vw - 32px)",Ce="var(--persona-pill-area-height, 80px)",Ae=ot.style;if(Ae.left="",Ae.right="",Ae.top="",Ae.bottom="",Ae.transform="",Ae.width="",Ae.maxWidth="",Ae.height="",Ae.maxHeight="",cn){let Ke=cn.style;Ke.bottom=M,Ke.width=H??""}if(a&&y!=="fullscreen"){if(y==="modal"){Ae.top="50%",Ae.left="50%",Ae.transform="translate(-50%, -50%)",Ae.bottom="auto",Ae.right="auto",Ae.width=ge,Ae.maxWidth=be,Ae.maxHeight=ce,Ae.height=ce;return}Ae.left="50%",Ae.transform="translateX(-50%)",Ae.bottom=`calc(${M} + ${Ce})`,Ae.top=se,Ae.width=O,Ae.maxWidth=be}},hl=()=>{if(U&&vd(),!Se())return;if(Pe()){let be=(o.launcher?.composerBar??{}).expandedSize??"anchored",Ce=U?"expanded":"collapsed";ot.dataset.state=Ce,ot.dataset.expandedSize=be,cn&&(cn.dataset.state=Ce,cn.dataset.expandedSize=be),ot.style.removeProperty("display"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),tk(U),Be.style.display=U?"flex":"none",Qs(),U?(J0(),Z0()):(rv(),sv()),aa();return}let a=un(o),u=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,M=o.launcher?.mobileFullscreen??!0,H=u.innerWidth<=y,O=M&&H&&ve,se=$o(o).reveal;U?(ot.style.removeProperty("display"),ot.style.display=a?"flex":"",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-95","persona-opacity-0"),Ve.classList.add("persona-scale-100","persona-opacity-100"),hn?(hn.setPanelOpen(!0),hn.element.style.display="none"):so&&(so.style.display="none")):(a?a&&(se==="overlay"||se==="push")&&!O?(ot.style.removeProperty("display"),ot.style.display="flex",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.setProperty("display","none","important"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.display="",ot.classList.add("persona-pointer-events-none","persona-opacity-0"),Ve.classList.remove("persona-scale-100","persona-opacity-100"),Ve.classList.add("persona-scale-95","persona-opacity-0")),hn?(hn.setPanelOpen(!1),hn.element.style.display=a?"none":""):so&&(so.style.display=a?"none":""))},Yt=(a,u="user")=>{if(!Se()||U===a)return;let y=U;U=a,hl();let M=(()=>{let O=o.launcher?.sidebarMode??!1,se=e.ownerDocument.defaultView??window,ge=o.launcher?.mobileFullscreen??!0,ce=o.launcher?.mobileBreakpoint??640,be=se.innerWidth<=ce,Ce=un(o)&&ge&&be,Ae=Pe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return O||ge&&be&&ve||Ce||Ae})();if(U&&M){if(!lr){let O=e.getRootNode(),se=O instanceof ShadowRoot?O.host:e.closest(".persona-host");se&&(lr=Lh(se,o.launcher?.zIndex??Jn))}cr||(cr=Ph(e.ownerDocument))}else U||(lr?.(),lr=null,cr?.(),cr=null);U&&(Sl(),Yf()||(Gn()==="follow"?hs(!0):Gf()));let H={open:U,source:u,timestamp:Date.now()};U&&!y?L.emit("widget:opened",H):!U&&y&&L.emit("widget:closed",H),L.emit("widget:state",{open:U,launcherEnabled:ve,voiceActive:vt.active,streaming:V.isStreaming()})},ys={inputDisabled:!1,sendDisabled:!1},pr=()=>ys.inputDisabled,Jf=()=>no(o.voiceRecognition?.provider)&&!!V&&(V.isBargeInActive()||["listening","processing","speaking"].includes(V.getVoiceStatus())),ui=()=>ys.inputDisabled||ys.sendDisabled,nk=()=>(ys.inputDisabled?ys.inputReason:void 0)??(ys.sendDisabled?ys.sendReason:void 0);function Zf(){if(!ze)return;if(Oe.getState().phase==="streaming"){ze.disabled=!1;return}let a=ut?!ut.isReady():!1;ze.disabled=ui()||a}function Cd(){if(!ro)return;let a=Oe.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;ro.toggleAttribute("data-persona-send-hidden",u)}function ok(){let a=nk();if(Pe()){let u=Pn??gt;a?u.setAttribute("title",a):u.removeAttribute("title"),gt.toggleAttribute(Ja,!!a);return}if(a){Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.setAttribute(Ja,""),Mt.removeAttribute(qc),Mt.textContent=a,xi(Mt,o.statusIndicator??{},"idle");return}if(Mt.hasAttribute(Ja)&&(Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),Mt.removeAttribute(Ja),g)){let u=V.getStatus();Tr(Mt,oo(u),o.statusIndicator??{},u)}}function em(){let a=Sg(o.composer?.inputDisabled),u=Sg(o.composer?.sendDisabled);ys={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},Oe.setInputDisabled(a.disabled),Oe.setSendDisabled(u.disabled);let y=Oe.getState().phase==="streaming",M=a.disabled,H=y||M;we&&(we instanceof HTMLTextAreaElement?we.disabled=M:we.setAttribute("contenteditable",M?"false":"true"),we.setAttribute("aria-disabled",M?"true":"false")),Zt&&(Zt.disabled=M),Gt&&(Gt.disabled=M);for(let O of Rt?.affordanceButtons??[])O.querySelectorAll("button").forEach(se=>{se.disabled=M});De&&(De.disabled=M||y&&!Jf()),Zs.forEach(O=>{O.elements.forEach(se=>{se.toggleAttribute("data-disabled",H),se instanceof HTMLButtonElement||se.setAttribute("aria-disabled",H?"true":"false")}),O.buttons.forEach(se=>{se.disabled=H})}),im.forEach(O=>{O.toggleAttribute("data-disabled",H),O instanceof HTMLButtonElement?O.disabled=H:O.setAttribute("aria-disabled",H?"true":"false"),O.querySelectorAll("button").forEach(se=>{se.disabled=H})}),gt.dataset.personaComposerStreaming=y?"true":"false",gt.dataset.personaComposerInputDisabled=M?"true":"false",gt.dataset.personaComposerSendDisabled=ui()?"true":"false",gt.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(O=>{(O instanceof HTMLButtonElement||O instanceof HTMLInputElement||O instanceof HTMLTextAreaElement||O instanceof HTMLSelectElement)&&(O.disabled=y)}),Zf(),ok()}let yl=a=>{Oe.setStreaming(a),Kc(a?"stop":"send"),em()},wd=()=>{vt.active||we&&we.focus()};L.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>wd(),200)});let av=null,tm=!1,nm=!$.hidden,bs=null,om=!J,xd=null;Ue.push(()=>{xd?.cancel(),xd=null});let rk=a=>{let u=OM(a);if(u===Q)return;Q=u,e.setAttribute("data-persona-conversation-state",u);let y=Le();on(),om&&(xd?.cancel(),xd=DM(gt,u==="active"?y:Le(),u==="active"?"drop":"rise",B().layout==="centered"?320:260)),ia()},lv=null,cv,dv=null,la=null,rm=!1,bl=a=>{let u=B(),y=`${u.variant}|${u.layout}|${u.dismiss}|${u.anchor??"bottom"}|${u.align??""}|${u.iconPlacement}|${u.kicker??""}|${u.title}|${u.subtitle}`;(y!==lv||u.icon!==cv)&&(lv=y,cv=u.icon,qu({host:$,iconHolder:me,kicker:ft,title:pt,subtitle:An,starterSuggestions:uo},u));let M=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;M!==dv&&(dv=M,ju(Ne,u.message,o));let H=a??(V?V.getMessages():o.initialMessages);rk(H);let O=tm,se=!O&&Ua(u,H),ge=se!==nm;if(nm=se,la){bs?.cancel(),bs=null,O!==rm&&(rm=O,O?$h(ye,$,null):Vh(ye,$,la)),$a(ye,$,!O);return}if(ge&&!se&&!O&&u.dismiss==="on-first-message"&&om){bs=BM($,be=>{bs===be&&(bs=null),!nm&&!la&&($a(ye,$,!1),ia()),be?.cancel()});return}if(bs){if(!se&&!O)return;bs.cancel(),bs=null}let ce=!$.hidden;$a(ye,$,se),!se&&ce&&ia()},sm=[],im=[],am=!1,pv=null,uv,fv=()=>{im.length=0;let a=sm.splice(0,sm.length);for(let u of a)try{u()}catch(y){console.warn("[persona] renderWelcome cleanup threw",y)}};Ue.push(fv);let sk=(a,u)=>{let y=Hh(a,u);if(!y)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let M=o.suggestions?.starters,H=Rh({item:{...y,behavior:y.behavior??M?.behavior??"send"},index:u,surface:"starter",source:"config",variant:M?.variant??"card",streaming:g?V.isStreaming():!1,config:o,plugins:p,chipsConfig:o.suggestionChipsConfig,session:V,getTextarea:()=>we,eventTarget:$,submitPrompt:Id});return im.push(H),H},lm=()=>{if(am)return;am=!0;let a=B();pv=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,uv=a.icon;try{fv(),$h(ye,$,la),la=null,rm=!1;let u=V?V.getMessages():o.initialMessages,y=Ua(a,u),M=0,H=null;for(let O of p)if(O.renderWelcome&&(H=O.renderWelcome({config:a,variant:a.variant,visible:y,defaultRenderer:()=>$,sendMessage:se=>{if(!V||V.isStreaming())return;let ge=se.trim();ge&&V.sendMessage(ge)},requestRender:()=>lm(),renderStarter:se=>sk(se,M++),storage:h(O.id),onCleanup:se=>{sm.push(se)}}),H))break;H&&H!==$&&(la=H,Vh(ye,$,H))}finally{am=!1}bl()},ik=()=>{let a=B();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===pv&&a.icon===uv||lm()},Sd=()=>{bl(),Qi||(we.placeholder=hA(Oe.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(ze.textContent=o.copy?.sendButtonLabel??"Send")),we.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',we.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},ak=!!o.setStoredConversationId,ca=a=>Te(u=>{let y={...u};return delete y[a],y}),Ad=a=>{let u=I[a];return typeof u=="string"?u:null},mv=()=>{let a=I.durableResume;if(!a||typeof a!="object")return null;let u=a;return typeof u.executionId=="string"&&u.executionId.length>0&&typeof u.after=="string"&&u.after.length>0?{executionId:u.executionId,after:u.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:a=>{Te(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ca("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{Te(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ca("conversationId"))});let gv=()=>o.clientToken??null,hv=a=>vE(a,Tt(),o.persistState===!1),yv=gv(),Ho=yv?hv(yv):null,lk=()=>{let a=I.pendingDisplayProjections;if(!a||typeof a!="object")return null;let u=a;return typeof u.conversationId!="string"||!Array.isArray(u.messageIds)?null:{conversationId:u.conversationId,messageIds:u.messageIds.filter(y=>typeof y=="string")}},vs={...Ho?{visitorStore:Ho}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!hf()?Promise.all([j,K]).then(()=>{}):j,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){ca("historyMessageCursor");return}Te(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:lk,setPendingDisplayProjections:a=>{if(!a){ca("pendingDisplayProjections");return}Te(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:mv,setStoredResumableHandle:a=>{if(!a){ca("durableResume");return}Te(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>P&&mv()!==null,...ak?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){ca("conversationRevision");return}Te(u=>({...u,conversationRevision:a}))}}};if(P){let a=o.onExecutionState,u=e.ownerDocument.defaultView,y=!1,M=()=>y=!0,H=()=>y=!1;u?.addEventListener("pagehide",M),u?.addEventListener("pageshow",H),Ue.push(()=>{u?.removeEventListener("pagehide",M),u?.removeEventListener("pageshow",H)}),o={...o,reconnectStream:o.reconnectStream??(O=>V.getClient().reconnectClientTokenStream(O)),onExecutionState:O=>{(O||!y)&&vs.setStoredResumableHandle?.(O?{executionId:O.executionId,after:O.lastEventId}:null),a?.(O)}}}let ck=()=>{let a=gv();if(a&&Ho?.matches(a,Tt(),o.persistState===!1)||!a&&!Ho)return;Ho?.destroy(),Ho=a?hv(a):null;let u={...vs};Ho?u.visitorStore=Ho:delete u.visitorStore,vs=u,V.setHistoryInternals(vs)},fi=null,dk=()=>{fi==null&&(fi=setInterval(()=>{let a=$e.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(fi),fi=null;return}let u=Date.now();a.forEach(y=>{let M=Number(y.getAttribute("data-tool-elapsed"));M&&(y.textContent=y.closest(".persona-activity-row")?Pl(u-M):dp(u-M))})},100))},cm=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((se,ge)=>cm(se,u[ge]));let y=a,M=u,H=Object.keys(y),O=Object.keys(M);return H.length===O.length&&H.every(se=>Object.prototype.hasOwnProperty.call(M,se)&&cm(y[se],M[se]))},bv=a=>{let{content:u,rawContent:y,llmContent:M,...H}=a;return H},dm=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Gy(a),pk=(a,u,y)=>{if(a.length!==u.length)return!1;let M=a[y.index],H=u[y.index];return!M||!H||M.id!==y.id||H.id!==y.id?!1:(!Object.is(M.content,H.content)||!Object.is(M.rawContent,H.rawContent)||!Object.is(M.llmContent,H.llmContent))&&dm(M)&&dm(H)&&cm(bv(M),bv(H))},Md=null,da=null,mi=null,_r=null,pm=null,uk=a=>{if(!P)return na(a);pm=a,queueMicrotask(()=>{pm===a&&(pm=null,na(a))})},Td=a=>{Md=a;let u,y;da=null;for(let H=a.length-1;H>=0;H-=1){let O=a[H];if(!u&&O.role==="user"&&(u=O),!y&&O.role==="assistant"&&(y=O),!da&&dm(O)&&(da={index:H,id:O.id}),u&&y&&da)break}Io($e,a,Z),ts()?.updateInlineArtifactBlocks($e,Lo.artifacts,{suppressTransition:xo}),dk(),bl(a),ni(a),hs(!xo),X0(a),a.length===0&&(pi(),dl=!0,cd=!1,ta=null,dd=!1),!Nf||ea?(Nf=!0,li=u?.id??null,Ff=y?.id??null):u&&u.id!==li?(li=u.id,q0(u.id)):y&&y.id!==Ff&&j0(),y&&(Ff=y.id),Y0(a);let M=vt.lastUserMessageId;u&&u.id!==M&&(vt.lastUserMessageId=u.id,L.emit("user:message",u)),vt.lastUserMessageWasVoice=!!u?.viaVoice,uk(a),aa()},um=()=>{_r!==null&&(cancelAnimationFrame(_r),_r=null);let a=mi;mi=null,a&&Td(a)},vv=()=>{_r!==null&&cancelAnimationFrame(_r),_r=null,mi=null},fk=a=>{let u=mi??Md;if(xo&&u&&da&&pk(u,a,da)){mi=a,_r===null&&(_r=requestAnimationFrame(()=>{_r=null;let y=mi;mi=null,y&&Td(y)}));return}if(a.length===0){vv(),Td(a);return}um(),Td(a)};V=new hu(o,{onMessagesChanged(a){fk(a)},onStatusChanged(a){let u=o.statusIndicator??{};Tr(Mt,(M=>M==="idle"?u.idleText??Cn.idle:M==="connecting"?u.connectingText??Cn.connecting:M==="connected"?u.connectedText??Cn.connected:M==="error"?u.errorText??Cn.error:M==="paused"?u.pausedText??Cn.paused:M==="resuming"?u.resumingText??Cn.resuming:Cn[M])(a),u,a),Zn()},onStreamingChanged(a){a||(V?.getMessages().length===0?vv():um()),xo=a,yl(a),Zn(),V&&Io($e,V.getMessages(),Z),a||(hs(!0),U0(),$b=!0,V&&Ub(V.getMessages(),Hs(o))),Xn(),Xs(a?"Responding\u2026":"Response complete."),aa()},onVoiceStatusChanged(a){if(L.emit("voice:status",{status:a,timestamp:Date.now()}),a!=="disconnected"&&!no(o.voiceRecognition?.provider))return;let u=V.getVoiceNotice();switch(u&&Pd(u,1e4),a){case"listening":if(!$f){let y=V.getVoiceDisclosure();y&&($f=!0,Pe()?(pd=we.placeholder,we.placeholder=y,Xs(y)):Pd(y,1e4))}Fr(),ma();break;case"processing":Fr(),Dk();break;case"speaking":Fr(),_k();break;default:a==="idle"&&V.isBargeInActive()?(Fr(),ma(),De?.setAttribute("aria-label","End voice session")):(vt.active=!1,$f=!1,pd!==null&&(we.placeholder=pd,pd=null),Fr(),Br("system"),Kb||yo());break}},onArtifactsState(a){Lo=a,a.artifacts.length===0&&(Ji=!1),ts()?.updateInlineArtifactBlocks($e,a.artifacts,{suppressTransition:xo}),Yo(),na()},onHistoryStateChanged(a){Kt(a)},onHistoryNotice(a){gn(a)},onReconnect(a){let{executionId:u,lastEventId:y}=a.handle;a.phase==="paused"?L.emit("stream:paused",{executionId:u,after:y}):a.phase==="resuming"?L.emit("stream:resuming",{executionId:u,after:y,attempt:a.attempt??1}):L.emit("stream:resumed",{executionId:u,after:y})}},vs),Po.current=V,Ue.push(()=>V.cancel()),Ue.push(()=>{V.destroy(),Ho?.destroy(),Ho=null});let fm=null;if(V.onReadAloudChange((a,u)=>{yb=a,bb=u,vb();let y=a??fm;a&&(fm=a);let M=y?V.getMessages().find(H=>H.id===y)??null:null;L.emit("message:read-aloud",{messageId:y,message:M,state:u,timestamp:Date.now()}),u==="idle"&&(fm=null)}),g=!0,Nf=!0,o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider))try{V.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let sn=null,mm=null,Cv=!1,wv=V.getHistoryState(),vl=()=>o.features?.history?.enabled===!0,xv=a=>{a&&(qo.textContent="",qo.textContent=a)},gm=()=>{m.forEach(y=>y()),m=[];let a=sn,u=a?.railCollapseShortcut();a&&u&&m.push(f.register({id:"history-rail-collapse",combo:u.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ot&&mt==="rail"&&a.railCollapsible()||a.railTriggerApplies(),run:()=>a.railOverlayMode()?a.toggleRailPinned():a.toggleRailCollapsed()}));for(let y of o.layout?.header?.trailingActions??[])y.shortcut&&m.push(f.register({id:`header-action-${y.id}`,combo:y.shortcut,run:()=>{let M=e.querySelector(`[data-persona-header-action="${y.id}"]`);M?M.click():o.layout?.header?.onAction?.(y.id)}}));for(let y of p)for(let M of y.shortcuts??[])m.push(f.register({...M,id:`${y.id}:${M.id}`}))};gm();let Ed=null,Sv=!1,Cl=()=>{if(!mo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&Ed?.trim()||null;mo.textContent=u??o.launcher?.title??"Chat Assistant";let y=mo.closest(".persona-combo-btn");if(!y)return;let M=!a||V.getActiveConversationId()!==null;y.setAttribute("data-persona-menu-locked",M?"false":"true"),y.setAttribute("aria-haspopup",M?"true":"false"),M||y.setAttribute("aria-expanded","false"),y.style.cursor=M?"pointer":"default";let H=y.querySelector("svg");H&&(H.style.display=M?"":"none")},mk=a=>{a!==Ed&&(Ed=a,Cl())},gk=a=>{Sv=a?.starred===!0,mk(a&&a.title.trim()||null),Cl()};Cl(),Be.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,y=V.getActiveConversationId();y&&(u==="delete"?ur(M=>M.requestDeleteConversation(y)):u==="star"&&V.canUpdateConversations()&&ur(M=>M.updateHistoryConversation(y,{starred:!Sv})).catch(()=>{}))}),Kt=a=>{wv=a,sn?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),yl(a.sendBlocked||xo),sn?.syncEarlierMessagesPill()},gn=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(Yn.clear(),pi(),dr()),xv(a.message),sn?.historySurface?.view.refresh()};let hk={get actionManager(){return ke},get activeConversationTitle(){return Ed},announceHistory:xv,get applyRailChrome(){return St},set applyRailChrome(a){St=a},get artifactSplitRoot(){return Ir},get body(){return ye},get config(){return o},get container(){return Be},get conversationOpenPendingEl(){return av},set conversationOpenPendingEl(a){av=a},get conversationOpenTakeover(){return tm},set conversationOpenTakeover(a){tm=a},currentKeyPrefix:Tt,destroyCallbacks:Ue,eventBus:L,get footer(){return gt},get header(){return Vt},get historyChromeSync(){return Zn},set historyChromeSync(a){Zn=a},historyFeatureEnabled:vl,get historyInternals(){return vs},set historyInternals(a){vs=a},get historyPresentation(){return mt},set historyPresentation(a){mt=a},get historySessionState(){return wv},get historyVisible(){return Ot},set historyVisible(a){Ot=a},get isStreaming(){return xo},jumpToBottomInstant:Gf,get lastAppliedMessages(){return Md},set lastAppliedMessages(a){Md=a},get launcherEnabled(){return ve},get launcherSurfaceInstance(){return hn},maybeFocusInput:wd,messageCache:Yn,get messagesWrapper(){return $e},mount:e,get open(){return U},panel:Ve,panelElements:wt,get persistentMetadata(){return I},set persistentMetadata(a){I=a},plugins:p,get reapplyHistoryHostChrome(){return Ht},set reapplyHistoryHostChrome(a){Ht=a},repinAnchoredMessage:ia,resetAnchorState:pi,restoreScrollPosition:Yf,resumeAutoScroll:dr,runStorageMutation:fd,get session(){return V},setActiveConversationSummary:gk,storageAdapter:x,get suppressScrollSend(){return ea},set suppressScrollSend(a){ea=a},syncScrollToBottomButton:Xn,updateWelcome:bl,getHistoryProviderFactory:YE,historyErrors:{HistoryClientError:kn,HistoryProviderError:Li},isDockedMountMode:un,renderLucideIcon:We,loadHistoryView:NE,createHeaderIconButton:Na,attachTooltip:$n},hm=a=>(!sn&&!Cv&&(sn=a.createHistoryShell(hk),sn.railCollapseShortcut()&&gm()),sn),ym=()=>{if(sn)return Promise.resolve(sn);let a=hf();return a?Promise.resolve(hm(a)):(mm??=GE().then(hm,u=>{throw mm=null,u}),mm)},ur=a=>{let u=hf(),y=sn??(u?hm(u):null);return y?a(y):ym().then(M=>{if(!M)throw new Error("[AgentWidget] The widget was destroyed");return a(M)})},kd=()=>{sn?.syncHistoryPresentation()};Ue.push(()=>{Cv=!0}),vl()&&ym().catch(()=>{}).finally(te),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&V.initClientSession().then(()=>{let a=sn;if(a?.historyAvailable())return V.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{sn?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let bm=()=>V.warmClientSession(),Av=a=>{let u=o.sessionInit??"input",y=Bt?.input??we,M=a.target;y&&(a.type==="input"?(u==="input"||u==="focus")&&M===y&&a.inputType&&y.value.trim():u==="focus"&&(a.type==="keyup"?M===y&&a.key==="Tab":(Bt?.form??Pn)?.contains(M)))&&bm()},Mv=["input","pointerdown","keyup"];Mv.forEach(a=>e.addEventListener(a,Av));let Tv,vm,Ev=()=>{let a=vm;vm=void 0;try{typeof a=="function"&&a()}catch{}},kv=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==Tv){Ev(),Tv=a;try{vm=a?.({warm:bm,mount:e})}catch{}}};kv(),Ue.push(()=>{Mv.forEach(a=>e.removeEventListener(a,Av)),Ev()}),(Ie||o.onSSEEvent)&&V.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),wn(a,u)});let Lv=()=>{let a=o.resume??(P?vs.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(a)};J?J.then(a=>{if(a){if(a.metadata&&(I=Yy(a.metadata),ke.syncFromMetadata()),a.messages?.length){ea=!0;try{V.hydrateMessages(a.messages)}finally{ea=!1}vd()}a.artifacts?.length&&V.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),Qb(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{om=!0,_(),Lv()}):(Qb(X),Lv());let yk=()=>{!Pe()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Yt(!0,"auto")},bk=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[y,M]=await Promise.allSettled([a.finalize(),u.finalize()]),H=[];return y.status==="fulfilled"?H.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),M.status==="fulfilled"?H.push(M.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",M.reason),W_(H)}}:a:u,Cm=()=>{let u=we.getInlineMessageFields?.();return u&&u.contentSegments.some(M=>M.kind==="mention")?u.contentSegments:void 0},Or=!1,gi=null,Ld=()=>{we.value="",we.style.height="auto",ko(),xl()},pa=null;function Pd(a,u=4e3){Xs(a),!(Pe()||!Mt)&&(Mt.hasAttribute(Ja)||(Mt.setAttribute(qc,""),Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.textContent=a,xi(Mt,o.statusIndicator??{},"idle"),pa&&clearTimeout(pa),pa=setTimeout(()=>{if(pa=null,!!Mt?.hasAttribute(qc)&&(Mt.removeAttribute(qc),Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),g)){let y=V.getStatus();Tr(Mt,oo(y),o.statusIndicator??{},y)}},u)))}function vk(){let a=Oe.getState().pendingSubmission;a&&(Yi(void 0),we&&(we.value=a.text,we.dispatchEvent(new Event("input",{bubbles:!0})),ko()),a.options.selectedModelId&&(Oe.setSelectedModelId(a.options.selectedModelId),ls?.repaint()),a.options.activeModeIds?.length&&Xc(a.options.activeModeIds),a.options.quote&&ar(a.options.quote),we?.focus())}let Ck=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},Pv=(a={})=>{let u=(a.overrideText??we?.value??"").trim();return a.resolveInlineCommand&&u?(Rt?.takeInlineCommand(u)??Promise.resolve(null)).then(y=>Iv(a,u,y)):Iv(a,u,null)},Iv=(a,u,y)=>{if(y?.kind==="action"){Ld(),Rt?.clear(),kr();return}let M=y?.kind==="server"?y.mentions:null,H=y?.kind==="prompt"?y.sendText:u,O=a.pending?.contentParts,se=(ut?.hasAttachments()??!1)||(O?.length??0)>0;if(!kA({text:H,hasAttachments:se,attachmentsReady:ut?.isReady()??!0,hasMentions:Rt?.hasMentions()??!1,hasServerMentions:!!M,inputDisabled:pr(),sendDisabled:ui()}))return;let ge=V.isStreaming()?Sf():"block";if(ge==="defer-one"&&!a.pending){if(Oe.getState().pendingSubmission){Pd("One message is already queued. Edit or remove it first.");return}wk({intent:a,sendText:H,serverMentions:M});return}let ce={text:H,mentionRefs:[...Rt?.getMentionRefs()??[],...M?.refs??[]],contentSegments:y?.kind==="prompt"?void 0:Cm(),options:{...Oe.getState().selectedModelId&&{selectedModelId:Oe.getState().selectedModelId},...Oe.getState().activeModeIds.length>0&&{activeModeIds:[...Oe.getState().activeModeIds]},...Oe.getState().quote&&{quote:{...Oe.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(ce.options={...a.pending.options},ce.contentSegments=a.pending.contentSegments,ce.mentionRefs=[...a.pending.mentionRefs],ce.viaVoice=a.pending.viaVoice);let be=()=>{if(O?.length)return[...O];if(!ut?.hasAttachments())return;let Dt=[...ut.getContentParts()];return ce.text&&Dt.push(vr(ce.text)),Dt};ce.contentParts=be();let Ce=()=>{si(),yk();let Dt=Rt?.collectForSubmit()??null,bo=bk(Dt,M),an=be();a.consumeDraft!==!1&&Ld();let mn={selectedModelId:ce.options.selectedModelId,activeModeIds:ce.options.activeModeIds},io=ge==="interrupt";io&&V.cancel(),V.sendMessage(ce.text,{contentParts:an,mentions:bo??void 0,contentSegments:ce.contentSegments,viaVoice:ce.viaVoice,composerOptions:mn,...ce.options.quote&&{quote:ce.options.quote},...io&&{interrupt:!0}}),ut?.hasAttachments()&&ut.clearAttachments(),Dt&&Rt?.clear(),kr();let bn=Oe.getState().activeModeIds,zt=gA(bn,o.composer?.modes);zt.length!==bn.length&&Xc(zt),Oe.getState().quote&&ar(void 0),gd(),Lf.release(),Ko()},Ae=o.composer?.onBeforeSend;if(!Ae){Ce();return}let Ke=new AbortController;gi=Ke;let Pt=Dt=>{if(gi=null,Dt.status==="error"){Ck(Dt.error);return}Dt.status==="proceed"&&Ce()},Ft=LA(Ae,ce,Ke.signal);if(!(Ft instanceof Promise)){Pt(Ft);return}return Oe.setPreparing(!0),Ft.then(Pt).finally(()=>Oe.setPreparing(!1))};function wk(a){let u=Oe.getState(),y=ut?.hasAttachments()??!1,M=y?[...ut.getContentParts()]:[];y&&a.sendText&&M.push(vr(a.sendText));let H=fh({text:a.sendText,contentParts:M.length?M:void 0,mentionRefs:[...Rt?.getMentionRefs()??[],...a.serverMentions?.refs??[]],contentSegments:Cm(),options:{...u.selectedModelId&&{selectedModelId:u.selectedModelId},...u.activeModeIds.length>0&&{activeModeIds:[...u.activeModeIds]},...u.quote&&{quote:{...u.quote}}},viaVoice:a.intent.viaVoice});Yi(H),a.intent.consumeDraft!==!1&&Ld(),y&&ut.clearAttachments(),Rt?.clear(),kr(),u.quote&&ar(void 0),gd(),Lf.release(),Ko(),Xs("Message queued. It sends when the response finishes.")}function xk(){let a=Oe.getState().pendingSubmission;a&&(Yi(void 0),Hd(a.text,{consumeDraft:!1,pending:a}))}function Sk(a){if(o.messageActions?.showEdit!==!0)return;let u=V.getMessages().find(y=>y.id===a);!u||!Yg(u)||ri!==a&&(si(),ri=a,us=CA({messageId:a,initialText:u.content,onSave:y=>Ak(a,y),onCancel:()=>si()}),Yn.delete(a),Io($e,V.getMessages(),Z),us.focus())}function Ak(a,u){let y=us;if(ri=null,us=null,y?.destroy(),Yn.delete(a),!V.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){Io($e,V.getMessages(),Z);return}ia()}function Mk(a){if(V.isStreaming())return;let u=Gg(V.getMessages(),a);u&&(si(),V.resubmitFrom(u,{reason:"retry"})&&ia())}Qc={regenerate:Mk,edit:Sk,quote:a=>{let y=V.getMessages().find(M=>M.id===a)?.content?.trim();y&&(ar({text:y,messageId:a}),we?.focus())}};let wl=async a=>{if(!Or){Or=!0;try{await Pv({resolveInlineCommand:!0,...a})}finally{Or=!1}}};function Id(a){ui()||(Ld(),Hd(a,{consumeDraft:!1}))}let Hd=(a,u)=>{if(Or)return;Or=!0;let y=()=>{Or=!1};try{let M=Pv({...u,overrideText:a});M instanceof Promise?M.finally(y):y()}catch(M){throw y(),M}},Tk=a=>{if(a.preventDefault(),V.isStreaming()){V.cancel(),Re?.reset(),bt?.update();return}Or||wl()},Ek=()=>o.features?.composerHistory!==!1,wm={...wh},xm=!1,xl=()=>{wm={...wh}},kk=()=>V.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),Lk=a=>{if(!we)return;xm=!0,we.value=a,we.dispatchEvent(new Event("input",{bubbles:!0})),xm=!1;let u=we.value.length;we.setSelectionRange(u,u)},Pk=a=>{xm||(a.isComposing||Rt?.handleInput(a.inputType??void 0),xl())},Ik=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(we)}),Hk=a=>{if(we&&!pr()&&!(!a.isComposing&&Rt?.handleKeydown(a))){if(Ek()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=we.selectionStart===0&&we.selectionEnd===0,y=$A({direction:a.key==="ArrowUp"?"up":"down",history:kk(),currentValue:we.value,atStart:u,state:wm});if(wm=y.state,y.handled){a.preventDefault(),y.value!==void 0&&Lk(y.value);return}}if(Sx(a,Ik())){if(V.isStreaming()){if(a.preventDefault(),Sf()==="block"||Or||ui())return;xl(),wl();return}if(Or){a.preventDefault();return}if(ui()){a.preventDefault();return}xl(),a.preventDefault(),ze.click()}}},Hv=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(Be)){if(gi){gi.abort(),gi=null,a.preventDefault(),a.stopImmediatePropagation();return}V.isStreaming()&&(V.cancel(),Re?.reset(),bt?.update(),xl(),a.preventDefault(),a.stopImmediatePropagation())}},Rk=async a=>{if(o.attachments?.enabled!==!0||!ut||pr())return;let u=P_(a.clipboardData);u.length!==0&&(a.preventDefault(),await ut.handleFiles(u))},Ro=null,fr=!1,ua=null,Nr=null,Sm=()=>o.voiceRecognition?.completionBehavior==="review";function Rd(a){De?.setAttribute("data-state",a),a==="recording"?Bk():Em()}let Rv="--persona-voice-level",Am=.5,fa=null,Mm=-1,Wd=0,Wv=()=>{let a=[],u=Dn??De?.parentElement??null;return u&&a.push(u),gt&&a.push(gt),a},Tm=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==Mm){Mm=u;for(let y of Wv())y.style.setProperty(Rv,String(u))}},Wk=()=>{Mm=-1,Wd=0;for(let a of Wv())a.style.removeProperty(Rv)};function Bk(){if(fa!==null)return;if(typeof requestAnimationFrame!="function"){Tm(g?V.getVoiceLevel()??Am:Am);return}let a=()=>{fa=requestAnimationFrame(a);let u=g?V.getVoiceLevel():null;if(u===null){Tm(Am);return}Wd+=(u-Wd)*.3,Tm(Wd)};fa=requestAnimationFrame(a)}function Em(){fa!==null&&(cancelAnimationFrame(fa),fa=null),Wk()}let Bv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Bd=(a="user")=>{if(fr||V.isStreaming())return;let u=Bv();if(!u)return;Ro=new u;let y=o.voiceRecognition??{},M=y.pauseDuration??2e3;Ro.continuous=y.provider?.browser?.continuous??!0,Ro.interimResults=!0,Ro.lang=y.provider?.browser?.language??"en-US";let H=we.value;Ro.onresult=O=>{let se="",ge="";for(let be=0;be<O.results.length;be++){let Ce=O.results[be],Ae=Ce[0].transcript;Ce.isFinal?se+=Ae+" ":ge=Ae}let ce=H+se+ge;we.value=ce,ko(),ua&&clearTimeout(ua),(se||ge)&&(ua=window.setTimeout(()=>{if(we.value.trim()&&Ro&&fr){if(Cs(),Sm())return;wl({viaVoice:!0})}},M))},Ro.onerror=O=>{O.error!=="no-speech"&&Cs()},Ro.onend=()=>{if(fr){let O=we.value.trim();!Sm()&&O&&O!==H.trim()&&wl({viaVoice:!0}),Cs()}};try{if(Ro.start(),fr=!0,vt.active=!0,a!=="system"&&(vt.manuallyDeactivated=!1),Br(a),yo(),Ko(),De){let O=o.voiceRecognition??{};Nr={backgroundColor:De.style.backgroundColor,color:De.style.color,borderColor:De.style.borderColor,iconName:O.iconName??"mic",iconSize:parseFloat(O.iconSize??"")||Co};let se=O.recordingBackgroundColor,ge=O.recordingIconColor,ce=O.recordingBorderColor;if(De.classList.add("persona-voice-recording"),Rd("recording"),De.style.backgroundColor=se??"var(--persona-voice-recording-bg, #ef4444)",De.style.color=ge??"var(--persona-voice-recording-indicator, #ffffff)",ge){let be=De.querySelector("svg");be&&be.setAttribute("stroke",ge)}ce&&(De.style.borderColor=ce),De.setAttribute("aria-label","Stop voice recognition")}}catch{Cs("system")}},Cs=(a="user")=>{if(fr){if(fr=!1,ua&&(clearTimeout(ua),ua=null),Ro){try{Ro.stop()}catch{}Ro=null}if(vt.active=!1,Br(a),yo(),Ko(),De){if(De.classList.remove("persona-voice-recording"),Rd("idle"),Nr){De.style.backgroundColor=Nr.backgroundColor,De.style.color=Nr.color,De.style.borderColor=Nr.borderColor;let u=De.querySelector("svg");u&&u.setAttribute("stroke",Nr.color||"currentColor"),Nr=null}De.setAttribute("aria-label","Start voice recognition")}}},Dv=null,Dd=a=>{let u=M=>{Dv??=M.createMicStateStyles({mic:()=>De,config:()=>o,session:()=>V,get original(){return Nr},set original(H){Nr=H},setMicState:Rd,renderIcon:We,iconFallbackPx:Co}),a(Dv)},y=NS();y?u(y):oc().then(u,()=>{})},ma=()=>Dd(a=>a.recording()),Dk=()=>Dd(a=>a.processing()),_k=()=>Dd(a=>a.speaking()),Fr=()=>Dd(a=>a.reset()),km=()=>{if(!pr()){if(no(o.voiceRecognition?.provider)){let a=V.getVoiceStatus(),u=V.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,yo(),Br("user"),Fr()});return}V.toggleVoice().then(()=>{vt.active=Uf(),vt.manuallyDeactivated=!vt.active,yo(),Br("user"),vt.active?ma():Fr()});return}if(fr){let a=we.value.trim();vt.manuallyDeactivated=!0,yo(),Cs("user"),a&&!Sm()&&wl()}else vt.manuallyDeactivated=!1,yo(),Bd("user")}};Af=km;let _v=()=>V.prewarmVoice(),Ov=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Nv=a=>{Ov()==="hover"&&De?.contains(a.target)&&_v()},Fv=["pointerover","pointerdown","focusin"];Fv.forEach(a=>e.addEventListener(a,Nv));let Vv,$v=null,Lm,Uv=()=>{let a=Lm;Lm=void 0;try{typeof a=="function"&&a()}catch{}},Pm=()=>{let a=Ov(),u=typeof a=="function"&&De?a:void 0,y=u?De:null;if(!(u===Vv&&y===$v)&&(Uv(),Vv=u,$v=y,!(!u||!y)))try{Lm=u({warm:_v,micButton:y,mount:e})}catch{}};Pm(),Ue.push(()=>{Fv.forEach(a=>e.removeEventListener(a,Nv)),Uv()}),De&&Ue.push(()=>{no(o.voiceRecognition?.provider)?(V.isVoiceActive()&&V.toggleVoice(),Fr()):Cs("system")});let Ok=L.on("assistant:complete",()=>{Oe.getState().pendingSubmission&&setTimeout(()=>{V.isStreaming()||xk()},0)});Ue.push(Ok);let Nk=L.on("assistant:complete",()=>{jb&&(vt.active||vt.manuallyDeactivated||jb==="assistant"&&!vt.lastUserMessageWasVoice||setTimeout(()=>{!vt.active&&!vt.manuallyDeactivated&&(no(o.voiceRecognition?.provider)?V.toggleVoice().then(()=>{vt.active=V.isVoiceActive(),Br("auto"),V.isVoiceActive()&&ma()}):Bd("auto"))},600))});Ue.push(Nk);let Fk=L.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});Ue.push(Fk);let zv=()=>{Yt(!U,"user")},hn=null,so=null;if(ve&&!Pe()){let{instance:a,element:u}=Gh({config:o,plugins:p,onToggle:zv});hn=a,a||(so=u)}hn?e.appendChild(hn.element):so&&e.appendChild(so),hl(),ni(),Sd(),lm(),yl(V.isStreaming()),Yf()||(Gn()==="follow"?hs(!0):Gf()),_0(),xt&&(!ve||Pe()?setTimeout(()=>wd(),0):U&&setTimeout(()=>wd(),200));let ws=null,qv=()=>{ws&&(ws.disconnect(),ws.observe(gt),ws.observe(Be),ws.observe($))},jv=go(),Sl=()=>{if(Pe()){Xe(),hl();return}let a=un(o),u=o.launcher?.sidebarMode??!1,y=e.ownerDocument.defaultView??window,M=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640,O=y.innerWidth<=H,se=M&&O&&ve;try{if(se){Qs(),il=id();return}let ge=!1;dt&&(dt=!1,Qs(),ge=!0);let ce=id();if(!ge&&ce!==il&&(Qs(),ge=!0),il=ce,ge&&nd(),!ve&&!a){Ve.style.height="",Ve.style.width="";return}if(!u&&!a){let be=Wi(o);Ve.style.width=be.width,Ve.style.maxWidth=be.maxWidth}sd(),Pb()}finally{Xe(),on();let ge=go();if(ge!==jv&&(jv=ge,bl(),ni()),hl(),U&&ve){let be=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Ce=o.launcher?.sidebarMode??!1,Ae=o.launcher?.mobileFullscreen??!0,Ke=un(o)&&Ae&&be,Pt=Ce||Ae&&be&&ve||Ke;if(Pt&&!cr){let Ft=e.getRootNode(),Dt=Ft instanceof ShadowRoot?Ft.host:e.closest(".persona-host");Dt&&!lr&&(lr=Lh(Dt,o.launcher?.zIndex??Jn)),cr=Ph(e.ownerDocument)}else Pt||(lr?.(),lr=null,cr?.(),cr=null)}}};Sl();let _d=e.ownerDocument.defaultView??window;if(_d.addEventListener("resize",Sl),Ue.push(()=>_d.removeEventListener("resize",Sl)),typeof ResizeObserver<"u"){ws=new ResizeObserver(()=>{on()}),qv(),Ue.push(()=>{ws?.disconnect(),ws=null});let a=new ResizeObserver(()=>{kd()});a.observe(Be),Ue.push(()=>a.disconnect())}_d.addEventListener("resize",kd),Ue.push(()=>_d.removeEventListener("resize",kd)),Ao=ye.scrollTop;let Kv=xr(ye),Gv=()=>{Lb();let a=ye.scrollTop,u=xr(ye),y=u<Kv;if(Kv=u,!zo()){Ao=a,Xn();return}let{action:M,nextLastScrollTop:H}=Ru({following:So.isFollowing(),currentScrollTop:a,lastScrollTop:Ao,nearBottom:Zr(ye,Rr),userScrollThreshold:R0,isAutoScrolling:ho||ld||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Ao=H,M==="resume"){hd()||dr();return}M==="pause"&&sa()};if(ye.addEventListener("scroll",Gv,{passive:!0}),Ue.push(()=>ye.removeEventListener("scroll",Gv)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{z0(),tg($e)});a.observe($e),a.observe(ye),Ue.push(()=>a.disconnect())}let Yv=()=>{zo()&&So.isFollowing()&&hd()&&sa()},Xv=ye.ownerDocument;Xv.addEventListener("selectionchange",Yv),Ue.push(()=>{Xv.removeEventListener("selectionchange",Yv)});let Vk=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Qv=a=>{Vk.has(a.key)&&(gs(),el()&&zo()&&So.isFollowing()&&sa())},Jv=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(gs(),el()&&zo()&&So.isFollowing()&&sa())};ye.addEventListener("keydown",Qv),ye.addEventListener("focusin",Jv),Ue.push(()=>{ye.removeEventListener("keydown",Qv),ye.removeEventListener("focusin",Jv)});let Zv=a=>{if(a.deltaY!==0&&gs(),!zo())return;let u=Wu({following:So.isFollowing(),deltaY:a.deltaY,nearBottom:Zr(ye,Rr),resumeWhenNearBottom:!0});u==="pause"?sa():u==="resume"&&!hd()&&dr()};ye.addEventListener("wheel",Zv,{passive:!0}),ye.addEventListener("touchmove",gs,{passive:!0}),ye.addEventListener("pointerdown",gs,{passive:!0}),Ue.push(()=>{ye.removeEventListener("touchmove",gs),ye.removeEventListener("pointerdown",gs)}),Ue.push(()=>ye.removeEventListener("wheel",Zv)),fn.addEventListener("click",()=>{pi(),ye.scrollTop=ye.scrollHeight,Ao=ye.scrollTop,dr(),hs(!0),Xn()}),Ue.push(()=>fn.remove()),Ue.push(()=>{Zb(),pi()});let eC=()=>{Ze&&(ei&&(Ze.removeEventListener("click",ei),ei=null),Se()?(Ze.style.display="",ei=()=>{Yt(!1,"user")},Ze.addEventListener("click",ei)):Ze.style.display="none")};eC(),(()=>{let{clearChatButton:a}=wt;a&&a.addEventListener("click",()=>{let u=sn;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(M=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",M)});return}V.clearMessages(),o.layout?.topFade&&(ye.scrollTop=0),ye.removeAttribute("data-persona-top-fade"),Yn.clear(),dr(),Ei(wt.composerOverlay);try{localStorage.removeItem(Qa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qa}`)}catch(M){console.error("[AgentWidget] Failed to clear default localStorage:",M)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(M){console.error("[AgentWidget] Failed to clear custom localStorage:",M)}let y=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(y),x?.clear&&fd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},ke.syncFromMetadata(),ut?.clearAttachments(),gd(),Yi(void 0),ar(void 0),si(),ee?.clear(),Re?.reset(),bt?.update()})})();let tC=[["keydown",Hk],["input",Pk],["input",ko],["input",kr],["keyup",kr],["paste",Rk],["focus",w0]],nC=a=>{if(a)for(let[u,y]of tC)Bt?.addListener(a,u,y)},$k=a=>{if(a)for(let[u,y]of tC)Bt?.removeListener(a,u,y)},oC=()=>{Bt&&(Bt.addListener(Bt.form,"submit",Tk),Bt.addListener(Bt.footer,"click",kr),nC(we),De&&Bt.addListener(De,"click",km),Pm())};oC();let rC=()=>{Rt?.onComposerSwap((a,u)=>{$k(u),we=a,Bt&&(Bt.input=a),nC(a),Tf(),em(),ko()})};rC();let Im=!1;function sC(){if(!Im){Im=!0;try{let a=we?.value??"",u=gt.ownerDocument??document,y=we?u.activeElement===we:!1;Em(),Bt?.destroy(),Bt=null,Rt?.destroy(),Rt=null;let M=null,H=()=>(M=Pe()?$u({config:o}):Ac({config:o}),M.footer),O=lb(H)??H();At.replaceComposer(O),gt=At.composer.footer;let se=M!==null&&O===M.footer;Qi=!se,Kc=se?M.setSendButtonMode:()=>{},ab(gt),db(gt),pb(),ub(),Ef(),rC(),fb(),kf(),mb(),oC();let ge=Zs.indexOf(Hr);if(Hr.destroy(),Hr=wc(eo),ge>=0&&(Zs[ge]=Hr),we&&(we.value=a),ko(),kr(),Sd(),ni(),yl(V.isStreaming()),o.statusIndicator?.mode==="transient"&&!Pe()){let ce=V.getStatus();Tr(Mt,oo(ce),o.statusIndicator,ce)}vt.active&&Rd("recording"),Qs(),qv(),Xe(),Ko(),Cd(),y&&we?.focus()}finally{Im=!1}}}let Al=e.ownerDocument??document;Al.addEventListener("keydown",Hv,!0);let iC=()=>{zf()},aC=()=>{Al.visibilityState==="hidden"&&zf()};typeof window<"u"&&(window.addEventListener("pagehide",iC),Al.addEventListener("visibilitychange",aC),Ue.push(()=>{window.removeEventListener("pagehide",iC),Al.removeEventListener("visibilitychange",aC)}));let lC="persona-attachment-drop-active",Ml=0,Hm=()=>{Ml=0,Be.classList.remove(lC)},ga=()=>o.attachments?.enabled===!0&&ut!==null&&!pr(),cC=a=>{!yf(a.dataTransfer)||!ga()||(Ml++,Ml===1&&Be.classList.add(lC))},dC=a=>{!yf(a.dataTransfer)||!ga()||(Ml--,Ml<=0&&Hm())},pC=a=>{!yf(a.dataTransfer)||!ga()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},uC=a=>{if(!yf(a.dataTransfer)||!ga())return;a.preventDefault(),a.stopPropagation(),Hm();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&ut.handleFiles(u)},xs=!0;Be.addEventListener("dragenter",cC,xs),Be.addEventListener("dragleave",dC,xs),e.addEventListener("dragover",pC,xs),e.addEventListener("drop",uC,xs);let Od=e.ownerDocument,fC=a=>{ga()&&a.preventDefault()},mC=a=>{ga()&&a.preventDefault()};Od.addEventListener("dragover",fC),Od.addEventListener("drop",mC),Ue.push(()=>{Bt?.destroy(),Bt=null,Em(),jo?.destroy(),jo=null,Lr?.destroy(),Lr=null,cs?.destroy(),cs=null,ds?.destroy(),ds=null,ls=null,xf=null,zf(),pl.destroy(),pa&&clearTimeout(pa),si(),gi?.abort(),gi=null,ut?.destroy(),ut=null,Oe.destroy(),Al.removeEventListener("keydown",Hv,!0),Rt?.destroy()}),Ue.push(()=>{Be.removeEventListener("dragenter",cC,xs),Be.removeEventListener("dragleave",dC,xs),e.removeEventListener("dragover",pC,xs),e.removeEventListener("drop",uC,xs),Od.removeEventListener("dragover",fC),Od.removeEventListener("drop",mC),Hm()}),Ue.push(()=>{V.cancel()}),hn?Ue.push(()=>{hn?.destroy()}):so&&Ue.push(()=>{so?.remove()});let yn={update(a){let u=o.future?.v5Defaults===!0,y=o.toolCall,M=o.messageActions,H=o.layout?.messages,O=o.colorScheme,se=o.loadingIndicator,ge=o.iterationDisplay,ce=o.features?.showReasoning,be=o.features?.showToolCalls,Ce=o.features?.toolCallDisplay,Ae=o.features?.reasoningDisplay,Ke=o.features?.streamAnimation?.type,Pt=o.features?.history?.enabled===!0,Ft=o.features?.history?.provider,Dt=o.getIdentityProof,bo=o.clientToken,an=o.contextMentions;o=mE({...o,features:d},a),d=o.features,o=ky(o),c(),Bf(),lc(e,o),_c(e,o),Oc(e,o),St(),Yo(),o.colorScheme!==O&&Ib();let mn=Iy.getForInstance(o.plugins);p.length=0,p.push(...mn),gm(),ve=o.launcher?.enabled??!0,tt=o.launcher?.autoExpand??!1,le=o.features?.showReasoning??!0,Me=o.features?.showToolCalls??!0,_e=o.features?.scrollToBottom??{};let io=Gn();ct=o.features?.scrollBehavior??{},io!==Gn()&&(pi(),dr()),qb(),rn(),Xn();let bn=Ie;if(Ie=o.features?.showEventStreamToggle??!1,Ie&&!bn){if(ee||(nn(),V.setSSEEventCallback((pe,kt)=>{o.onSSEEvent?.(pe,kt),wn(pe,kt)})),!$t&&Vt){let pe=o.features?.eventStream?.classNames,kt="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"+(pe?.toggleButton?" "+pe.toggleButton:"");$t=v("button",kt),$t.style.width="28px",$t.style.height="28px",$t.style.color=lo.actionIconColor,$t.type="button",$t.setAttribute("aria-label","Event Stream"),$t.title="Event Stream";let Lt=Je(rs.Activity,"18px","currentColor",1.5);Lt&&$t.appendChild(Lt);let _t=wt.clearChatButtonWrapper,en=wt.closeButtonWrapper,Qn=_t||en;Qn&&Qn.parentNode===Vt?Vt.insertBefore($t,Qn):Vt.appendChild($t),$t.addEventListener("click",()=>{Ee?Xi():Mf()})}}else!Ie&&bn&&(Xi(),$t&&($t.remove(),$t=null),ee?.clear(),Ut?.destroy(),ee=null,Ut=null,Re?.reset(),Re=null,Fe=null);if(o.launcher?.enabled===!1&&hn&&(hn.destroy(),hn=null),o.launcher?.enabled===!1&&so&&(so.remove(),so=null),o.launcher?.enabled!==!1&&!hn&&!so){let{instance:pe,element:kt}=Gh({config:o,plugins:p,onToggle:zv});hn=pe,pe||(so=kt),e.appendChild(kt)}hn&&hn.update(o),Cl(),ir&&o.launcher?.subtitle!==void 0&&(ir.textContent=o.launcher.subtitle);let zt=o.layout?.header;if(zt?.layout!==Ye&&Vt){let pe=zt?Fu(o,zt,{showClose:Se(),onClose:()=>Yt(!1,"user")}):Ii({config:o,showClose:Se(),onClose:()=>Yt(!1,"user")});At.replaceHeader(pe),Vt=At.header.element,Nt=At.header.iconHolder,mo=At.header.headerTitle,ir=At.header.headerSubtitle,Ze=At.header.closeButton,Ye=zt?.layout,Cl()}else if(zt){if(Nt&&(Nt.style.display=zt.showIcon===!1?"none":""),mo&&(mo.style.display=zt.showTitle===!1?"none":""),ir&&(ir.style.display=zt.showSubtitle===!1?"none":""),Ze){let pe=Se()&&zt.showCloseButton!==!1;Ze.style.display=pe?"":"none"}if(wt.clearChatButtonWrapper){let pe=zt.showClearChat;if(pe!==void 0){wt.clearChatButtonWrapper.style.display=pe?"":"none";let{closeButtonWrapper:kt}=wt;kt&&!kt.classList.contains("persona-absolute")&&(pe?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}}let gr=o.layout?.showHeader!==!1;Vt&&(Vt.style.display=gr?"":"none");let Bo=o.layout?.showFooter!==!1;gt&&(gt.style.display=Bo?"":"none"),Xe(),Xn(),ve!==lt?ve?Yt(tt,"auto"):(U=!0,hl()):tt!==ht&&Yt(tt,"auto"),ht=tt,lt=ve,Sl(),eC();let hr=JSON.stringify(o.toolCall)!==JSON.stringify(y),Xo=JSON.stringify(o.messageActions)!==JSON.stringify(M),As=JSON.stringify(o.layout?.messages)!==JSON.stringify(H),Tl=o.loadingIndicator?.render!==se?.render||o.loadingIndicator?.renderIdle!==se?.renderIdle||o.loadingIndicator?.showBubble!==se?.showBubble,hi=o.iterationDisplay!==ge,q=(o.features?.showReasoning??!0)!==(ce??!0)||(o.features?.showToolCalls??!0)!==(be??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(Ae);(o.future?.v5Defaults===!0!==u||hr||Xo||As||Tl||hi||q)&&V&&(ii++,Io($e,V.getMessages(),Z));let st=o.features?.streamAnimation?.type;if(st!==Ke&&st&&st!=="none"){let pe=Of(st,o.features?.streamAnimation?.plugins);pe&&gc(pe,e)}let he=o.launcher??{},qt=he.headerIconHidden??!1,Sn=o.layout?.header?.showIcon,to=qt||Sn===!1,On=he.headerIconName,Xt=he.headerIconSize??Ll;if(Nt){let pe=Vt,kt=pe?.querySelector(".persona-flex-col");if(to)Nt.style.display="none",pe&&kt&&!pe.contains(kt)&&pe.insertBefore(kt,pe.firstChild);else{if(Nt.style.display="",Nt.style.height=Xt,Nt.style.width=Xt,pe&&kt&&(pe.contains(Nt)?Nt.nextSibling!==kt&&(Nt.remove(),pe.insertBefore(Nt,kt)):pe.insertBefore(Nt,kt)),On){let _t=parseFloat(Xt)||24,en=We(On,_t*.6,"currentColor",1);en?(en.style.width=`calc(${_t}px * var(--persona-components-header-iconScale, 0.6))`,en.style.height=`calc(${_t}px * var(--persona-components-header-iconScale, 0.6))`,Nt.replaceChildren(en)):Nt.textContent=he.agentIconText??"\u{1F4AC}"}else if(he.iconUrl){let _t=Nt.querySelector("img");if(_t)_t.src=he.iconUrl,_t.style.height=Xt,_t.style.width=Xt;else{let en=document.createElement("img");en.src=he.iconUrl,en.alt="",en.className="persona-rounded-xl persona-object-cover",en.style.height=Xt,en.style.width=Xt,Nt.replaceChildren(en)}}else{let _t=Nt.querySelector("svg"),en=Nt.querySelector("img");(_t||en)&&Nt.replaceChildren(),Nt.textContent=he.agentIconText??"\u{1F4AC}"}let Lt=Nt.querySelector("img");Lt&&(Lt.style.height=Xt,Lt.style.width=Xt)}}let vn=o.layout?.header?.showTitle,Rn=o.layout?.header?.showSubtitle;if(mo&&(mo.style.display=vn===!1?"none":""),ir&&(ir.style.display=Rn===!1?"none":""),Ze){let pe=Se()&&o.layout?.header?.showCloseButton!==!1;if(Ze.style.display=pe?"":"none",!Pe()){let Fn=he.closeButtonSize??"";Ze.style.height=Fn,Ze.style.width=Fn,Ze.style.minWidth=Fn,Ze.style.minHeight=Fn}let kt=he.closeButtonPlacement??"inline",{closeButtonWrapper:Lt}=wt,_t=kt==="top-right",en=Lt?.classList.contains("persona-absolute");if(Lt&&_t!==en)if(Lt.remove(),_t){Lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Fn=sn?.railColumn??Be;Fn.style.position="relative",Fn.appendChild(Lt)}else{let Fn=he.clearChat?.placement??"inline",Vn=he.clearChat?.enabled??!0;Lt.className=Vn&&Fn==="inline"?"":"persona-ml-auto",Vt&&Vt.appendChild(Lt)}if(Ze.style.color=he.closeButtonColor||lo.actionIconColor,he.closeButtonBackgroundColor?(Ze.style.backgroundColor=he.closeButtonBackgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let Fn=he.closeButtonBorderWidth||"0px",Vn=he.closeButtonBorderColor||"transparent";Ze.style.border=`${Fn} solid ${Vn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");he.closeButtonBorderRadius?(Ze.style.borderRadius=he.closeButtonBorderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(Ze.style.paddingLeft=he.closeButtonPaddingX,Ze.style.paddingRight=he.closeButtonPaddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),he.closeButtonPaddingY?(Ze.style.paddingTop=he.closeButtonPaddingY,Ze.style.paddingBottom=he.closeButtonPaddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom=""),Ou(Ze,he.closeButtonIconName??"x",{iconSize:Pe()?zh:void 0,iconText:he.closeButtonIconText??"\xD7"});let Qn=he.closeButtonTooltipText??"Close chat",Jo=he.closeButtonShowTooltip??!0;Ze.setAttribute("aria-label",Qn),Lt&&$n({anchor:Ze,trigger:Lt,text:()=>Ze?.getAttribute("aria-label")??Qn,enabled:Jo})}let{clearChatButton:Qe,clearChatButtonWrapper:Qt}=wt;if(Qe){let pe=he.clearChat??{},kt=pe.enabled??!0,Lt=o.layout?.header?.showClearChat,_t=Lt!==void 0?Lt:kt,en=pe.placement??"inline";if(Qt){Qt.style.display=_t?"":"none";let{closeButtonWrapper:Qn}=wt;!Pe()&&Qn&&!Qn.classList.contains("persona-absolute")&&(_t?Qn.classList.remove("persona-ml-auto"):Qn.classList.add("persona-ml-auto"));let Jo=en==="top-right",Fn=Qt.classList.contains("persona-absolute");if(!Pe()&&Jo!==Fn&&_t){if(Qt.remove(),Jo){Qt.className="persona-absolute persona-top-4 persona-z-50",Qt.style.right="48px";let yr=sn?.railColumn??Be;yr.style.position="relative",yr.appendChild(Qt)}else{Qt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qt.style.right="";let yr=wt.closeButtonWrapper;Vt&&yr&&yr.parentElement===Vt?Vt.insertBefore(Qt,yr):Vt&&Vt.appendChild(Qt)}let Vn=wt.closeButtonWrapper;Vn&&!Vn.classList.contains("persona-absolute")&&(Jo?Vn.classList.add("persona-ml-auto"):Vn.classList.remove("persona-ml-auto"))}}if(_t){if(!Pe()){let Vn=pe.size??"";Qe.style.height=Vn,Qe.style.width=Vn,Qe.style.minWidth=Vn,Qe.style.minHeight=Vn}let Qn=pe.iconColor??"";if(Qe.style.color=Qn||lo.actionIconColor,Ou(Qe,pe.iconName??"refresh-cw",{iconSize:Pe()?qh:void 0}),pe.backgroundColor?(Qe.style.backgroundColor=pe.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),pe.borderWidth||pe.borderColor){let Vn=pe.borderWidth||"0px",yr=pe.borderColor||"transparent";Qe.style.border=`${Vn} solid ${yr}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");pe.borderRadius?(Qe.style.borderRadius=pe.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),pe.paddingX?(Qe.style.paddingLeft=pe.paddingX,Qe.style.paddingRight=pe.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),pe.paddingY?(Qe.style.paddingTop=pe.paddingY,Qe.style.paddingBottom=pe.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Jo=pe.tooltipText??"Clear chat",Fn=pe.showTooltip??!0;Qe.setAttribute("aria-label",Jo),Qt&&$n({anchor:Qe,trigger:Qt,text:()=>Qe?.getAttribute("aria-label")??Jo,enabled:Fn})}}let it=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ry],Wn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Nc.message,Nc.messageAndClick];ke=Wy({parsers:it,handlers:Wn,getSessionMetadata:xe,updateSessionMetadata:Te,emit:L.emit,documentRef:typeof document<"u"?document:null}),Z=n0(o,ke,ne),ck(),V.updateConfig(o),kv(),(o.features?.history?.enabled===!0!==Pt||o.features?.history?.provider!==Ft||o.getIdentityProof!==Dt||o.clientToken!==bo)&&(sn?.closeHistory({restoreFocus:!1}),sn?.installHistoryProvider()),sn?.syncHistoryChromeImpl(),kd(),vl()&&!sn&&ym().catch(()=>{}),Io($e,V.getMessages(),Z),ni(),Sd(),ik(),yl(V.isStreaming()),an!==o.contextMentions&&sC();let _o=o.voiceRecognition?.enabled===!0,Nn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),jt=no(o.voiceRecognition?.provider);if(_o&&(Nn||jt))if(!De||!Dn){let pe=Ia(o);if(pe){De=pe.button,Dn=pe.wrapper;let kt=ro&&ro.parentElement===js?ro:null;js?js.insertBefore(Dn,kt):Pn?.appendChild(Dn),Bt&&(Bt.micButton=De),Bt?.addListener(De,"click",km),De.disabled=pr()||V.isStreaming()&&!Jf()}}else{let pe=o.voiceRecognition??{},kt=o.sendButton??{},Lt=pe.iconName??"mic",_t=pe.iconSize,en=parseFloat(_t??"")||Co;De.classList.add(Mo),De.classList.toggle(rr,!_t),De.style.width=_t??"",De.style.height=_t??"",De.style.minWidth=_t??"",De.style.minHeight=_t??"";let Qn=pe.iconColor??kt.textColor;De.innerHTML="";let Jo=We(Lt,en,Qn||"currentColor",1.5);Jo?De.appendChild(Jo):De.textContent="\u{1F3A4}";let Fn=pe.backgroundColor??kt.backgroundColor;Fn?De.style.backgroundColor=Fn:De.style.backgroundColor="",Qn?De.style.color=Qn:De.style.color="var(--persona-text, #111827)",pe.borderWidth?(De.style.borderWidth=pe.borderWidth,De.style.borderStyle="solid"):(De.style.borderWidth="",De.style.borderStyle=""),pe.borderColor?De.style.borderColor=pe.borderColor:De.style.borderColor="",pe.paddingX?(De.style.paddingLeft=pe.paddingX,De.style.paddingRight=pe.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),pe.paddingY?(De.style.paddingTop=pe.paddingY,De.style.paddingBottom=pe.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Vn=pe.tooltipText??"Start voice recognition",yr=pe.showTooltip??!1;De.setAttribute("aria-label",Vn),Dn&&$n({anchor:De,trigger:Dn,text:()=>De?.getAttribute("aria-label")??Vn,enabled:yr}),Dn.style.display="",De.disabled=pr()||V.isStreaming()&&!Jf()}else De&&Dn&&(Dn.style.display="none",no(o.voiceRecognition?.provider)?V.isVoiceActive()&&V.toggleVoice():fr&&Cs());if(Pm(),o.attachments?.enabled===!0){if(!In||!Zt){let pe=o.attachments??{};_n||(_n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),_n.style.display="none",(we.parentElement??Pn).insertBefore(_n,we)),Gt||(Gt=document.createElement("input"),Gt.type="file",Gt.accept=(pe.allowedTypes??Qr).join(","),Gt.multiple=(pe.maxFiles??4)>1,Gt.style.display="none",Gt.setAttribute("aria-label","Attach files"),(we.parentElement??Pn).insertBefore(Gt,we)),In=v("div","persona-send-button-wrapper"),Zt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Mo} ${rr}`),Zt.type="button",Zt.setAttribute("aria-label",pe.buttonTooltipText??"Attach file");let kt=pe.buttonIconName??"paperclip";Zt.style.fontSize="18px",Zt.style.lineHeight="1";let Lt=We(kt,Co,"currentColor",1.5);Lt?Zt.appendChild(Lt):Zt.textContent="\u{1F4CE}",Zt.addEventListener("click",en=>{en.preventDefault(),Gt?.click()}),In.appendChild(Zt);let _t=pe.buttonTooltipText??"Attach file";$n({anchor:Zt,trigger:In,text:()=>Zt?.getAttribute("aria-label")??_t}),Kn?Kn.append(In):Pn.appendChild(In),Bt&&(Bt.attachmentButton=Zt,Bt.attachmentInput=Gt??void 0,Bt.attachmentPreviews=_n??void 0),!ut&&Gt&&_n&&(ut=rc.fromConfig(pe,nb),ut.setPreviewsContainer(_n),Bt?.addListener(Gt,"change",async()=>{ut&&Gt?.files&&(await ut.handleFileSelect(Gt.files),Gt.value="")}))}else{In.style.display="";let pe=o.attachments??{};Gt&&(Gt.accept=(pe.allowedTypes??Qr).join(","),Gt.multiple=(pe.maxFiles??4)>1),ut&&ut.updateConfig({allowedTypes:pe.allowedTypes,maxFileSize:pe.maxFileSize,maxFiles:pe.maxFiles,adapter:pe.adapter})}if(Be.querySelector(".persona-attachment-drop-overlay")?.remove(),Be.appendChild(o0(o.attachments?.dropOverlay)),Zt){let pe=o.attachments??{},kt=pe.buttonTooltipText??"Attach file";Zt.setAttribute("aria-label",kt),Zt.textContent="";let Lt=We(pe.buttonIconName??"paperclip",Co,"currentColor",1.5);Lt?Zt.appendChild(Lt):Zt.textContent="\u{1F4CE}",In&&$n({anchor:Zt,trigger:In,text:()=>Zt?.getAttribute("aria-label")??kt})}}else In&&(In.style.display="none"),ut&&ut.clearAttachments(),Be.querySelector(".persona-attachment-drop-overlay")?.remove();let at=o.sendButton??{},Ms=at.useIcon??!1,Tn=at.iconText??"\u2191",vo=at.iconName,Vr=at.tooltipText??"Send message",Rm=at.showTooltip??!1,yi=at.size,Wm=parseFloat(yi??"")||Mg,$r=at.backgroundColor,bi=at.textColor;if(Ms){if(ze.style.width=yi??"",ze.style.height=yi??"",ze.style.minWidth=yi??"",ze.style.minHeight=yi??"",ze.style.fontSize="18px",ze.style.lineHeight="1",bi?ze.style.color=bi:ze.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!V.isStreaming())if(ze.innerHTML="",vo){let pe=parseFloat(at.iconSize??"")||Math.round(Wm*.5),kt=bi?.trim()||"currentColor",Lt=at.iconStrokeWidth??2,_t=We(vo,pe,kt,Lt),en=We(at.stopIconName??"square",pe,kt,Lt);_t&&en?ze.appendChild(Tg(_t,en)):_t?ze.appendChild(_t):ze.textContent=Tn}else ze.textContent=Tn;ze.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Mo}`,$r?(ze.style.backgroundColor=$r,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=o.copy?.sendButtonLabel??"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.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",$r?(ze.style.backgroundColor=$r,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),bi?ze.style.color=bi:ze.classList.add("persona-text-white");at.borderWidth?(ze.style.borderWidth=at.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),at.borderColor?ze.style.borderColor=at.borderColor:ze.style.borderColor="",at.paddingX?(ze.style.paddingLeft=at.paddingX,ze.style.paddingRight=at.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),at.paddingY?(ze.style.paddingTop=at.paddingY,ze.style.paddingBottom=at.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom=""),V.isStreaming()||ze.setAttribute("aria-label",Vr),Cd(),ro&&$n({anchor:ze,trigger:ro,text:()=>ze.getAttribute("aria-label")??Vr,enabled:Rm}),gb(),_f();let gC=vu(Oe.getState().activeModeIds,o.composer?.modes);Oe.setActiveModeIds(gC),Ki().length>0!==!!Lr&&kf(),Lr?.render(gC,Ki());for(let pe of[...Gi.keys()])bu(pe,o.composer?.modeGroups)||Gi.delete(pe);Gi.forEach(pe=>pe.repaint()),ls?.repaint(),jo?.resolve();let Nd=Os(o,Pe());if(Df(),Nd){$e.style.maxWidth=Nd,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ne.style.maxWidth=Nd,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%";for(let pe of[Pn,eo,_n,Mt])pe&&(pe.style.maxWidth=Nd,pe.style.marginLeft="auto",pe.style.marginRight="auto",pe.style.width="100%")}else{$e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ne.style.maxWidth="",Ne.style.marginLeft="",Ne.style.marginRight="",Ne.style.width="";for(let pe of[Pn,eo,_n,Mt])pe&&(pe.style.maxWidth="",pe.style.marginLeft="",pe.style.marginRight="",pe.style.width="")}let Qo=o.statusIndicator??{};if(Ym(Mt,Pn,Qo),xi(Mt,Qo,V?.getStatus()??"idle"),V){let pe=V.getStatus();Tr(Mt,(Lt=>Lt==="idle"?Qo.idleText??Cn.idle:Lt==="connecting"?Qo.connectingText??Cn.connecting:Lt==="connected"?Qo.connectedText??Cn.connected:Lt==="error"?Qo.errorText??Cn.error:Lt==="paused"?Qo.pausedText??Cn.paused:Lt==="resuming"?Qo.resumingText??Cn.resuming:Cn[Lt])(pe),Qo,pe)}Mt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let qk=Qo.align==="left"?"persona-text-left":Qo.align==="center"?"persona-text-center":"persona-text-right";Mt.classList.add(qk),Tf(),em(),Ko(),Ht()},open(){Se()&&Yt(!0,"api")},close(){Se()&&Yt(!1,"api")},toggle(){Se()&&Yt(!U,"api")},reconnect(){V.reconnectNow()},clearChat(){Pr=!1,i.clear(),r.clear(),s.clear(),l.clear(),V.clearMessages(),o.layout?.topFade&&(ye.scrollTop=0),ye.removeAttribute("data-persona-top-fade"),Yn.clear(),dr();try{localStorage.removeItem(Qa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qa}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),x?.clear&&fd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},ke.syncFromMetadata(),ut?.clearAttachments(),gd(),Yi(void 0),ar(void 0),si(),ee?.clear(),Re?.reset(),bt?.update()},setMessage(a){return!we||V.isStreaming()||pr()?!1:(!U&&Se()&&Yt(!0,"system"),we.value=a,we.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(V.isStreaming()||ui())return!1;let u=a?.trim()||we.value.trim();return u?(!U&&Se()&&Yt(!0,"system"),we.value="",we.style.height="auto",ko(),Hd(u,{consumeDraft:!1}),!0):!1},getComposerState(){return Oe.getState()},setQuote(a){let u=a?.text?.trim();u&&ar({...a,text:u})},clearQuote(){ar(void 0)},startVoiceRecognition(){return V.isStreaming()?!1:no(o.voiceRecognition?.provider)?(V.isVoiceActive()||V.isBargeInActive()||(!U&&Se()&&Yt(!0,"system"),vt.manuallyDeactivated=!1,yo(),V.toggleVoice().then(()=>{vt.active=Uf(),yo(),Br("user"),vt.active&&ma()})),!0):fr?!0:Bv()?(!U&&Se()&&Yt(!0,"system"),vt.manuallyDeactivated=!1,yo(),Bd("user"),!0):!1},stopVoiceRecognition(){return no(o.voiceRecognition?.provider)?!V.isVoiceActive()&&!V.isBargeInActive()?!1:((V.isBargeInActive()?V.deactivateBargeIn():V.toggleVoice()).then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,yo(),Br("user"),Fr()}),!0):fr?(vt.manuallyDeactivated=!0,yo(),Cs("user"),!0):!1},injectMessage(a){return!U&&Se()&&Yt(!0,"system"),V.injectMessage(a)},injectAssistantMessage(a){!U&&Se()&&Yt(!0,"system");let u=V.injectAssistantMessage(a);return R&&(R=!1,G&&(clearTimeout(G),G=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),u},injectUserMessage(a){return!U&&Se()&&Yt(!0,"system"),V.injectUserMessage(a)},injectSystemMessage(a){return!U&&Se()&&Yt(!0,"system"),V.injectSystemMessage(a)},injectMessageBatch(a){return!U&&Se()&&Yt(!0,"system"),V.injectMessageBatch(a)},injectComponentDirective(a){return!U&&Se()&&Yt(!0,"system"),V.injectComponentDirective(a)},injectTestMessage(a){!U&&Se()&&Yt(!0,"system"),V.injectTestEvent(a)},async connectStream(a,u){return V.connectStream(a,u)},__pushEventStreamEvent(a){Ie&&(nn(),wn(a.type,a.payload))},showEventStream(){Ie&&Mf()},hideEventStream(){Ee&&Xi()},isEventStreamVisible(){return Ee},listConversations(a){return V.listConversations(a)},getActiveConversationId(){return V.getActiveConversationId()},openConversation(a,u){return ur(y=>y.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return ur(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){bm()},deleteConversation(a){return ur(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return ur(y=>y.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return ur(y=>y.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return ur(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return ur(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=Ho;if(!a)return null;let u=await a.get();return a===Ho?u:null},getHistoryIdentityStatus(){let a=sn?.historyProvider;return a?a.getIdentityStatus():vl()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return vl()?ur(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){sn?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return Ot},showArtifacts(){po(o)&&(Pr=!1,Ji=!0,Yo(),Et?.setMobileOpen(!0))},hideArtifacts(){po(o)&&(Pr=!0,Yo())},upsertArtifact(a){return po(o)?(ks(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(Pr=!1,Ji=!0),V.upsertArtifact(a)):null},selectArtifact(a){po(o)&&V.selectArtifact(a)},clearArtifacts(){po(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return ve&&!U&&!Pe()||!we?!1:(we.focus(),!0)},async resolveApproval(a,u,y){let H=V.getMessages().find(O=>O.variant==="approval"&&O.approval?.id===a);if(!H?.approval)throw new Error(`Approval not found: ${a}`);if(H.approval.toolType==="webmcp"){V.resolveWebMcpApproval(H.id,u);return}return V.resolveApproval(H.approval,u,y)},setFollowUpSuggestions(a){I0(a)},clearFollowUpSuggestions(){zb()},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...I}},updatePersistentMetadata(a){Te(a)},on(a,u){return L.on(a,u)},off(a,u){L.off(a,u)},isOpen(){return Se()&&U},isVoiceActive(){return vt.active},toggleReadAloud(a){V.toggleReadAloud(a)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(a){return V.getReadAloudState(a)},onReadAloudChange(a){return V.onReadAloudChange(a)},getState(){return{open:Se()&&U,launcherEnabled:ve,voiceActive:vt.active,streaming:V.isStreaming()}},showCSATFeedback(a){!U&&Se()&&Yt(!0,"system");let u=$e.querySelector(".persona-feedback-container");u&&u.remove();let y=ZE({onSubmit:async(M,H)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(M,H),a?.onSubmit?.(M,H)},onDismiss:a?.onDismiss,...a});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!U&&Se()&&Yt(!0,"system");let u=$e.querySelector(".persona-feedback-container");u&&u.remove();let y=e0({onSubmit:async(M,H)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(M,H),a?.onSubmit?.(M,H)},onDismiss:a?.onDismiss,...a});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return V.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return V.submitNPSFeedback(a,u)},destroy(){um(),fi!=null&&(clearInterval(fi),fi=null),i.clear(),r.clear(),s.clear(),l.clear(),Ue.forEach(a=>a()),ot.remove(),cn?.remove(),hn?.destroy(),so?.remove(),ei&&Ze.removeEventListener("click",ei)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:yn,getMessages:yn.getMessages,getStatus:yn.getStatus,getMetadata:yn.getPersistentMetadata,updateMetadata:yn.updatePersistentMetadata,clearHistory:()=>yn.clearChat(),setVoiceActive:y=>y?yn.startVoiceRecognition():yn.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ue.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.focusInput()};if(window.addEventListener("persona:focusInput",u),Ue.push(()=>{window.removeEventListener("persona:focusInput",u)}),Ie){let be=Ae=>{let Ke=Ae.detail;(!Ke?.instanceId||Ke.instanceId===a)&&yn.showEventStream()},Ce=Ae=>{let Ke=Ae.detail;(!Ke?.instanceId||Ke.instanceId===a)&&yn.hideEventStream()};window.addEventListener("persona:showEventStream",be),window.addEventListener("persona:hideEventStream",Ce),Ue.push(()=>{window.removeEventListener("persona:showEventStream",be),window.removeEventListener("persona:hideEventStream",Ce)})}let y=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.showHistory()},M=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.hideHistory()};window.addEventListener("persona:showHistory",y),window.addEventListener("persona:hideHistory",M),Ue.push(()=>{window.removeEventListener("persona:showHistory",y),window.removeEventListener("persona:hideHistory",M)});let H=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.showArtifacts()},O=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.hideArtifacts()},se=be=>{let Ce=be.detail;Ce?.instanceId&&Ce.instanceId!==a||Ce?.artifact&&yn.upsertArtifact(Ce.artifact)},ge=be=>{let Ce=be.detail;Ce?.instanceId&&Ce.instanceId!==a||typeof Ce?.id=="string"&&yn.selectArtifact(Ce.id)},ce=be=>{let Ce=be.detail;(!Ce?.instanceId||Ce.instanceId===a)&&yn.clearArtifacts()};window.addEventListener("persona:showArtifacts",H),window.addEventListener("persona:hideArtifacts",O),window.addEventListener("persona:upsertArtifact",se),window.addEventListener("persona:selectArtifact",ge),window.addEventListener("persona:clearArtifacts",ce),Ue.push(()=>{window.removeEventListener("persona:showArtifacts",H),window.removeEventListener("persona:hideArtifacts",O),window.removeEventListener("persona:upsertArtifact",se),window.removeEventListener("persona:selectArtifact",ge),window.removeEventListener("persona:clearArtifacts",ce)})}let Wo=I_(o.persistState);if(Wo&&Se()){let a=H_(Wo.storage),u=`${Wo.keyPrefix}widget-open`,y=`${Wo.keyPrefix}widget-voice`,M=`${Wo.keyPrefix}widget-voice-mode`;if(a){let H=Wo.persist?.openState&&a.getItem(u)==="true",O=Wo.persist?.voiceState&&a.getItem(y)==="true",se=Wo.persist?.voiceState&&a.getItem(M)==="true";if(H&&(hn?.setPanelOpen(!0,"auto"),setTimeout(()=>{yn.open(),setTimeout(()=>{if(O||se)yn.startVoiceRecognition();else if(Wo.persist?.focusInput){let ge=e.querySelector("textarea");ge&&ge.focus()}},100)},0)),Wo.persist?.openState&&(L.on("widget:opened",()=>{a.setItem(u,"true")}),L.on("widget:closed",()=>{a.setItem(u,"false")})),Wo.persist?.voiceState&&(L.on("voice:state",ge=>{a.setItem(y,ge.active?"true":"false")}),L.on("user:message",ge=>{a.setItem(M,ge.viaVoice?"true":"false")})),Wo.clearOnChatClear){let ge=()=>{a.removeItem(u),a.removeItem(y),a.removeItem(M)},ce=()=>ge();window.addEventListener("persona:clear-chat",ce),Ue.push(()=>{window.removeEventListener("persona:clear-chat",ce)})}}}if(oe&&Se()&&(hn?.setPanelOpen(!0,"auto"),setTimeout(()=>{yn.open()},0)),aa(),!H0){let a=va(()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))});Ue.push(a)}E=()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))},V.getMessages().length>0&&vd(),T=()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))};let Uk=LC(()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z))});Ue.push(Uk);let zk=Ay(()=>{V&&(ii++,Yn.clear(),Io($e,V.getMessages(),Z),ts()?.updateInlineArtifactBlocks($e,Lo.artifacts,{suppressTransition:!0}),Yo())});return Ue.push(zk),yn};nr();var s0=(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},B_=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},D_=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},__=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},i0=(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"},Zy=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=""},a0=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Zy(e)},Xy=e=>{e.style.transition=""},Qy=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=""},Jy=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},bf=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},O_=(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))},N_=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},F_=e=>{let t=Jr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:zn(t,r)??r;return{inset:o(n?.inset,Su),canvasBackground:o(n?.canvasBackground,Au)}},l0=(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},V_=(e,t,n,o,r,s,i,l)=>{let c=$o(s),d=c.reveal==="push",p=l!=null,f=l?.inset??"",m=l?.canvasBackground??"";O_(e,t,n,o,d),N_(e,t,n,o,c.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"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 g=e.ownerDocument.defaultView,h=s?.launcher?.mobileFullscreen??!0,b=s?.launcher?.mobileBreakpoint??640,C=g!=null?g.innerWidth<=b:!1;if(h&&C&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Qy(t),Xy(o),a0(o),Jy(n),bf(r,o),l0(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??Jn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(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"),a0(o),B_(o,c.maxHeight),l0(o,p&&i,f,m),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Qy(t),Xy(o),Jy(n),bf(r,o);let S=c.animate?"transform 180ms ease":"none",E=c.side==="right"?"translateX(100%)":"translateX(-100%)",k=i?"translateX(0)":E;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=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=S,o.style.transform=k,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Xy(o),Zy(o),bf(r,o);let S=s0(c.width,e.clientWidth),E=Math.max(0,e.clientWidth),k=c.animate?"margin-left 180ms ease":"none",D=c.side==="right"?i?-S:0:i?0:-S;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=`${E+S}px`,t.style.transition=k,t.style.marginLeft=`${D}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Qy(t),Zy(o),Jy(n),bf(r,o);let S=c.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=i?c.width:"0px",k=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",D=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",D_(o,c.maxHeight),o.style.overflow=S||D?"hidden":"visible",o.style.transition=k,S){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let z=p?`calc(${s0(c.width,e.clientWidth)}px - (2 * ${f}))`:c.width;r.style.width=z,r.style.minWidth=z,r.style.maxWidth=z,r.style.boxSizing="border-box"}}},$_=(e,t)=>{let n=e.ownerDocument.createElement("div");return i0(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){i0(n,o)},destroy(){n.remove()}}},U_=(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,i=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),d=n.createElement("aside"),p=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",d.appendChild(p),o.insertBefore(i,e),c.appendChild(e);let m=null,g=()=>{m?.disconnect(),m=null},h=null,b=()=>{h=t?.launcher?.detachedPanel===!0?F_(t):null};b();let C=()=>{V_(i,l,c,d,p,t,f,h)},A=null,S=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Mu(()=>{b(),C()}))},E=()=>{g(),$o(t).reveal==="push"&&(typeof ResizeObserver>"u"||(m=new ResizeObserver(()=>{C()}),m.observe(i)))},k=!1,D=()=>{C(),E(),f&&!k&&i.dataset.personaDockMobileFullscreen!=="true"&&(k=!0,__(i,$o(t)))},z=i.ownerDocument.defaultView,Y=()=>{D()};return z?.addEventListener("resize",Y),$o(t).reveal==="push"?(l.appendChild(c),l.appendChild(d),i.appendChild(l)):(i.appendChild(c),i.appendChild(d)),D(),S(),{mode:"docked",host:p,shell:i,syncWidgetState(T){let W=T.launcherEnabled?T.open:!0;f!==W&&(f=W,D())},updateConfig(T){t=T,(t?.launcher?.enabled??!0)===!1&&(f=!0),b(),D(),S()},destroy(){z?.removeEventListener("resize",Y),A?.(),A=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},c0=(e,t)=>un(t)?U_(e,t):$_(e,t);er();var jc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},d0=.15,p0=1.5,eb="persona-preview-shell-theme",z_={load:()=>null,save:()=>{},clear:()=>{}},q_=["How do I get started?","Pricing & plans","Talk to support"];function tb(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function j_(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function u0(e){let t=j_(e);return`* { box-sizing: border-box; }
1287
1287
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
1288
1288
  html { color-scheme: ${e}; }
1289
1289
  body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
@@ -1307,7 +1307,7 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1307
1307
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
1308
1308
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
1309
1309
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
1310
- .preview-workspace-card.short { height: 96px; }`}function u0(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(eb);o||(o=n.createElement("style"),o.id=eb,n.head.appendChild(o)),o.textContent=p0(t)}var j_=`
1310
+ .preview-workspace-card.short { height: 96px; }`}function f0(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(eb);o||(o=n.createElement("style"),o.id=eb,n.head.appendChild(o)),o.textContent=u0(t)}var K_=`
1311
1311
  <div class="preview-iframe-mock" aria-hidden="true">
1312
1312
  <div class="preview-iframe-chrome">
1313
1313
  <span class="preview-iframe-dot"></span>
@@ -1326,7 +1326,7 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1326
1326
  <div class="preview-iframe-line body"></div>
1327
1327
  <div class="preview-iframe-line body"></div>
1328
1328
  </div>
1329
- </div>`,K_=`
1329
+ </div>`,G_=`
1330
1330
  <div class="preview-workspace-content-shell" aria-hidden="true">
1331
1331
  <div class="preview-iframe-line hero"></div>
1332
1332
  <div class="preview-iframe-line body"></div>
@@ -1339,8 +1339,8 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1339
1339
  <div class="preview-workspace-card short"></div>
1340
1340
  <div class="preview-workspace-card short"></div>
1341
1341
  </div>
1342
- </div>`;function f0(e,t,n,o){let r=`
1343
- ${j_}
1342
+ </div>`;function m0(e,t,n,o){let r=`
1343
+ ${K_}
1344
1344
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
1345
1345
  <div class="preview-workspace-shell">
1346
1346
  <div class="preview-workspace-topbar">
@@ -1352,7 +1352,7 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1352
1352
  </div>
1353
1353
  <div class="preview-workspace-body">
1354
1354
  <div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
1355
- ${K_}
1355
+ ${G_}
1356
1356
  </div>
1357
1357
  </div>
1358
1358
  </div>`;return`<!DOCTYPE html>
@@ -1361,15 +1361,15 @@ _Details: ${n.message}_`:o}var GS=e=>Ca(e)||e===Yr,hu=class e{constructor(t={},n
1361
1361
  <meta charset="UTF-8">
1362
1362
  <meta name="viewport" content="width=device-width, initial-scale=1">
1363
1363
  <link rel="stylesheet" href="${tb(o)}">
1364
- <style id="${eb}">${p0(t)}</style>
1364
+ <style id="${eb}">${u0(t)}</style>
1365
1365
  </head>
1366
1366
  <body>
1367
1367
  ${n?s:r}
1368
1368
  </body>
1369
- </html>`}var G_=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Y_=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||e?.features?.reasoningDisplay?.activePreview);function X_(e,t,n=[]){if(e==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return e==="home"?[]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&Y_(t)?[...G_(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Q_(e,t,n=[]){let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?e.suggestionChips?.length?e.suggestionChips:z_:e.suggestionChips,initialMessages:X_(t,e,n),storageAdapter:U_};return t==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),t==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function J_(e,t){let n=qd(e.config),o=e.config?.future,r=e.theme?_a(e.theme,{validate:!1,future:o}):_a(void 0,{future:o});return{...n,...e.config,theme:r,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??"light"}}function Za(e,t){let n=e.scene??"conversation";return Q_(J_(e,t),n,e.appendedMessages??[])}function m0(e){let t=e.compareMode??"off",n=e.shellMode??"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Za(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Za(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let o={...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Za(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Za(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Za(e,n),shellMode:n}]}function g0(e,t){let n={...t},o=[],r=[],s=null,i=!1,l=1,c=1,d=0;function p(){return n.device??"desktop"}function f(){return n.zoom??l}function m(){let S=getComputedStyle(e),E=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),k=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),D=40,z=(n.compareMode??"off")!=="off",Y=(e.clientWidth-E-D)/(z?2:1),T=e.clientHeight-k-D;if(Y<=0||T<=0)return 1;let W=jc[p()]??jc.desktop;return Math.min(Y/W.w,T/W.h,1)}function g(){l=m();let S=Math.max(c0,Math.min(d0,f()));c=S;let E=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let k of E){let D=k.dataset.device??"desktop",z=jc[D]??jc.desktop;k.style.width=`${z.w*S}px`,k.style.height=`${z.h*S}px`,D==="mobile"&&(k.style.borderRadius=`${32*S}px`);let Y=k.querySelector("iframe");Y&&(Y.style.width=`${z.w}px`,Y.style.height=`${z.h}px`,Y.style.transformOrigin="top left",Y.style.transition="none",Y.style.transform=`scale(${S})`)}n.onScaleChange?.(S)}function h(){n.onBeforeDestroy?.();for(let S of o)S.destroy();for(let S of r)S();o=[],r=[]}function b(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function C(){if(i)return;h();let S=++d,E=m0(n),k=p(),D=(n.compareMode??"off")!=="off",z=(n.scene??"conversation")==="minimized",Y=n.widgetCssPath??"/widget-dist/widget.css",T=n.buildSrcdoc??f0,W=k==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",L=_=>`<div class="${W}" data-mount-id="${_.mountId}" data-device="${k}" data-shell-mode="${_.shellMode}">
1369
+ </html>`}var Y_=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],X_=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||e?.features?.reasoningDisplay?.activePreview);function Q_(e,t,n=[]){if(e==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return e==="home"?[]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&X_(t)?[...Y_(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function J_(e,t,n=[]){let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?e.suggestionChips?.length?e.suggestionChips:q_:e.suggestionChips,initialMessages:Q_(t,e,n),storageAdapter:z_};return t==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),t==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function Z_(e,t){let n=qd(e.config),o=e.config?.future,r=e.theme?_a(e.theme,{validate:!1,future:o}):_a(void 0,{future:o});return{...n,...e.config,theme:r,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??"light"}}function Za(e,t){let n=e.scene??"conversation";return J_(Z_(e,t),n,e.appendedMessages??[])}function g0(e){let t=e.compareMode??"off",n=e.shellMode??"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Za(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Za(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let o={...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Za(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Za(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Za(e,n),shellMode:n}]}function h0(e,t){let n={...t},o=[],r=[],s=null,i=!1,l=1,c=1,d=0;function p(){return n.device??"desktop"}function f(){return n.zoom??l}function m(){let S=getComputedStyle(e),E=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),k=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),D=40,z=(n.compareMode??"off")!=="off",Y=(e.clientWidth-E-D)/(z?2:1),T=e.clientHeight-k-D;if(Y<=0||T<=0)return 1;let W=jc[p()]??jc.desktop;return Math.min(Y/W.w,T/W.h,1)}function g(){l=m();let S=Math.max(d0,Math.min(p0,f()));c=S;let E=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let k of E){let D=k.dataset.device??"desktop",z=jc[D]??jc.desktop;k.style.width=`${z.w*S}px`,k.style.height=`${z.h*S}px`,D==="mobile"&&(k.style.borderRadius=`${32*S}px`);let Y=k.querySelector("iframe");Y&&(Y.style.width=`${z.w}px`,Y.style.height=`${z.h}px`,Y.style.transformOrigin="top left",Y.style.transition="none",Y.style.transform=`scale(${S})`)}n.onScaleChange?.(S)}function h(){n.onBeforeDestroy?.();for(let S of o)S.destroy();for(let S of r)S();o=[],r=[]}function b(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function C(){if(i)return;h();let S=++d,E=g0(n),k=p(),D=(n.compareMode??"off")!=="off",z=(n.scene??"conversation")==="minimized",Y=n.widgetCssPath??"/widget-dist/widget.css",T=n.buildSrcdoc??m0,W=k==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",L=_=>`<div class="${W}" data-mount-id="${_.mountId}" data-device="${k}" data-shell-mode="${_.shellMode}">
1370
1370
  ${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${tb(_.label)}</span></div>`:""}
1371
1371
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${_.mountId}"></iframe>
1372
- </div>`,w=D?`<div class="preview-compare-grid">${E.map(_=>`<div class="preview-compare-cell">${L(_)}</div>`).join("")}</div>`:`<div class="preview-single">${L(E[0])}</div>`;n.morphContainer?n.morphContainer(e,w):e.innerHTML=w,g();let x=b(),P=0,I=x.length,J=()=>{if(i||S!==d)return;for(let j of x){let te=j.dataset.mountId;if(!te||!j.contentDocument)continue;let K=E.find(Te=>Te.mountId===te);if(!K)continue;let X=()=>{},oe=un(K.config),de=oe?(()=>{let Te=j.contentDocument?.getElementById(`preview-content-${te}`);if(!Te)return null;let re=l0(Te,K.config),N=j.contentDocument.createElement("div");N.id=te,N.style.height="100%",N.style.display="flex",N.style.flexDirection="column",N.style.flex="1",N.style.minHeight="0",re.host.appendChild(N);let ke=()=>re.syncWidgetState(xe.getState()),ve=X;return X=()=>{re.destroy(),ve()},N.__syncDock=ke,N.__hostLayout=re,N})():j.contentDocument.getElementById(te);if(!de)continue;let xe=o0(de,K.config);if(o.push(xe),oe&&de.__syncDock){let Te=de.__syncDock,re=xe.on("widget:opened",Te),N=xe.on("widget:closed",Te),ke=X;X=()=>{re(),N(),ke()},Te()}r.push(X),z&&xe.close()}let _=n.scene??"conversation";if(_==="messages")for(let j of o)j.showHistory({focus:!1});if(_==="artifact"||n.config?.features?.artifacts?.enabled)for(let j of o)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
1372
+ </div>`,w=D?`<div class="preview-compare-grid">${E.map(_=>`<div class="preview-compare-cell">${L(_)}</div>`).join("")}</div>`:`<div class="preview-single">${L(E[0])}</div>`;n.morphContainer?n.morphContainer(e,w):e.innerHTML=w,g();let x=b(),P=0,I=x.length,J=()=>{if(i||S!==d)return;for(let j of x){let te=j.dataset.mountId;if(!te||!j.contentDocument)continue;let K=E.find(Te=>Te.mountId===te);if(!K)continue;let X=()=>{},oe=un(K.config),de=oe?(()=>{let Te=j.contentDocument?.getElementById(`preview-content-${te}`);if(!Te)return null;let re=c0(Te,K.config),N=j.contentDocument.createElement("div");N.id=te,N.style.height="100%",N.style.display="flex",N.style.flexDirection="column",N.style.flex="1",N.style.minHeight="0",re.host.appendChild(N);let ke=()=>re.syncWidgetState(xe.getState()),ve=X;return X=()=>{re.destroy(),ve()},N.__syncDock=ke,N.__hostLayout=re,N})():j.contentDocument.getElementById(te);if(!de)continue;let xe=r0(de,K.config);if(o.push(xe),oe&&de.__syncDock){let Te=de.__syncDock,re=xe.on("widget:opened",Te),N=xe.on("widget:closed",Te),ke=X;X=()=>{re(),N(),ke()},Te()}r.push(X),z&&xe.close()}let _=n.scene??"conversation";if(_==="messages")for(let j of o)j.showHistory({focus:!1});if(_==="artifact"||n.config?.features?.artifacts?.enabled)for(let j of o)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
1373
1373
 
1374
1374
  This is a preview of the artifact sidebar.
1375
1375
 
@@ -1377,4 +1377,4 @@ This is a preview of the artifact sidebar.
1377
1377
 
1378
1378
  - Markdown rendering
1379
1379
  - Document toolbar
1380
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:x,controllers:[...o]})};for(let _ of x){let j=_.dataset.mountId;if(!j)continue;let te=E.find(K=>K.mountId===j);te&&(_.addEventListener("load",()=>{P++,P>=I&&J()},{once:!0}),_.srcdoc=T(j,te.shellMode,un(te.config),Y))}I===0&&J()}function A(){if(i)return;let S=m0(n);if(o.length!==S.length){C();return}if(S.some(k=>{let D=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${k.mountId}"]`);return!D||D.dataset.shellMode!==k.shellMode})){C();return}o.forEach((k,D)=>{k.update(S[D].config),(n.scene??"conversation")==="minimized"&&k.close()});for(let k of S){let D=e.querySelector(`iframe[data-mount-id="${k.mountId}"]`);D&&u0(D,k.shellMode)}n.onAfterUpdate?.({iframes:b(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||g()}),s.observe(e)),C(),{update(S){if(i)return;let E=S.device!==void 0&&S.device!==n.device||S.scene!==void 0&&S.scene!==n.scene||S.compareMode!==void 0&&S.compareMode!==n.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==n.widgetCssPath;n={...n,...S},E?C():A()},destroy(){i||(i=!0,h(),s?.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},g())},getIframes(){return b()},getScale(){return c},setZoom(S){i||(n={...n,zoom:S},g())}}}0&&(module.exports={createThemePreview});
1380
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:x,controllers:[...o]})};for(let _ of x){let j=_.dataset.mountId;if(!j)continue;let te=E.find(K=>K.mountId===j);te&&(_.addEventListener("load",()=>{P++,P>=I&&J()},{once:!0}),_.srcdoc=T(j,te.shellMode,un(te.config),Y))}I===0&&J()}function A(){if(i)return;let S=g0(n);if(o.length!==S.length){C();return}if(S.some(k=>{let D=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${k.mountId}"]`);return!D||D.dataset.shellMode!==k.shellMode})){C();return}o.forEach((k,D)=>{k.update(S[D].config),(n.scene??"conversation")==="minimized"&&k.close()});for(let k of S){let D=e.querySelector(`iframe[data-mount-id="${k.mountId}"]`);D&&f0(D,k.shellMode)}n.onAfterUpdate?.({iframes:b(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||g()}),s.observe(e)),C(),{update(S){if(i)return;let E=S.device!==void 0&&S.device!==n.device||S.scene!==void 0&&S.scene!==n.scene||S.compareMode!==void 0&&S.compareMode!==n.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==n.widgetCssPath;n={...n,...S},E?C():A()},destroy(){i||(i=!0,h(),s?.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},g())},getIframes(){return b()},getScale(){return c},setZoom(S){i||(n={...n,zoom:S},g())}}}0&&(module.exports={createThemePreview});