@runtypelabs/persona 4.29.0 → 4.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.cjs +3 -3
- package/dist/approval-ui.d.cts +1 -1
- package/dist/approval-ui.d.ts +1 -1
- package/dist/approval-ui.js +3 -3
- package/dist/artifacts-ui.d.cts +2 -2
- package/dist/artifacts-ui.d.ts +2 -2
- package/dist/chunk-B1-_pp-Y.js +4 -0
- package/dist/{chunk-DjOvgFsn.js → chunk-BcLIgi1h.js} +1 -1
- package/dist/chunk-Bm2-bemv.js +1 -0
- package/dist/chunk-BvhTpG6k.js +1 -0
- package/dist/chunk-Csks3Qw1.js +1 -0
- package/dist/chunk-D5B629Mj.js +1 -0
- package/dist/chunk-DGlFKA0r.js +9 -0
- package/dist/chunk-DO9_WSpy.js +1 -0
- package/dist/chunk-DTDHeUsG.js +1 -0
- package/dist/chunk-DjFpGFGA.js +1 -0
- package/dist/{chunk-dRBlrLd7.js → chunk-DtmtfIkd.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/client-stream.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{composer-input-D3sB8_P_.d.cts → composer-input-B0P4OtNi.d.cts} +1 -1
- package/dist/{composer-input-D3sB8_P_.d.ts → composer-input-B0P4OtNi.d.ts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.cts → context-mention-manager-DmLI_RM6.d.cts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.ts → context-mention-manager-DmLI_RM6.d.ts} +1 -1
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-Dsw66XqE.d.cts → defaults-DVo1wbZs.d.cts} +1 -1
- package/dist/{defaults-Dsw66XqE.d.ts → defaults-DVo1wbZs.d.ts} +1 -1
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.cts → fallback-speech-engine-BMnlmKnY.d.cts} +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.ts → fallback-speech-engine-BMnlmKnY.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +56 -56
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.global.js +2 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +38 -38
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.cts → markdown-parsers-loader-CeovcyYf.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.ts → markdown-parsers-loader-CeovcyYf.d.ts} +1 -1
- package/dist/{preview-DKKpfTo7.d.cts → preview-Bkb4UrQC.d.cts} +2 -2
- package/dist/{preview-DKKpfTo7.d.ts → preview-Bkb4UrQC.d.ts} +2 -2
- package/dist/session-actions.js +1 -1
- package/dist/{session-DleMr9dZ.d.ts → session-iLyKipoM.d.cts} +21 -9
- package/dist/{session-DleMr9dZ.d.cts → session-iLyKipoM.d.ts} +21 -9
- package/dist/session-reconnect.cjs +1 -1
- package/dist/session-reconnect.d.cts +8 -2
- package/dist/session-reconnect.d.ts +8 -2
- package/dist/session-reconnect.js +1 -1
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +61 -61
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +40 -40
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{types-oAZ1VReS.d.cts → types-BuDirJkQ.d.cts} +35 -3
- package/dist/{types-oAZ1VReS.d.ts → types-BuDirJkQ.d.ts} +35 -3
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +10 -4
- package/dist/voice-runtime.d.ts +10 -4
- package/dist/voice-runtime.js +5 -5
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.cts → webmcp-runtime-entry-CXLjRt1k.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.ts → webmcp-runtime-entry-CXLjRt1k.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/client-approve.test.ts +17 -1
- package/src/client-resume.ts +15 -3
- package/src/client.interrupt.test.ts +21 -0
- package/src/client.ts +24 -4
- package/src/components/activity-row.ts +3 -2
- package/src/components/approval-actions.test.ts +8 -0
- package/src/components/approval-actions.ts +6 -2
- package/src/components/approval-bubble.test.ts +14 -0
- package/src/components/approval-bubble.ts +8 -1
- package/src/components/tool-bubble.ts +8 -5
- package/src/generated/runtype-openapi-contract.ts +1 -1
- package/src/resume-dedupe-local-only.test.ts +273 -0
- package/src/runtime/persist-state.test.ts +86 -0
- package/src/session-actions.ts +20 -6
- package/src/session-reconnect.ts +18 -1
- package/src/session.restored-browser-tools.test.ts +272 -0
- package/src/session.ts +176 -29
- package/src/session.voice.test.ts +169 -0
- package/src/styles/widget.css +4 -2
- package/src/types.ts +37 -2
- package/src/ui.restored-browser-tools.test.ts +128 -0
- package/src/ui.ts +32 -18
- package/src/utils/formatting.test.ts +9 -1
- package/src/utils/formatting.ts +4 -0
- package/src/utils/local-only-message.ts +15 -0
- package/src/utils/restored-browser-state.ts +50 -0
- package/src/utils/storage.ts +12 -1
- package/src/utils/voice-prior-tool-results.ts +37 -0
- package/src/voice/runtype-voice-provider.ts +13 -8
- package/src/voice/session-voice-wiring.ts +1 -2
- package/src/voice/voice-delegation.ts +10 -3
- package/src/voice/voice.test.ts +38 -2
- package/dist/chunk-B6zZsT6F.js +0 -1
- package/dist/chunk-CIVsNcrk.js +0 -1
- package/dist/chunk-CKdlNyzM.js +0 -9
- package/dist/chunk-DbhxjyOB.js +0 -4
- package/dist/chunk-DsdqLStH.js +0 -1
- package/dist/chunk-GIqbL2Eg.js +0 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("lucide"),d=require("marked"),f=require("dompurify");f=l(f,1);let p=require("partial-json"),m=require("idiomorph");var h,g=o((()=>{h=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i}}));function _(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=v(t)&&v(r)?_(t,r):r}return n}var v,y=o((()=>{v=e=>typeof e==`object`&&!!e&&!Array.isArray(e)}));function b(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return O(n)?b(n,r):[r]})}function x(e,t){for(let n of t.split(`.`)){if(!O(e)||!Object.prototype.hasOwnProperty.call(e,n))return`absent`;if(e=e[n],e===void 0)return`clear`}return`explicit`}function S(e,t){return e?.[D]??t.filter(t=>x(e,t)===`explicit`)}function C(e,t){return Object.defineProperty(e,D,{value:t,enumerable:!0,configurable:!0}),e}function w(e,t,n){return C(e,S(t,b(n)))}function T(e,t,n){let r=t[D];if(r)return r;let i=new Set(S(e,n));for(let e of n){let n=x(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function E(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!O(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var D,O,k=o((()=>{D=Symbol(`persona.defaultsProvenance`),O=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),A,j,M,ee,N,P,F,te,ne=o((()=>{A=Symbol(`persona.panelAliasProvenance`),j=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),M=(e,t)=>j(e,t)&&e[t]!==void 0,ee=e=>({launcherWidth:M(e?.launcher,`width`),legacyLauncherWidth:M(e,`launcherWidth`),sidebarWidth:M(e?.launcher,`sidebarWidth`),dockWidth:M(e?.launcher?.dock,`width`)}),N=e=>{let t=e?.[A];return t?{...t}:ee(e)},P=(e,t)=>(Object.defineProperty(e,A,{value:t,enumerable:!0,configurable:!0}),e),F=(e,t)=>P(e,N(t)),te=(e,t)=>{let n=t[A];if(n)return{...n};let r=N(e);return j(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),j(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(j(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),j(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),j(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:j(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)}})),I=o((()=>{}));function re(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function ie(e){let t=re(e)===`v5`?me:fe;return _(de,t)}function ae(e,t){if(e||t)return e?t?_(e,t):e:t}function oe(e){let t=ie(e);return e?w(F({...t,...e,theme:ae(t.theme,e.theme),darkTheme:ae(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,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),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,me):w(F(t),void 0,me)}var se,ce,le,L,R,ue,de,fe,pe,me,he=o((()=>{y(),k(),ne(),I(),se=`min(440px, calc(100vw - 24px))`,ce=`40px`,le=`How can I help...`,L={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},R={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},ue={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:se,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:ce,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)`},de={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:ue,copy:{inputPlaceholder:le,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,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:L,reasoningDisplay:R,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,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},fe={},pe={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},me={launcher:pe,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`}}}},ie()})),z,ge,B,V,H=o((()=>{z=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},ge=()=>document.createDocumentFragment(),B=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},V=(...e)=>e.filter(Boolean).join(` `)})),_e,ve=o((()=>{_e=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,r=null,i=null,a=null;return{setLoader:e=>{r=e,n&&(i=null,a=null)},load:()=>i?Promise.resolve(i):a||(a=(r??t)().then(e=>(i=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{i=e},getSync:()=>i}}})),ye=/* @__PURE__ */ s({EXTRA_LUCIDE_ICONS:()=>be}),be,xe=o((()=>{be={user:u.User,mail:u.Mail,phone:u.Phone,calendar:u.Calendar,clock:u.Clock,building:u.Building,"map-pin":u.MapPin,lock:u.Lock,key:u.Key,"credit-card":u.CreditCard,hash:u.Hash,globe:u.Globe,link:u.Link,"circle-check":u.CircleCheck,"circle-x":u.CircleX,"triangle-alert":u.TriangleAlert,info:u.Info,ban:u.Ban,shield:u.Shield,house:u.House,"pen-line":u.PenLine,save:u.Save,share:u.Share,funnel:u.Funnel,settings:u.Settings,"rotate-cw":u.RotateCw,"shopping-cart":u.ShoppingCart,"shopping-bag":u.ShoppingBag,package:u.Package,truck:u.Truck,tag:u.Tag,gift:u.Gift,receipt:u.Receipt,wallet:u.Wallet,store:u.Store,"dollar-sign":u.DollarSign,percent:u.Percent,play:u.Play,pause:u.Pause,"volume-x":u.VolumeX,camera:u.Camera,image:u.Image,film:u.Film,headphones:u.Headphones,"message-circle":u.MessageCircle,bell:u.Bell,heart:u.Heart,"eye-off":u.EyeOff,bookmark:u.Bookmark,"calendar-days":u.CalendarDays,timer:u.Timer,folder:u.Folder,"folder-open":u.FolderOpen,files:u.Files,"chart-column":u.ChartColumn,sparkles:u.Sparkles,zap:u.Zap,sun:u.Sun,moon:u.Moon,flag:u.Flag,lightbulb:u.Lightbulb,monitor:u.Monitor,smartphone:u.Smartphone}})),Se,Ce,we,Te,Ee=o((()=>{ve(),{setLoader:Se,load:Ce}=_e({fallbackImport:()=>Promise.resolve().then(()=>(xe(),ye))}),we=Se,Te=Ce})),De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,U,ze=o((()=>{g(),Ee(),De={activity:u.Activity,"arrow-down":u.ArrowDown,"arrow-up":u.ArrowUp,"arrow-up-right":u.ArrowUpRight,bot:u.Bot,"chevron-down":u.ChevronDown,"chevron-up":u.ChevronUp,"chevron-right":u.ChevronRight,"chevron-left":u.ChevronLeft,check:u.Check,clipboard:u.Clipboard,"clipboard-copy":u.ClipboardCopy,"code-xml":u.CodeXml,copy:u.Copy,file:u.File,"file-code":u.FileCode,"file-spreadsheet":u.FileSpreadsheet,"file-text":u.FileText,"image-plus":u.ImagePlus,loader:u.Loader,"loader-circle":u.LoaderCircle,mic:u.Mic,paperclip:u.Paperclip,quote:u.Quote,"refresh-cw":u.RefreshCw,search:u.Search,send:u.Send,"shield-alert":u.ShieldAlert,"shield-check":u.ShieldCheck,"shield-x":u.ShieldX,square:u.Square,"thumbs-down":u.ThumbsDown,"thumbs-up":u.ThumbsUp,upload:u.Upload,"volume-2":u.Volume2,x:u.X,"at-sign":u.AtSign,"arrow-left":u.ArrowLeft,"arrow-right":u.ArrowRight,"external-link":u.ExternalLink,ellipsis:u.Ellipsis,"ellipsis-vertical":u.EllipsisVertical,menu:u.Menu,"panel-left":u.PanelLeft,plus:u.Plus,minus:u.Minus,pencil:u.Pencil,trash:u.Trash,"trash-2":u.Trash2,download:u.Download,maximize:u.Maximize,minimize:u.Minimize,"message-square":u.MessageSquare,star:u.Star,eye:u.Eye,history:u.History},Oe=/* @__PURE__ */ `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`.split(`.`),ke=new Map(Object.entries(De)),Ae=/* @__PURE__ */ new Set,je=!1,Me=/* @__PURE__ */ new Set,Ne=e=>{let t=[...Me];e&&Me.clear();for(let e of t)try{e()}catch{}},Pe=e=>je?()=>{}:(Me.add(e),()=>{Me.delete(e)}),Fe=()=>{let e=0;for(let t of[...Ae]){let n=ke.get(t.name);if(!n)continue;Ae.delete(t),e++;let r=h(n,t.size,t.color,t.strokeWidth);if(r)for(t.el.removeAttribute(`data-persona-icon-pending`);r.firstChild;)t.el.appendChild(r.firstChild)}return e},Ie=!1,Le=()=>{Te().then(e=>{if(!je){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))ke.has(t)||ke.set(t,n);je=!0,Fe(),Ne(!0)}}).catch(e=>{Ie=!0,console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},Re=(e,t,n)=>{let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`width`,String(e)),r.setAttribute(`height`,String(e)),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t),r.setAttribute(`stroke-width`,String(n)),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-icon-pending`,`true`),r},U=(e,t=24,n=`currentColor`,r=2)=>{let i=ke.get(e);if(i)return h(i,t,n,r);if(Oe.includes(e)){Ie&&=!1;let i=Re(t,n,r);if(Ae.size>=500){let e=Ae.values().next().value;e&&Ae.delete(e)}return Ae.add({el:i,name:e,size:t,color:n,strokeWidth:r}),Le(),i}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}}));he(),ze(),H(),g();const Be=[`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`],Ve=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),He=(e,t)=>{let n=z(`div`,[`persona-message-bubble`,e,...Be].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},Ue=e=>{let t=z(`button`,e.expandable?`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`:`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`);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},We=(e,t,n)=>{e.innerHTML=``;let r=h(t?u.ChevronUp:u.ChevronDown,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},Ge=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=z(`div`,`persona-flex persona-items-center`);We(r,n.expanded,n.iconColor);let i=z(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},Ke=e=>{let t=z(`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?.();Ve(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},qe=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&We(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`},Je=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&We(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};g(),H();function Ye(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?L:R,...e?.future?.v5Defaults===!0?me.features?.[n]:{},...e?.features?.[n]}}}}function Xe(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function Ze(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 Qe(e,t,n,r){if(Xe(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=z(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let d={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,"awaiting-approval":`clock`},f=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,p=f?U(f,16,`currentColor`,2):c===`pending`?h(u.Circle,16,`currentColor`,2):c===`awaiting-approval`?h(u.Clock,16,`currentColor`,2):U(d[c],16,`currentColor`,2);p&&l.appendChild(p),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let m=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,g=n.features?.[m]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((g===`always`||g===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=z(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:Ze(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let _=e.querySelector(`:scope > .persona-border-t`);return _?.classList.add(`persona-activity-body`),_&&(_.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,_.id)),e}function $e(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function et(e,t,n,r){let i=z(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=z(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=z(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),Ge(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=z(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),Qe(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}var tt,nt,rt,it=o((()=>{tt=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),nt=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=tt(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},rt=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}}));it();function at(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function ot(e){return e?.type===`runtype`||e?.type===`custom`}const W=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function st(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:W()}catch{return!1}}var ct=/* @__PURE__ */ s({DOMPurify:()=>f.default,Marked:()=>d.Marked}),G=o((()=>{})),K,q,lt,ut,dt,J,ft,pt,Y,mt,ht=o((()=>{ve(),{setLoader:K,load:q,provide:lt,getSync:ut}=_e({fallbackImport:()=>Promise.resolve().then(()=>(G(),ct))}),dt=/* @__PURE__ */ new Set,J=()=>{let e=[...dt];dt.clear();for(let t of e)try{t()}catch{}},ft=()=>{let e=ut();return e?Promise.resolve(e):q().then(e=>(J(),e))},pt=e=>ut()?()=>{}:(dt.add(e),()=>{dt.delete(e)}),Y=e=>{lt(e),J()},mt=ut})),gt,_t,vt,yt,bt=o((()=>{ht(),gt=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},_t=e=>{let t=null;return n=>{let r=mt();if(!r)return yt(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=gt(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},vt=e=>e?_t({markedOptions:e.options,renderer:e.renderer}):_t(),_t(),yt=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)})),xt,St,Ct,wt,Tt=o((()=>{bt(),ht(),xt={ALLOWED_TAGS:/* @__PURE__ */ `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`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `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`.split(`.`)},St=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ct=()=>{let e=null;return t=>{let n=mt();if(!n)return yt(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!St.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,xt)}},wt=e=>e===!1?null:typeof e==`function`?e:Ct()}));Tt();const Et=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Dt=e=>e.includes(`|`),Ot=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},kt=e=>`| ${e.join(` | `)} |`,At=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,jt=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),Mt=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
2
|
-
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!
|
|
3
|
-
`):e},
|
|
4
|
-
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("lucide"),d=require("marked"),f=require("dompurify");f=l(f,1);let p=require("partial-json"),m=require("idiomorph");function h(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${_(t.join(``))}`}function g(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function _(e){return`${g(e,0).toString(36)}.${g(e,2654435761).toString(36)}`}var v,y,b,x,S,C,w,T,E=o((()=>{v=`webmcp:`,y=/* @__PURE__ */ new Map,b=e=>{y.clear();for(let t of e){let e=t.title?.trim();e&&y.set(t.name,e)}},x=e=>y.get(C(e)),S=null,C=e=>e.startsWith(`webmcp:`)?e.slice(7):e,w=e=>e.startsWith(v),T=()=>S?S():import(`@mcp-b/webmcp-polyfill`)}));function D(e){return e.toolType===`webmcp`&&!e.executionId}function O(e){let t=e.approval,n=t?.status===`pending`&&D(t),r=!1,i=t=>!t.name||!w(t.name)||(r=!0,!(t.status!==`complete`||e.agentMetadata?.awaitingLocalTool===!0&&t.result===void 0&&t.success===void 0))?t:{...t,status:`complete`,interrupted:!0,success:!1,error:k,approvalStatus:t.approvalStatus===`pending`?`timeout`:t.approvalStatus,startedAt:t.completedAt===void 0?void 0:t.startedAt},a=e.toolCall?i(e.toolCall):void 0,o=e.tools?.map(i);return{...e,streaming:r||n?!1:e.streaming,...n?{approval:{...t,status:`timeout`,interrupted:!0}}:{},...a?{toolCall:a}:{},...o?{tools:o}:{},...r&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}var k,A=o((()=>{E(),k=`The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.`})),j,ee=o((()=>{j=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i}}));function M(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=N(t)&&N(r)?M(t,r):r}return n}var N,P=o((()=>{N=e=>typeof e==`object`&&!!e&&!Array.isArray(e)}));function te(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return ce(n)?te(n,r):[r]})}function ne(e,t){for(let n of t.split(`.`)){if(!ce(e)||!Object.prototype.hasOwnProperty.call(e,n))return`absent`;if(e=e[n],e===void 0)return`clear`}return`explicit`}function re(e,t){return e?.[se]??t.filter(t=>ne(e,t)===`explicit`)}function F(e,t){return Object.defineProperty(e,se,{value:t,enumerable:!0,configurable:!0}),e}function ie(e,t,n){return F(e,re(t,te(n)))}function ae(e,t,n){let r=t[se];if(r)return r;let i=new Set(re(e,n));for(let e of n){let n=ne(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function oe(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!ce(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var se,ce,le=o((()=>{se=Symbol(`persona.defaultsProvenance`),ce=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),ue,de,I,fe,pe,me,he,ge,_e=o((()=>{ue=Symbol(`persona.panelAliasProvenance`),de=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),I=(e,t)=>de(e,t)&&e[t]!==void 0,fe=e=>({launcherWidth:I(e?.launcher,`width`),legacyLauncherWidth:I(e,`launcherWidth`),sidebarWidth:I(e?.launcher,`sidebarWidth`),dockWidth:I(e?.launcher?.dock,`width`)}),pe=e=>{let t=e?.[ue];return t?{...t}:fe(e)},me=(e,t)=>(Object.defineProperty(e,ue,{value:t,enumerable:!0,configurable:!0}),e),he=(e,t)=>me(e,pe(t)),ge=(e,t)=>{let n=t[ue];if(n)return{...n};let r=pe(e);return de(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),de(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(de(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),de(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),de(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:de(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)}})),ve=o((()=>{}));function L(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function R(e){let t=L(e)===`v5`?ke:De;return M(Ee,t)}function z(e,t){if(e||t)return e?t?M(e,t):e:t}function ye(e){let t=R(e);return e?ie(he({...t,...e,theme:z(t.theme,e.theme),darkTheme:z(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,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),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,ke):ie(he(t),void 0,ke)}var be,xe,Se,Ce,we,Te,Ee,De,Oe,ke,Ae=o((()=>{P(),le(),_e(),ve(),be=`min(440px, calc(100vw - 24px))`,xe=`40px`,Se=`How can I help...`,Ce={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},we={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Te={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:be,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:xe,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)`},Ee={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:Te,copy:{inputPlaceholder:Se,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,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:Ce,reasoningDisplay:we,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,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},De={},Oe={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},ke={launcher:Oe,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`}}}},R()})),B,je,V,Me,H=o((()=>{B=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},je=()=>document.createDocumentFragment(),V=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},Me=(...e)=>e.filter(Boolean).join(` `)})),Ne,Pe=o((()=>{Ne=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,r=null,i=null,a=null;return{setLoader:e=>{r=e,n&&(i=null,a=null)},load:()=>i?Promise.resolve(i):a||(a=(r??t)().then(e=>(i=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{i=e},getSync:()=>i}}})),Fe=/* @__PURE__ */ s({EXTRA_LUCIDE_ICONS:()=>Ie}),Ie,Le=o((()=>{Ie={user:u.User,mail:u.Mail,phone:u.Phone,calendar:u.Calendar,clock:u.Clock,building:u.Building,"map-pin":u.MapPin,lock:u.Lock,key:u.Key,"credit-card":u.CreditCard,hash:u.Hash,globe:u.Globe,link:u.Link,"circle-check":u.CircleCheck,"circle-x":u.CircleX,"triangle-alert":u.TriangleAlert,info:u.Info,ban:u.Ban,shield:u.Shield,house:u.House,"pen-line":u.PenLine,save:u.Save,share:u.Share,funnel:u.Funnel,settings:u.Settings,"rotate-cw":u.RotateCw,"shopping-cart":u.ShoppingCart,"shopping-bag":u.ShoppingBag,package:u.Package,truck:u.Truck,tag:u.Tag,gift:u.Gift,receipt:u.Receipt,wallet:u.Wallet,store:u.Store,"dollar-sign":u.DollarSign,percent:u.Percent,play:u.Play,pause:u.Pause,"volume-x":u.VolumeX,camera:u.Camera,image:u.Image,film:u.Film,headphones:u.Headphones,"message-circle":u.MessageCircle,bell:u.Bell,heart:u.Heart,"eye-off":u.EyeOff,bookmark:u.Bookmark,"calendar-days":u.CalendarDays,timer:u.Timer,folder:u.Folder,"folder-open":u.FolderOpen,files:u.Files,"chart-column":u.ChartColumn,sparkles:u.Sparkles,zap:u.Zap,sun:u.Sun,moon:u.Moon,flag:u.Flag,lightbulb:u.Lightbulb,monitor:u.Monitor,smartphone:u.Smartphone}})),Re,ze,Be,Ve,He=o((()=>{Pe(),{setLoader:Re,load:ze}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Le(),Fe))}),Be=Re,Ve=ze})),Ue,We,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,U,W=o((()=>{ee(),He(),Ue={activity:u.Activity,"arrow-down":u.ArrowDown,"arrow-up":u.ArrowUp,"arrow-up-right":u.ArrowUpRight,bot:u.Bot,"chevron-down":u.ChevronDown,"chevron-up":u.ChevronUp,"chevron-right":u.ChevronRight,"chevron-left":u.ChevronLeft,check:u.Check,clipboard:u.Clipboard,"clipboard-copy":u.ClipboardCopy,"code-xml":u.CodeXml,copy:u.Copy,file:u.File,"file-code":u.FileCode,"file-spreadsheet":u.FileSpreadsheet,"file-text":u.FileText,"image-plus":u.ImagePlus,loader:u.Loader,"loader-circle":u.LoaderCircle,mic:u.Mic,paperclip:u.Paperclip,quote:u.Quote,"refresh-cw":u.RefreshCw,search:u.Search,send:u.Send,"shield-alert":u.ShieldAlert,"shield-check":u.ShieldCheck,"shield-x":u.ShieldX,square:u.Square,"thumbs-down":u.ThumbsDown,"thumbs-up":u.ThumbsUp,upload:u.Upload,"volume-2":u.Volume2,x:u.X,"at-sign":u.AtSign,"arrow-left":u.ArrowLeft,"arrow-right":u.ArrowRight,"external-link":u.ExternalLink,ellipsis:u.Ellipsis,"ellipsis-vertical":u.EllipsisVertical,menu:u.Menu,"panel-left":u.PanelLeft,plus:u.Plus,minus:u.Minus,pencil:u.Pencil,trash:u.Trash,"trash-2":u.Trash2,download:u.Download,maximize:u.Maximize,minimize:u.Minimize,"message-square":u.MessageSquare,star:u.Star,eye:u.Eye,history:u.History},We=/* @__PURE__ */ `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`.split(`.`),Ge=new Map(Object.entries(Ue)),Ke=/* @__PURE__ */ new Set,qe=!1,Je=/* @__PURE__ */ new Set,Ye=e=>{let t=[...Je];e&&Je.clear();for(let e of t)try{e()}catch{}},Xe=e=>qe?()=>{}:(Je.add(e),()=>{Je.delete(e)}),Ze=()=>{let e=0;for(let t of[...Ke]){let n=Ge.get(t.name);if(!n)continue;Ke.delete(t),e++;let r=j(n,t.size,t.color,t.strokeWidth);if(r)for(t.el.removeAttribute(`data-persona-icon-pending`);r.firstChild;)t.el.appendChild(r.firstChild)}return e},Qe=!1,$e=()=>{Ve().then(e=>{if(!qe){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Ge.has(t)||Ge.set(t,n);qe=!0,Ze(),Ye(!0)}}).catch(e=>{Qe=!0,console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},et=(e,t,n)=>{let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`width`,String(e)),r.setAttribute(`height`,String(e)),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t),r.setAttribute(`stroke-width`,String(n)),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-icon-pending`,`true`),r},U=(e,t=24,n=`currentColor`,r=2)=>{let i=Ge.get(e);if(i)return j(i,t,n,r);if(We.includes(e)){Qe&&=!1;let i=et(t,n,r);if(Ke.size>=500){let e=Ke.values().next().value;e&&Ke.delete(e)}return Ke.add({el:i,name:e,size:t,color:n,strokeWidth:r}),$e(),i}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}}));A(),Ae(),W(),H(),ee();const G=[`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`],tt=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),nt=(e,t)=>{let n=B(`div`,[`persona-message-bubble`,e,...G].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},K=e=>{let t=B(`button`,e.expandable?`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`:`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`);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},q=(e,t,n)=>{e.innerHTML=``;let r=j(t?u.ChevronUp:u.ChevronDown,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},J=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=B(`div`,`persona-flex persona-items-center`);q(r,n.expanded,n.iconColor);let i=B(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},rt=e=>{let t=B(`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?.();tt(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},it=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&q(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`},at=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&q(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};ee(),H();function Y(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?Ce:we,...e?.future?.v5Defaults===!0?ke.features?.[n]:{},...e?.features?.[n]}}}}function ot(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function st(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 X(e,t,n,r){if(ot(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=t.toolCall?.interrupted?`interrupted`:s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=B(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let d={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,interrupted:`x`,"awaiting-approval":`clock`},f=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,p=f?U(f,16,`currentColor`,2):c===`pending`?j(u.Circle,16,`currentColor`,2):c===`awaiting-approval`?j(u.Clock,16,`currentColor`,2):U(d[c],16,`currentColor`,2);p&&l.appendChild(p),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let m=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,h=n.features?.[m]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((h===`always`||h===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=B(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:st(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let g=e.querySelector(`:scope > .persona-border-t`);return g?.classList.add(`persona-activity-body`),g&&(g.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,g.id)),e}function ct(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function lt(e,t,n,r){let i=B(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=B(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=B(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),J(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=B(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),X(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}var ut,dt,ft,pt=o((()=>{ut=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),dt=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=ut(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},ft=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}}));pt();function mt(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function ht(e){return e?.type===`runtype`||e?.type===`custom`}const gt=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function _t(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:gt()}catch{return!1}}var vt=/* @__PURE__ */ s({DOMPurify:()=>f.default,Marked:()=>d.Marked}),yt=o((()=>{})),bt,xt,St,Ct,wt,Tt,Et,Dt,Ot,kt,At=o((()=>{Pe(),{setLoader:bt,load:xt,provide:St,getSync:Ct}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(yt(),vt))}),wt=/* @__PURE__ */ new Set,Tt=()=>{let e=[...wt];wt.clear();for(let t of e)try{t()}catch{}},Et=()=>{let e=Ct();return e?Promise.resolve(e):xt().then(e=>(Tt(),e))},Dt=e=>Ct()?()=>{}:(wt.add(e),()=>{wt.delete(e)}),Ot=e=>{St(e),Tt()},kt=Ct})),jt,Mt,Nt,Pt,Ft=o((()=>{At(),jt=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Mt=e=>{let t=null;return n=>{let r=kt();if(!r)return Pt(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=jt(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Nt=e=>e?Mt({markedOptions:e.options,renderer:e.renderer}):Mt(),Mt(),Pt=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)})),Z,It,Lt,Rt,zt=o((()=>{Ft(),At(),Z={ALLOWED_TAGS:/* @__PURE__ */ `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`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `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`.split(`.`)},It=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Lt=()=>{let e=null;return t=>{let n=kt();if(!n)return Pt(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!It.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,Z)}},Rt=e=>e===!1?null:typeof e==`function`?e:Lt()}));zt();const Bt=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Vt=e=>e.includes(`|`),Ht=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},Ut=e=>`| ${e.join(` | `)} |`,Wt=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,Gt=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),Kt=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!Vt(r)||Bt.test(r)||!Bt.test(i))continue;let a=Ht(r).length;if(a<1)continue;let o=Wt(a);t[e+1]!==o&&(t[e+1]=o,n=!0);let s=e+2;for(;s<t.length;s++){let e=t[s];if(e.trim()===``||!Vt(e))break;let r=Ut(Gt(Ht(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
|
|
3
|
+
`):e},qt=`var(--persona-md-table-scroll-fade, 24px)`,Jt=/* @__PURE__ */ new WeakSet;function Yt(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function Xt(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:qt),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:qt)}function Zt(e){Jt.has(e)||(Jt.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&Xt(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(Xt)}function Qt(e){return e===`card`?`collapsed`:e}function $t(e){return e.split(`;`,1)[0].trim().toLowerCase()}function en(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if($t(e)===t)return{mode:Qt(r),selector:$t(e)};let r=`${t.split(`/`,1)[0]}/*`;for(let[e,t]of n)if($t(e)===r)return{mode:Qt(t),selector:r}}function tn(e,t){let n=e?.display,r=typeof n==`string`?{default:n}:n??{};if(t.file&&r.files){if(typeof r.files==`string`)return{mode:Qt(r.files),matchedBy:{type:`files`}};let e=t.file.mimeType?$t(t.file.mimeType):void 0,n=e?en(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:`mediaType`,mediaType:e,selector:n.selector}};if(r.files.default)return{mode:Qt(r.files.default),matchedBy:{type:`files`}}}let i=r.byKind?.[t.artifactType];if(i)return{mode:Qt(i),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byKind`}};let a=r.byType?.[t.artifactType];if(a)return{mode:Qt(a),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byType`}};let o=t.presentation?.preferredMode;return o?{mode:Qt(o),matchedBy:{type:`preferredMode`}}:r.default?{mode:Qt(r.default),matchedBy:{type:`default`}}:{mode:`panel`,matchedBy:{type:`personaDefault`}}}function nn(e,t){return tn(e,t).mode}function rn(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 an=o((()=>{})),on,sn,cn,ln,un,dn,fn,pn,mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn=o((()=>{on=e=>e.replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),sn=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)}},cn=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs===void 0?Math.max(0,t-n):e.durationMs)/1e3;return r<.1?`Thought for <0.1 seconds`:`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,``)} seconds`},ln=e=>e.status===`complete`?cn(e):e.status===`pending`?`Waiting`:``,un=(e,t)=>{let n=t?.durationMs??15e3,r=t?.chars??1200;return typeof e.durationMs==`number`?e.durationMs<n:(e.chunks??[]).join(``).length<r},dn=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())))/1e3;return t<.1?`Used tool for <0.1 seconds`:`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,``)} seconds`},fn=e=>e.status===`complete`?dn(e):`Using tool...`,pn=e=>{let t=e/1e3;return t<.1?`<0.1s`:t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,``)}s`},mn=e=>{if(e.interrupted&&e.duration===void 0&&e.durationMs===void 0&&(e.startedAt===void 0||e.completedAt===void 0))return``;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 pn(t)},hn=e=>{let t=e.durationMs===void 0?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return pn(t)},gn=(e,t,n)=>{if(!t)return n;let r=e.name?.trim()||`tool`,i=mn(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,i)},_n=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],i=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,o;for(;(o=i.exec(n))!==null;)o.index>a&&vn(r,n.slice(a,o.index),[]),o[1]===void 0?o[2]===void 0?o[3]!==void 0&&vn(r,o[3],[`dim`]):vn(r,o[2],[`italic`]):vn(r,o[1],[`bold`]),a=o.index+o[0].length;return a<n.length&&vn(r,n.slice(a),[]),r},vn=(e,t,n)=>{let r=t.split(`{duration}`);for(let t=0;t<r.length;t++)r[t]&&e.push({text:r[t],styles:n}),t<r.length-1&&e.push({text:`{duration}`,styles:n,isDuration:!0})},yn=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,`
|
|
5
5
|
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return t[1]}let n=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(n&&n[1])try{return n[1].replace(/\\n/g,`
|
|
6
|
-
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return n[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e===null?null:{text:e,raw:r};let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},_n=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},vn=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},yn=()=>{let e=gn();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)}},bn=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=(0,p.parse)(n,p.STR|p.OBJ);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?nn(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=nn(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},xn=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}})),Cn,Z,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr,yr,br,xr=o((()=>{H(),Cn=`ask_user_question`,Z=`data-persona-ask-sheet-for`,wn=`Other`,Tn=`Other…`,En=`Type your own answer here`,Dn=`Send`,On=`Next`,kn=`Back`,An=`Submit all`,jn=`Skip`,Mn=3,Nn=`data-ask-current-index`,Pn=`data-ask-question-count`,Fn=`data-ask-answers`,In=`data-ask-grouped`,Ln=`data-ask-layout`,Rn=e=>e.layout===`pills`?`pills`:`rows`,zn=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,Bn=!1,Vn=e=>e.replace(/["\\]/g,`\\$&`),Hn=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,Un=e=>e?.features?.askUserQuestion??{},Wn=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=(0,p.parse)(e,p.STR|p.OBJ|p.ARR);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},Gn=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!Bn&&(Bn=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Kn=e=>Gn(e)[0]??null,qn=(e,t)=>Gn(e)[t]??null,Jn=(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))},Yn=(e,t,n)=>{if(e!==`rows`)return null;let r=z(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=z(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=z(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},Xn=(e,t,n,r)=>{let i=z(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=z(`span`,`persona-ask-row-content`),o=z(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=z(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=Yn(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},Zn=e=>{let t=z(`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 t.setAttribute(`aria-hidden`,`true`),t},Qn=(e,t,n,r)=>{let i=z(`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`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<Mn;e++)i.appendChild(Zn(r));return i}if(o.forEach((e,t)=>{i.appendChild(Xn(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?wn:Tn;if(r===`rows`){let n=z(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=z(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??En,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=Yn(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=z(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},$n=(e,t)=>{let n=z(`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`);n.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??En,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=z(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??Dn,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},er=e=>{let t=z(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=z(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??Dn,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},tr=(e,t,n)=>{let r=z(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=z(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??kn,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=z(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=z(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??jn,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=z(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??An:n.nextLabel??On,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},nr=e=>{let t=e.getAttribute(Fn);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},rr=(e,t)=>{e.setAttribute(Fn,JSON.stringify(t))},ir=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ar=(e,t)=>{e.setAttribute(Nn,String(Math.max(0,Math.floor(t))))},or=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(In)===`true`,cr=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},lr=(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)))},ur=(e,t)=>{let{payload:n}=Wn(t),r=Gn(n),i=nr(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},dr=e=>{let t=nr(e)[ir(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},fr=e=>{if(!sr(e))return;let t=nr(e)[ir(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},pr=(e,t,n)=>{let r=Un(n),i=zn(e),{payload:a,complete:o}=Wn(t),s=sr(e),c=ir(e),l=or(e),u=s?qn(a,c):Kn(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=Qn(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith($n(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(er(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=tr(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();dr(e),fr(e)},mr=(e,t,n)=>{let r=Un(t),i=Rn(r),a=e.toolCall.id,o=Gn(n),s=Math.max(1,o.length),c=s>1,l=cr(e,o),u=c?lr(e,s):0,d=z(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(Z,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(Pn,String(s)),d.setAttribute(Nn,String(u)),d.setAttribute(In,c?`true`:`false`),d.setAttribute(Ln,i),rr(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),Jn(d,r);let f=z(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=z(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=z(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=z(`div`,i===`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 h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild($n(r,i)),pr(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},hr=(e,t,n)=>{let{payload:r}=Wn(t),i=Math.max(1,Gn(r).length);i>or(e)&&(e.setAttribute(Pn,String(i)),i>1&&!sr(e)&&e.setAttribute(In,`true`)),pr(e,t,n)},gr=(e,t,n)=>{if(!n||!Hn(e)||Un(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Z}]`).forEach(e=>{e.getAttribute(Z)!==r&&e.remove()});let i=n.querySelector(`[${Z}="${Vn(r)}"]`);if(i){hr(i,e,t);return}let{payload:a}=Wn(e),o=mr(e,t,a);n.appendChild(o)},_r=(e,t)=>{if(!e)return;let n=t?`[${Z}="${Vn(t)}"]`:`[${Z}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},vr=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),yr=(e,t)=>{let n=nr(e),r=ir(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,rr(e,n),dr(e),fr(e)},br=(e,t,n,r)=>{let i=or(e),a=Math.max(0,Math.min(i-1,r));ar(e,a),pr(e,t,n)}})),Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr=o((()=>{Sr=`suggest_replies`,Cr={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},wr={name:Sr,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:Cr,origin:`sdk`,annotations:{readOnlyHint:!0}},Tr=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Er=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Dr=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 r=n.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Or=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(!Er(n))continue;let r=Dr(n.toolCall?.args);return r.length>0?r:null}return null},kr=/* @__PURE__ */ new Set,Ar=(e,t,n)=>{let r=`${e}:${t}:${n}`;kr.has(r)||(kr.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},jr=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&Ar(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),Nr,Pr,Fr,Ir=o((()=>{xr(),Mr(),Nr={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,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},Pr={name:Cn,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:Nr,origin:`sdk`,annotations:{readOnlyHint:!0}},Fr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Pr),jr(e).expose&&t.push(wr),t}})),Lr,Rr,zr,Br=o((()=>{Lr={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},Rr=1e5,zr=100001}));async function Vr(e,t,n){let r={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(r,await e.getHeaders());let i={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},a=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:r,body:JSON.stringify({...n,...i})}),o=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return a(o);let{sessionId:s}=await e.initSession(),c=await a(`/v1/client/approve`,{sessionId:s});if(c.status===404){let e=await c.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return a(o)}return c}async function Hr(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o),i&&o){let t=[...Fr(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var Ur=o((()=>{Ir(),Br()})),Wr=/* @__PURE__ */ s({preferFinalStructuredContent:()=>Kr,resolveApproval:()=>Vr,resumeFlow:()=>Hr,streamResponse:()=>Jr});function Gr(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function Kr(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let i=Yr(n);if(!Yr(r))return e;if(!i||r===n||r.startsWith(n))return t;let a=_n(e);return _n(t)!==null&&a===null?t:e}async function qr(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function Jr(e,t,n,r,i){let a=t.getReader(),o=new TextDecoder,s=``,c=Date.now(),l=0,u=()=>c+l++,d=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},f=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},p=e=>{f(e)&&n({type:`message`,message:d(e)})},m=null,h=null,g={current:null},_={current:null},v=null,y=``,b=/* @__PURE__ */ new Map,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map,T=r,E=!1,D=()=>{if(m)return m;let e,t=``,n=v;return!E&&T?(e=T,E=!0,t=i??``):e=T&&n?`${T}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u()},p(m),m},O=e=>{let t=C.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:u(),reasoning:{id:e,status:`streaming`,chunks:[]}};return C.set(e,n),p(n),n},k=/* @__PURE__ */ new Set,A=/* @__PURE__ */ new Map,j=/* @__PURE__ */ new Set,M=/* @__PURE__ */ new Map,ee=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},N=e=>{let t=w.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:u(),toolCall:{id:e,status:`pending`}};return w.set(e,n),p(n),n},P=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},F=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},te=/* @__PURE__ */ new Map,ne=/* @__PURE__ */ new Map,I=(e,t)=>{let n=F(t),r=Kr(ne.get(e.id),n);e.rawContent=r;let i=te.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(n.trim().length===0||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{if(i){let e=i.close?.();e instanceof Promise&&e.catch(()=>{})}te.delete(e.id),ne.delete(e.id),e.streaming=!1,p(e)};if(!i){a(n),o();return}let s=_n(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},re=null,ie=(t,n,r,i)=>{t.rawContent=n,te.has(t.id)||te.set(t.id,e.createStreamParser());let a=te.get(t.id),o=n.trim().startsWith(`{`)||n.trim().startsWith(`[`);if(o&&ne.set(t.id,n),a.__isPlainTextParser===!0){t.content=i===void 0?t.content+r:n,ne.delete(t.id),te.delete(t.id),t.rawContent=void 0,p(t);return}let s=a.processChunk(n);if(s instanceof Promise)s.then(e=>{let a=typeof e==`string`?e:e?.text??null;a!==null&&a.trim()!==``?(t.content=a,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,ne.delete(t.id),te.delete(t.id),t.rawContent=void 0,p(t))}).catch(()=>{t.content=i===void 0?t.content+r:n,ne.delete(t.id),te.delete(t.id),t.rawContent=void 0,p(t)});else{let e=typeof s==`string`?s:s?.text??null;e!==null&&e.trim()!==``?(t.content=e,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,ne.delete(t.id),te.delete(t.id),t.rawContent=void 0,p(t))}},ae=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,p(e);return}let r=ne.get(e.id)??F(n);e.rawContent=r;let i=te.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=_n(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,te.delete(e.id),ne.delete(e.id),p(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:ne.has(e.id)||(e.content=F(n));let t=te.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),te.delete(e.id)}ne.delete(e.id),e.streaming=!1,p(e)}},oe=(e,t,n)=>{let r=x.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return x.set(e,i),p(i),i},se=[],ce,le=/* @__PURE__ */ new Map,L=0,R=`agent`,ue=!1,de=null,fe=null,pe=e.config().iterationDisplay??`separate`;for(ce=()=>{for(let t=0;t<se.length;t++){let r=se[t];if(!ue&&R!==`flow`&&typeof r.stepType==`string`&&(R=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t),oe(e,t,`reasoning`);continue}let n=r.id,i=O(n);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,p(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),p(t));continue}let t=r.id,n=O(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,p(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,p(t)}b.delete(e),x.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!C.get(t)&&(n||r.scope===`loop`)&&O(t);let i=C.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,p(i)}}else if(r.type===`tool_start`){m&&=(m.streaming=!1,p(m),null),typeof r.iteration==`number`&&(L=r.iteration);let e=r.toolCallId,t=r.toolName;if(ee(t)){k.add(e);continue}let n=N(e),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??P(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,r.executionId&&(n.agentMetadata={executionId:r.executionId,iteration:r.iteration}),p(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(k.has(e))continue;let t=N(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:L}),p(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(k.has(e)){k.delete(e);continue}let t=N(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:r.iteration??L}),p(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${u()}`,n=N(t),i=r.toolName,a=r.origin===`webmcp`&&!Kt(i)?`webmcp:${i}`:i,o=Kt(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??P(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},p(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t);continue}let n=m;n&&(R===`flow`?(ae(n),re=n):(n.streaming=!1,p(n)),m=null),v=typeof r.id==`string`?r.id:v,y=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?b.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(S.get(e)??``)+n;if(S.set(e,i),i.trim()===``)continue;let a=oe(e,t);a.agentMetadata={...a.agentMetadata,executionId:r.executionId,parentToolId:t},ie(a,i,n,void 0);continue}if(v=typeof r.id==`string`?r.id:v,R===`flow`){let e=typeof r.delta==`string`?r.delta:``;if(y+=e,y.trim()===``)continue;let t=D();t.agentMetadata={executionId:r.executionId,iteration:L},ie(t,y,e,void 0),h=t;continue}let n=typeof r.delta==`string`?r.delta:``;y+=n;let i=D();i.agentMetadata={executionId:r.executionId,iteration:L,turnId:de??void 0,agentName:fe?.agentName},ie(i,y,n,void 0),h=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)){let t=x.get(e);t&&ae(t),b.delete(e),S.delete(e),x.delete(e);continue}let t=m;t&&(R===`flow`?(ae(t),re=t):((t.content??``)===``&&typeof r.text==`string`&&(t.content=r.text),t.streaming=!1,p(t)),m=null),v=null,y=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`});continue}{let e=re;re=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(te.delete(e.id),ne.delete(e.id),e.streaming=!1,p(e)):I(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=D();t&&(r.stopReason=t),e?ae(r,n):(r.streaming=!1,p(r))}}continue}}else if(r.type===`execution_start`)R=r.kind===`flow`?`flow`:`agent`,ue=!0,R===`agent`&&(fe={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:L;if(e!==L){if(pe===`separate`&&e>1){let e=m;e&&(e.streaming=!1,p(e),m=null)}L=e}de=typeof r.id==`string`?r.id:null,h=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=w.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),p(t))}}else if(r.type===`tool_input_complete`){if(k.has(r.toolCallId))continue;let e=N(r.toolCallId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,p(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=m??h;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,p(t))}de===r.id&&(de=null)}else if(r.type===`media_start`){let e=String(r.id);le.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=le.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=le.get(e);le.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:Gr(e)})}}}if(l.length>0){let e=u(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:L}};p(n);let i=m;i&&(i.streaming=!1,p(i)),m=null,g.current=null}}else if(r.type===`execution_complete`){let e=m;e&&(r.kind===`flow`&&e.streaming!==!1?ae(e):(e.streaming=!1,p(e)),m=null),v=null,y=``,re=null,n({type:`status`,status:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${u()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:`pending`,agentId:fe?.agentId??`virtual`,executionId:r.executionId??fe?.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}:{}}};p(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:r.decision??`approved`,agentId:fe?.agentId??`virtual`,executionId:r.executionId??fe?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};p(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),M.set(i,{markdown:``,title:a,file:s}),!j.has(i)){j.add(i);let n=$t(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),rawContent:en(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};A.set(i,c),p(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=M.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=M.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=A.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=M.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}M.delete(e),p(t),A.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`})}}}se.length=0};;){let{done:t,value:r}=await a.read();if(t)break;s+=o.decode(r,{stream:!0});let i=s.split(`
|
|
6
|
+
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return n[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e===null?null:{text:e,raw:r};let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},bn=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},xn=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Sn=()=>{let e=yn();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)}},Cn=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=(0,p.parse)(n,p.STR|p.OBJ);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?on(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=on(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},wn=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}})),En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr=o((()=>{H(),En=`ask_user_question`,Dn=`data-persona-ask-sheet-for`,On=`Other`,kn=`Other…`,An=`Type your own answer here`,jn=`Send`,Mn=`Next`,Nn=`Back`,Pn=`Submit all`,Fn=`Skip`,In=3,Ln=`data-ask-current-index`,Rn=`data-ask-question-count`,zn=`data-ask-answers`,Bn=`data-ask-grouped`,Vn=`data-ask-layout`,Hn=e=>e.layout===`pills`?`pills`:`rows`,Un=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,Wn=!1,Gn=e=>e.replace(/["\\]/g,`\\$&`),Kn=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,qn=e=>e?.features?.askUserQuestion??{},Jn=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=(0,p.parse)(e,p.STR|p.OBJ|p.ARR);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},Yn=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!Wn&&(Wn=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Xn=e=>Yn(e)[0]??null,Zn=(e,t)=>Yn(e)[t]??null,Qn=(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))},$n=(e,t,n)=>{if(e!==`rows`)return null;let r=B(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=B(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=B(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},er=(e,t,n,r)=>{let i=B(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=B(`span`,`persona-ask-row-content`),o=B(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=B(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=$n(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},tr=e=>{let t=B(`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 t.setAttribute(`aria-hidden`,`true`),t},nr=(e,t,n,r)=>{let i=B(`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`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<In;e++)i.appendChild(tr(r));return i}if(o.forEach((e,t)=>{i.appendChild(er(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?On:kn;if(r===`rows`){let n=B(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=B(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??An,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=$n(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=B(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},rr=(e,t)=>{let n=B(`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`);n.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??An,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=B(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??jn,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},ir=e=>{let t=B(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=B(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??jn,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},ar=(e,t,n)=>{let r=B(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=B(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??Nn,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=B(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=B(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??Fn,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=B(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??Pn:n.nextLabel??Mn,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},or=e=>{let t=e.getAttribute(zn);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},sr=(e,t)=>{e.setAttribute(zn,JSON.stringify(t))},cr=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},lr=(e,t)=>{e.setAttribute(Ln,String(Math.max(0,Math.floor(t))))},ur=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},dr=e=>e.getAttribute(Bn)===`true`,fr=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},pr=(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)))},mr=(e,t)=>{let{payload:n}=Jn(t),r=Yn(n),i=or(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},hr=e=>{let t=or(e)[cr(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},gr=e=>{if(!dr(e))return;let t=or(e)[cr(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},_r=(e,t,n)=>{let r=qn(n),i=Un(e),{payload:a,complete:o}=Jn(t),s=dr(e),c=cr(e),l=ur(e),u=s?Zn(a,c):Xn(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=nr(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(rr(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(ir(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=ar(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();hr(e),gr(e)},vr=(e,t,n)=>{let r=qn(t),i=Hn(r),a=e.toolCall.id,o=Yn(n),s=Math.max(1,o.length),c=s>1,l=fr(e,o),u=c?pr(e,s):0,d=B(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(Dn,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(Rn,String(s)),d.setAttribute(Ln,String(u)),d.setAttribute(Bn,c?`true`:`false`),d.setAttribute(Vn,i),sr(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),Qn(d,r);let f=B(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=B(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=B(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=B(`div`,i===`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 h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(rr(r,i)),_r(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},yr=(e,t,n)=>{let{payload:r}=Jn(t),i=Math.max(1,Yn(r).length);i>ur(e)&&(e.setAttribute(Rn,String(i)),i>1&&!dr(e)&&e.setAttribute(Bn,`true`)),_r(e,t,n)},br=(e,t,n)=>{if(!n||!Kn(e)||qn(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Dn}]`).forEach(e=>{e.getAttribute(Dn)!==r&&e.remove()});let i=n.querySelector(`[${Dn}="${Gn(r)}"]`);if(i){yr(i,e,t);return}let{payload:a}=Jn(e),o=vr(e,t,a);n.appendChild(o)},xr=(e,t)=>{if(!e)return;let n=t?`[${Dn}="${Gn(t)}"]`:`[${Dn}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Sr=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),Cr=(e,t)=>{let n=or(e),r=cr(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,sr(e,n),hr(e),gr(e)},wr=(e,t,n,r)=>{let i=ur(e),a=Math.max(0,Math.min(i-1,r));lr(e,a),_r(e,t,n)}})),Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir=o((()=>{Er=`suggest_replies`,Dr={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},Or={name:Er,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:Dr,origin:`sdk`,annotations:{readOnlyHint:!0}},kr=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Ar=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,jr=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 r=n.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Mr=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(!Ar(n))continue;let r=jr(n.toolCall?.args);return r.length>0?r:null}return null},Nr=/* @__PURE__ */ new Set,Pr=(e,t,n)=>{let r=`${e}:${t}:${n}`;Nr.has(r)||(Nr.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Fr=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&Pr(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),Lr,Rr,zr,Br=o((()=>{Tr(),Ir(),Lr={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,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},Rr={name:En,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:Lr,origin:`sdk`,annotations:{readOnlyHint:!0}},zr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Rr),Fr(e).expose&&t.push(Or),t}})),Vr,Hr,Ur,Wr=o((()=>{Vr={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},Hr=1e5,Ur=100001}));async function Gr(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function Kr(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o,r?.assistantMessageId&&(l.assistantMessageId=r.assistantMessageId)),i&&o){let t=[...zr(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var qr=o((()=>{Br(),Wr()})),Jr=/* @__PURE__ */ s({preferFinalStructuredContent:()=>Xr,resolveApproval:()=>Gr,resumeFlow:()=>Kr,streamResponse:()=>Qr});function Yr(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function Xr(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let i=$r(n);if(!$r(r))return e;if(!i||r===n||r.startsWith(n))return t;let a=bn(e);return bn(t)!==null&&a===null?t:e}async function Zr(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function Qr(e,t,n,r,i){let a=t.getReader(),o=new TextDecoder,s=``,c=Date.now(),l=0,u=()=>c+l++,d=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},f=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},p=e=>{f(e)&&n({type:`message`,message:d(e)})},m=null,h=null,g={current:null},_={current:null},v=null,y=``,b=/* @__PURE__ */ new Map,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,T=/* @__PURE__ */ new Map,E=r,D=!1,O=()=>{if(m)return m;let e,t=``,n=v;return!D&&E?(e=E,D=!0,t=i??``):e=E&&n?`${E}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u()},p(m),m},k=e=>{let t=C.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:u(),reasoning:{id:e,status:`streaming`,chunks:[]}};return C.set(e,n),p(n),n},A=/* @__PURE__ */ new Set,j=/* @__PURE__ */ new Map,ee=/* @__PURE__ */ new Set,M=/* @__PURE__ */ new Map,N=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},P=e=>{let t=T.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:u(),toolCall:{id:e,status:`pending`}};return T.set(e,n),p(n),n},te=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},ne=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},re=/* @__PURE__ */ new Map,F=/* @__PURE__ */ new Map,ie=(e,t)=>{let n=ne(t),r=Xr(F.get(e.id),n);e.rawContent=r;let i=re.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(n.trim().length===0||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{if(i){let e=i.close?.();e instanceof Promise&&e.catch(()=>{})}re.delete(e.id),F.delete(e.id),e.streaming=!1,p(e)};if(!i){a(n),o();return}let s=bn(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ae=null,oe=(t,n,r,i)=>{t.rawContent=n,re.has(t.id)||re.set(t.id,e.createStreamParser());let a=re.get(t.id),o=n.trim().startsWith(`{`)||n.trim().startsWith(`[`);if(o&&F.set(t.id,n),a.__isPlainTextParser===!0){t.content=i===void 0?t.content+r:n,F.delete(t.id),re.delete(t.id),t.rawContent=void 0,p(t);return}let s=a.processChunk(n);if(s instanceof Promise)s.then(e=>{let a=typeof e==`string`?e:e?.text??null;a!==null&&a.trim()!==``?(t.content=a,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,F.delete(t.id),re.delete(t.id),t.rawContent=void 0,p(t))}).catch(()=>{t.content=i===void 0?t.content+r:n,F.delete(t.id),re.delete(t.id),t.rawContent=void 0,p(t)});else{let e=typeof s==`string`?s:s?.text??null;e!==null&&e.trim()!==``?(t.content=e,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,F.delete(t.id),re.delete(t.id),t.rawContent=void 0,p(t))}},se=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,p(e);return}let r=F.get(e.id)??ne(n);e.rawContent=r;let i=re.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=bn(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,re.delete(e.id),F.delete(e.id),p(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:F.has(e.id)||(e.content=ne(n));let t=re.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),re.delete(e.id)}F.delete(e.id),e.streaming=!1,p(e)}},ce=(e,t,n)=>{let r=x.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return x.set(e,i),p(i),i},le=[],ue,de=/* @__PURE__ */ new Map,I=0,fe=`agent`,pe=!1,me=null,he=null,ge=e.config().iterationDisplay??`separate`;for(ue=()=>{for(let t=0;t<le.length;t++){let r=le[t];if(!pe&&fe!==`flow`&&typeof r.stepType==`string`&&(fe=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t),ce(e,t,`reasoning`);continue}let n=r.id,i=k(n);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,p(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),p(t));continue}let t=r.id,n=k(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,p(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,p(t)}b.delete(e),x.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!C.get(t)&&(n||r.scope===`loop`)&&k(t);let i=C.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,p(i)}}else if(r.type===`tool_start`){m&&=(m.streaming=!1,p(m),null),typeof r.iteration==`number`&&(I=r.iteration);let e=r.toolCallId,t=r.toolName;if(N(t)){A.add(e);continue}let n=P(e),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??te(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,r.executionId&&(n.agentMetadata={executionId:r.executionId,iteration:r.iteration}),p(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(A.has(e))continue;let t=P(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:I}),p(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(A.has(e)){A.delete(e);continue}let t=P(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:r.iteration??I}),p(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${u()}`,n=P(t),i=r.toolName,a=r.origin===`webmcp`&&!w(i)?`webmcp:${i}`:i,o=w(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??te(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},p(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t);continue}let n=m;n&&(fe===`flow`?(se(n),ae=n):(n.streaming=!1,p(n)),m=null),v=typeof r.id==`string`?r.id:v,y=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?b.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(S.get(e)??``)+n;if(S.set(e,i),i.trim()===``)continue;let a=ce(e,t);a.agentMetadata={...a.agentMetadata,executionId:r.executionId,parentToolId:t},oe(a,i,n,void 0);continue}if(v=typeof r.id==`string`?r.id:v,fe===`flow`){let e=typeof r.delta==`string`?r.delta:``;if(y+=e,y.trim()===``)continue;let t=O();t.agentMetadata={executionId:r.executionId,iteration:I},oe(t,y,e,void 0),h=t;continue}let n=typeof r.delta==`string`?r.delta:``;y+=n;let i=O();i.agentMetadata={executionId:r.executionId,iteration:I,turnId:me??void 0,agentName:he?.agentName},oe(i,y,n,void 0),h=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)){let t=x.get(e);t&&se(t),b.delete(e),S.delete(e),x.delete(e);continue}let t=m;t&&(fe===`flow`?(se(t),ae=t):((t.content??``)===``&&typeof r.text==`string`&&(t.content=r.text),t.streaming=!1,p(t)),m=null),v=null,y=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`});continue}{let e=ae;ae=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(re.delete(e.id),F.delete(e.id),e.streaming=!1,p(e)):ie(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=O();t&&(r.stopReason=t),e?se(r,n):(r.streaming=!1,p(r))}}continue}}else if(r.type===`execution_start`)fe=r.kind===`flow`?`flow`:`agent`,pe=!0,fe===`agent`&&(he={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:I;if(e!==I){if(ge===`separate`&&e>1){let e=m;e&&(e.streaming=!1,p(e),m=null)}I=e}me=typeof r.id==`string`?r.id:null,h=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=T.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),p(t))}}else if(r.type===`tool_input_complete`){if(A.has(r.toolCallId))continue;let e=P(r.toolCallId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,p(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=m??h;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,p(t))}me===r.id&&(me=null)}else if(r.type===`media_start`){let e=String(r.id);de.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=de.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=de.get(e);de.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:Yr(e)})}}}if(l.length>0){let e=u(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:I}};p(n);let i=m;i&&(i.streaming=!1,p(i)),m=null,g.current=null}}else if(r.type===`execution_complete`){let e=m;e&&(r.kind===`flow`&&e.streaming!==!1?se(e):(e.streaming=!1,p(e)),m=null),v=null,y=``,ae=null,n({type:`status`,status:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${u()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:`pending`,agentId:he?.agentId??`virtual`,executionId:r.executionId??he?.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}:{}}};p(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:r.decision??`approved`,agentId:he?.agentId??`virtual`,executionId:r.executionId??he?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};p(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),M.set(i,{markdown:``,title:a,file:s}),!ee.has(i)){ee.add(i);let n=nn(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),rawContent:rn(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};j.set(i,c),p(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=M.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=M.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=j.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=M.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}M.delete(e),p(t),j.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`})}}}le.length=0};;){let{done:t,value:r}=await a.read();if(t)break;s+=o.decode(r,{stream:!0});let i=s.split(`
|
|
7
7
|
|
|
8
8
|
`);s=i.pop()??``;for(let t of i){let r=t.split(`
|
|
9
|
-
`),i=`message`,a=``,o=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?a+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(o=e.slice(3).trim());let s=()=>{o!==null&&o!==``&&n({type:`cursor`,id:o})};if(!a){s();continue}let c;try{c=JSON.parse(a)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=i===`message`?typeof l?.type==`string`?l.type:`message`:i;if(e.onSSEEvent?.(d,c),e.parseSSEEvent){g.current=m;let t=await
|
|
10
|
-
`):``,_i=e=>{if(e==null)return{status:`completed`};let t;try{t=JSON.parse(e)}catch{return{status:`completed`,result:e}}return typeof t==`object`&&t&&t.isError===!0?{status:`failed`,error:{message:gi(t.content)||`The page tool reported an error.`}}:t===void 0?{status:`completed`}:{status:`completed`,result:t}},vi=async e=>{if(typeof window>`u`||typeof window.confirm!=`function`)return!1;let t=yi(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`\n\nArguments:\n${t}`:``)+(e.description?`\n\n${e.description}`:``);return window.confirm(n)},yi=e=>{if(e==null)return``;try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+`…`:t}catch{return String(e)}},bi=e=>(e.window===void 0||typeof window<`u`&&e.window===window)&&(e.origin===void 0||typeof location<`u`&&e.origin===location.origin),xi=e=>{if(e===void 0)return``;try{return JSON.stringify(e)}catch{return String(e)}}})),Ci=/* @__PURE__ */ s({WebMcpBridge:()=>ci}),wi=o((()=>{Si()}));ve();const{setLoader:Ti,load:Ei}=_e({fallbackImport:()=>Promise.resolve().then(()=>(wi(),Ci))}),Di=Ei;function Q(e){return e.origin===`webmcp`&&!e.name.startsWith(ki)?ki+e.name:e.name}function Oi(e,t){let n=!1,r=Promise.resolve(),i=null,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=()=>{r=r.then(async()=>{let r=n?null:await e.snapshot().catch(()=>null);if(!r||n||r.fingerprint===i)return;let o=r.tools.map(e=>({...e,name:Q(e)})),s={type:`client_tools`,fingerprint:r.fingerprint,tools:o};t.send(s)&&(i=r.fingerprint,a=new Map(o.map(e=>[e.name,e])))})},c=e=>{for(let[t,n]of o)(e===void 0||n.delegationId===e)&&(o.delete(t),n.abort.abort())},l=e.onChange(s);return s(),{abort:c,close(){n=!0,l(),c()},call(r){let{delegationId:s,toolCallId:c}=r;if(n||typeof s!=`string`||!s||typeof c!=`string`||!c)return;let l=new AbortController;o.get(c)?.abort.abort(),o.set(c,{delegationId:s,abort:l});let u=({status:e,result:r,error:i})=>{o.get(c)?.abort===l&&(o.delete(c),!(n||t.cancelled(s))&&t.send({type:`client_tool_result`,delegationId:s,toolCallId:c,status:e,...r!==void 0&&{result:r},...i&&{error:{message:i.message}}}))},d=typeof r.name==`string`?r.name:``,f=a.get(d)??a.get(ki+d);if(!f||r.fingerprint!==i)return u({status:`stale`,error:{message:f?`The page's tools changed.`:`Unknown tool: ${d}`}});let p=r.arguments&&typeof r.arguments==`object`&&!Array.isArray(r.arguments)?r.arguments:{},m=typeof r.timeoutMs==`number`&&r.timeoutMs>0?r.timeoutMs:0,h,g=e.execute(f.name,p,{signal:l.signal,autoConfirmReadOnly:!0}).catch(e=>({status:`failed`,error:{message:e instanceof Error?e.message:String(e)}})),_=new Promise(e=>{m&&(h=setTimeout(()=>{l.abort(),e({status:`timeout`,error:{message:`Page tool exceeded ${m}ms.`}})},m))});Promise.race([g,_]).then(e=>{clearTimeout(h),u(e)})}}}var ki,Ai=o((()=>{ki=`webmcp:`})),ji=/* @__PURE__ */ s({createVoiceClientToolsSession:()=>Oi,voiceClientToolName:()=>Q}),Mi=o((()=>{Ai()}));ve();const{setLoader:Ni,load:Pi}=_e({fallbackImport:()=>Promise.resolve().then(()=>(Mi(),ji))}),Fi=Pi;function Ii(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Li(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=Ii(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=Ii(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw 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 Ri(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function zi(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function $(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}const Bi=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),Vi=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Hi=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=Bi(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:Vi(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},Ui=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=Hi(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n};var Wi=`4.29.0`,Gi,Ki=o((()=>{Gi=Wi})),qi=/* @__PURE__ */ s({deleteAllConversations:()=>ca,deleteConversation:()=>sa,finalizeDisplayProjections:()=>oa,getConversation:()=>aa,historyErrorFor:()=>ea,listConversations:()=>ia,readErrorCode:()=>Qi,recoverFromUnauthorized:()=>$i,resetVisitor:()=>la});function Ji(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Yi(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Xi(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;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 Zi(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,pa);return i}async function Qi(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function $i(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,ma);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,ha);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,ga);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function ea(e,t,n){let r=await Qi(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,pa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,ma)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,ha):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,ga):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function ta(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`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(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function na(e,t,n){ra(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Yi(e,n.scope)===`verified-user`&&(a=await Xi(e,i,r),a&&(i=await Zi(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Ji(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":Gi,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await $i(e,await Qi(e,u),a,r);continue}if(!u.ok)throw await ea(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return ta(e,d,a!==null,r),f}}function ra(e){if(!e.isClientTokenMode())throw 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 ia(e,t){let n=await na(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(fa),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function aa(e,t,n){let r=await na(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:fa(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function oa(e,t,n){ra(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>ua)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${ua} character limit`);r+=n}if(r>da)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${da} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await na(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=da,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function sa(e,t,n){let r=await na(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function ca(e,t){let n=await na(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 la(e){ra(e),e.setHistoryIdentityStatus({state:`resetting`});try{await na(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var ua,da,fa,pa,ma,ha,ga,_a=o((()=>{Ki(),ua=32768,da=49152,fa=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:``}},pa=`The identity proof was not admitted; account history is unavailable`,ma=`The identity proof was rejected`,ha=`The request carried no visitor credential`,ga=`The stored visitor belongs to a different signed-in user`}));ve();const{setLoader:va,load:ya,provide:ba}=_e({fallbackImport:()=>Promise.resolve().then(()=>(_a(),qi))}),xa=ya;function Sa(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ca(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function wa(e){return{type:`text`,text:e}}function Ta(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}function Ea(e){return Pa.includes(e)||e.startsWith(`image/`)}function Da(e){return Ea(e.type)}function Oa(e,t,n){return{type:`file`,data:e,mimeType:t,filename:n}}async function ka(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Da(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Aa(e,t=Ia,n=10485760){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 ja(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Ma(e,t){let n=ja(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 Na,Pa,Fa,Ia,La=o((()=>{Na=`[Image]`,Pa=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Fa=[`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`],Ia=[...Pa,...Fa]}));function Ra(e){if(typeof e!=`string`||e===``)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function za(e){return typeof e==`string`?e:void 0}function Ba(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.type){case`text`:return typeof t.text==`string`?wa(t.text):null;case`image`:return typeof t.image==`string`?Ta(t.image,{mimeType:za(t.mimeType),alt:za(t.alt)}):null;case`file`:return typeof t.data==`string`&&typeof t.mimeType==`string`&&typeof t.filename==`string`?Oa(t.data,t.mimeType,t.filename):null;case`audio`:return typeof t.audio==`string`?{type:`audio`,audio:t.audio,...za(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case`video`:return typeof t.video==`string`?{type:`video`,video:t.video,...za(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Va(e,t){let n=Ra(t),r=e.map(e=>Ra(e.timestamp)),i=Array(e.length),a=0;for(;a<r.length;){let e=r[a];if(e!==null){i[a]=e,a+=1;continue}let t=a;for(;t+1<r.length&&r[t+1]===null;)t+=1;let o=t-a+1,s=a>0?i[a-1]:null,c=t+1<r.length?r[t+1]:null,l=c!==null&&n!==null?Math.min(c,n):c??n;for(let e=0;e<o;e+=1)i[a+e]=l===null?s===null?Ka+e:s+e+1:l-(o-e);a=t+1}return i.map(e=>new Date(e).toISOString())}function Ha(e,t){let n=Va(e,t?.beforeCreatedAt),r=[];return e.forEach((e,t)=>{if(typeof e?.id!=`string`||e.id===``||!Ga.includes(e.role))return;let i=e.role,a=n[t];if(e.displayAvailable===!1)r.push({id:e.id,role:i,content:``,createdAt:a,agentMetadata:{historyDisplayUnavailable:!0}});else if(typeof e.displayContent==`string`)r.push({id:e.id,role:i,content:e.displayContent,createdAt:a});else if(typeof e.content==`string`)r.push({id:e.id,role:i,content:e.content,createdAt:a});else if(Array.isArray(e.content)){let t=e.content.map(Ba).filter(e=>e!==null),n=Sa(t);r.push({id:e.id,role:i,content:n||(Ca(t)?`[Image]`:``),createdAt:a,...t.length>0&&{contentParts:t}})}else r.push({id:e.id,role:i,content:``,createdAt:a})}),r}function Ua(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 Wa(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}var Ga,Ka,qa=o((()=>{La(),Ga=[`user`,`assistant`,`system`],Ka=0}));Jt(),Ir(),Sn(),Ki(),qa(),Br();var Ja=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const Ya=e=>`reason`in e?e.reason:void 0,Xa=(e,t)=>e instanceof Ja&&e.code===t,Za=e=>!e.voiceCaption&&!!(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),Qa=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),$a=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function eo(e){switch(e){case`json`:return bn;case`regex-json`:return yn;case`xml`:return xn;default:return vn}}var to=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":Gi,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??eo(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return Di().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:Ht,getToolDisplayTitle:Ut,loadPolyfill:qt});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await Fi()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:Lt(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=Li(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new Ja(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":Gi,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await xa();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await xa()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){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`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&Ya(t)===Ya(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Gi},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new Ja(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new Ja(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new Ja(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new Ja(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!Xa(n,`not_found`)&&!Xa(n,`visitor_required`)&&!Xa(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new Ja(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new Ja(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Gi},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:Ja,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await xa()).listConversations(this.#G(),e)}async getConversation(e,t){return(await xa()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await xa()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await xa()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await xa()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await xa()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),ti().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=$();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(Za).map(e=>{let t=l?Ua(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Gi,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new Ja(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new Ja(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof Ja)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t){return(await ti()).resolveApproval(this.#U(),e,t)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?Lt(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await ti()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=Ui(Qa(e),e=>Za(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?$a(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...Fr(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=Ui(Qa(e),e=>Za(e)?$a(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...Fr(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=ni()??await ti();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}};function no(e){return e instanceof ro}var ro,io=o((()=>{ro=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryProviderError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}}})),ao,oo=o((()=>{xr(),ao=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(e,i,a)=>{let o=i.trim();if(!o||!r.current)return;let s=e.getAttribute(`data-tool-call-id`)??``,c=a.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{toolUseId:s,answer:o,answers:a.structured,values:a.values??(a.source===`multi`?o.split(`, `):[o]),isFreeText:c,source:a.source},bubbles:!0,composed:!0})),_r(n,s);let l=r.current.getMessages().find(e=>e.toolCall?.id===s);l?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(l,a.structured??o):r.current.sendMessage(o)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:ur(e,i),currentIndex:ir(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=ir(t);if(n>=or(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(br(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let e=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:e},bubbles:!0,composed:!0})),_r(n,e);let i=r.current?.getMessages().find(t=>t.toolCall?.id===e);i?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(i),r.current?.resolveAskUserQuestion(i,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=sr(u);if(n&&t){let t=nr(u)[ir(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),yr(u,Array.from(n)),a(u);return}if(n){yr(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=vr(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=vr(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(sr(u)){yr(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=nr(u)[ir(u)];(typeof e!=`string`||e!==i)&&yr(u,i)}let o=d===`next`?1:-1,s=ir(u)+o;br(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&yr(u,n);let a=ur(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:ir(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=sr(u),d=ir(u),f=d>=or(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:s},bubbles:!0,composed:!0})),_r(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}yr(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=ur(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}br(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(sr(n)?(yr(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function so(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
|
|
11
|
-
`:r===``||
|
|
12
|
-
`||o===``||!i&&po.test(o))return null;a--}return null}function lo(e,t,n){for(let r of n){let n=co(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function uo(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}function fo(e,t,n){return{value:e.slice(0,t.triggerIndex)+e.slice(n),caret:t.triggerIndex}}var po,mo=o((()=>{po=/\s/}));function ho(e){return[{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},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var go=o((()=>{}));function _o(e){e.delayMs!==void 0&&(Co=Eo(e.delayMs)),e.skipDelayMs!==void 0&&(wo=Eo(e.skipDelayMs))}function vo(e){ko.get(e)?.hide()}function yo(e){ko.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=bo,viewportPadding:s=xo}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>Eo(e.delayMs??Co),x=()=>Eo(e.skipDelayMs??wo),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&Oo(x())},w=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Po(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Po(v,s,y),x=r.left+r.width/2,S=Math.max(So,i.width-So),C=Po(x-m,So,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},T=()=>{if(_||!a||u||!t.isConnected||jo(t))return;let e=v(),n=No(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(zr);let o=i.getComputedStyle?.(t);if(o){for(let e of Fo){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),w(),u.dataset.state=`open`;let h=()=>{t.isConnected?(d&&(d.textContent=v()),f&&(f.textContent=y()),w()):C()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.getRootNode(),b=Mo(g)?g:r.documentElement,x=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});x?.observe(b,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),x?.disconnect()}},E=e=>{_||u||(S(),e||b()<=0||Do()?T():m=l().setTimeout(()=>{m=void 0,T()},b()))},D=()=>{h||g?E(g):C()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,D())},k=()=>{h=!1,D()},A=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}D()},j=()=>{g=!1,D()},M=()=>{h=!1,g=!1,C()},ee=e=>{e.key===`Escape`&&M()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,A),t.addEventListener(`blur`,j),t.addEventListener(`keydown`,ee),t.addEventListener(`click`,M);let N={get isOpen(){return u!==null},show:T,hide:C,reposition:w,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,A),t.removeEventListener(`blur`,j),t.removeEventListener(`keydown`,ee),t.removeEventListener(`click`,M),ko.delete(t))}};return ko.set(t,N),N}var bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io=o((()=>{Br(),I(),bo=8,xo=8,So=10,Co=200,wo=300,To=0,Eo=e=>Math.max(0,e),Do=()=>Date.now()<To,Oo=e=>{To=e>0?Date.now()+e:0},ko=/* @__PURE__ */ new WeakMap,Ao=`data-persona-tooltip-suppressed`,jo=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Mo=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,No=e=>{let t=e.getRootNode?.();return Mo(t)?t:e.ownerDocument.body},Po=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Fo=[...[`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 Lo(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 r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function Ro(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function zo(e,t){e.style.maxHeight=`${t*Lo(e)}px`,e.style.overflowY=`auto`}function Bo(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 Vo(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Ho(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!Vo(t)}function Uo(e){return(e.submitKey??`enter`)===`enter`?Vo(e)?`enter`:`send`:`enter`}function Wo(e,t){e.setAttribute(`enterkeyhint`,Uo(t))}function Go(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function Ko(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 qo=o((()=>{})),Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns,rs,is=o((()=>{H(),ze(),he(),La(),Io(),qo(),Jo=`persona-composer-control`,Yo=`persona-composer-control--glyph`,Xo=(e,t,n)=>{let r=e.ownerDocument?.defaultView;if(!r)return;let i=r.getComputedStyle(e);for(let e of n){let n=i.getPropertyValue(e).trim();n?t.style.setProperty(e,n):t.style.removeProperty(e)}},Zo=(e,t)=>{let n=z(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,Wo(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Bo(n)}),Go(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 r=Ro(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*Lo(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}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:o}},Qo=(e,t,n=`send`)=>{let r=B(`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`),r.append(e,t),r},$o=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,r=t.iconText??`↑`,i=t.iconName,a=t.stopIconName??`square`,o=t.tooltipText??`Send message`,s=t.stopTooltipText??`Stop generating`,c=e?.copy?.sendButtonLabel??`Send`,l=e?.copy?.stopButtonLabel??`Stop`,u=t.showTooltip??!1,d=t.size,f=parseFloat(d??``)||40,p=t.backgroundColor,m=t.textColor,h=z(`div`,`persona-send-button-wrapper`),g=B(`button`,{className:V(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,n?`persona-flex persona-items-center persona-justify-center ${Jo}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,n&&!p&&`persona-bg-persona-primary`,!n&&!m&&`persona-text-white`),attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`},style:{width:n?d:void 0,height:n?d:void 0,minWidth:n?d:void 0,minHeight:n?d:void 0,fontSize:n?`18px`:void 0,lineHeight:n?`1`:void 0,color:n?m||`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:m||void 0,backgroundColor:n&&p||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}}),_=null,v=null,y=null;if(n){let e=parseFloat(t.iconSize??``)||Math.round(f*.5),n=t.iconStrokeWidth??2,o=m?.trim()||`currentColor`;if(i&&(_=U(i,e,o,n)),v=U(a,e,o,n),!t.iconSize)for(let t of[_,v])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);_&&v?(y=Qo(_,v),g.appendChild(y)):_?g.appendChild(_):(g.textContent=r,v=null)}else g.textContent=c;g.setAttribute(`aria-label`,o),h.appendChild(g),yo({anchor:g,trigger:h,text:()=>g.getAttribute(`aria-label`)??``,enabled:u});let b=`send`;return{button:g,wrapper:h,setMode:e=>{if(e===b)return;b=e;let t=e===`stop`?s:o;g.setAttribute(`aria-label`,t),g.setAttribute(`data-persona-send-mode`,e),n?(g.querySelector(`[data-persona-glyph-stack]`)??y)?.setAttribute(`data-mode`,e):g.textContent=e===`stop`?l:c},glyphStack:y}},es=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`;if(!(n||r||i))return null;let a=t.iconName??`mic`,o=t.iconSize,s=parseFloat(o??``)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,l=t.iconColor??e?.sendButton?.textColor,u=z(`div`,`persona-send-button-wrapper`),d=B(`button`,{className:V(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer`,Jo,!o&&`persona-composer-control--glyph`),attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:`18px`,lineHeight:`1`,color:l||`var(--persona-text, #111827)`,backgroundColor:c||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}}),f=U(a,s,l||`currentColor`,1.5);f?d.appendChild(f):d.textContent=`🎤`,u.appendChild(d);let p=t.tooltipText??`Start voice recognition`;return yo({anchor:d,trigger:u,text:()=>d.getAttribute(`aria-label`)??p,enabled:t.showTooltip??!1}),{button:d,wrapper:u}},ts=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=z(`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 r=z(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Ia).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=z(`div`,`persona-send-button-wrapper`),o=B(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Jo} ${Yo}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=U(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return yo({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},ns=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=z(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),nt(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=z(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},rs=()=>B(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function as(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=z(`div`,`persona-send-button-wrapper`),o=B(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Jo} ${Yo}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=U(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),yo({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var os=o((()=>{H(),ze(),Io(),is()})),ss,cs,ls,us=o((()=>{ss=null,cs=e=>{ss=e},ls=(e,t,n,r)=>ss?.(e,t,n,r)??null}));function ds(e){let{ref:t,config:n,onRemove:r}=e;if(n.renderMentionChip){let e=`resolving`,i,a=n.renderMentionChip({ref:t,status:e,payload:i,remove:r});return{get el(){return a},setStatus:(o,s)=>{if(o===e&&s===i)return;e=o,i=s;let c=n.renderMentionChip({ref:t,status:e,payload:i,remove:r});a.replaceWith(c),a=c}}}let i=t.iconName??n.chipIconName??`at-sign`,a=B(`div`,{className:`persona-mention-chip`,attrs:{"data-persona-mention-chip":``,"data-status":`resolving`,title:t.label}}),o=z(`span`,`persona-mention-chip-icon`),s=e=>{o.replaceChildren();let t=ls(e,13,`currentColor`,2);t&&o.appendChild(t)};s(i);let c=z(`span`,`persona-mention-chip-spinner`),l=B(`span`,{className:`persona-mention-chip-label`,text:t.label}),d=B(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label} context`}}),f=h(u.X,11,`currentColor`,2.5);return f?d.appendChild(f):d.textContent=`×`,d.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(c),a.appendChild(l),a.appendChild(d),{el:a,setStatus:e=>{a.setAttribute(`data-status`,e),e===`resolving`?(c.parentNode!==a&&a.insertBefore(c,l),o.parentNode===a&&o.remove(),a.setAttribute(`title`,t.label)):(c.parentNode===a&&c.remove(),o.parentNode!==a&&a.insertBefore(o,l),e===`error`?(s(`triangle-alert`),a.setAttribute(`title`,`Couldn't add ${t.label} to context`)):(s(i),a.setAttribute(`title`,t.label)))}}}var fs=o((()=>{H(),g(),us()}));function ps(e){e.style.display=e.childElementCount>0?`flex`:`none`}function ms(e){let t=e.querySelector(hs);if(t)return t;let n=B(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}var hs,gs=o((()=>{H(),hs=`[data-persona-composer-chip-row]`}));function _s(e){let t=0;for(let n of e.split(`
|
|
13
|
-
`)){let e=/^ {0,3}(`+)/.exec(n);e&&e[1].length>t&&(t=e[1].length)}return t}function
|
|
9
|
+
`),i=`message`,a=``,o=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?a+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(o=e.slice(3).trim());let s=()=>{o!==null&&o!==``&&n({type:`cursor`,id:o})};if(!a){s();continue}let c;try{c=JSON.parse(a)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=i===`message`?typeof l?.type==`string`?l.type:`message`:i;if(e.onSSEEvent?.(d,c),e.parseSSEEvent){g.current=m;let t=await Zr(e,c,n,g,p,u,_);if(g.current&&g.current!==m&&(m=g.current),t){s();continue}}l&&(le.push({...l,type:d}),ue()),s()}}ue()}var $r,ei=o((()=>{E(),an(),Tn(),qr(),$r=e=>e.startsWith(`{`)||e.startsWith(`[`)||e.startsWith(`<`)}));Pe();const{setLoader:ti,load:ni,provide:ri,getSync:ii}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(ei(),Jr))}),ai=ni,oi=ii;var si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei=o((()=>{si=3e4,ci=(e,t)=>({ok:!1,reason:e,message:t}),li=`webmcp:`,ui=e=>e.startsWith(li)?e.slice(7):e,di={warn(e,...t){typeof console<`u`&&typeof console.warn==`function`&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},fi=class{#e;#t;#n=!1;#r=null;#i=!1;#a;constructor(e,t){this.config=e,this.#a=t,this.#e=e.onConfirm??null,this.#t=si}setConfirmHandler(e){this.#e=e}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#l()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let e=this.#l();if(!e)return[];let t;try{t=(await e.getTools()).filter(wi)}catch(e){return di.warn(`getTools() threw: shipping an empty WebMCP snapshot.`,e),[]}this.#a.recordToolDisplayTitles(t);let n=typeof location<`u`?location.origin:``;return t.filter(e=>this.#d(e.name)).map(e=>{let t=hi(e.annotations);return{name:e.name,description:e.description,parametersSchema:gi(e.inputSchema),origin:`webmcp`,...n?{pageOrigin:n}:{},...t?{annotations:t}:{},...t?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,t,n){let r=await this.#o(e,t,n,!1);return r.ok?_i(r.raw):yi(r.message)}async executeVoiceToolCall(e,t,n={}){let r=await this.#o(e,t,n.signal,n.autoConfirmReadOnly===!0);return r.ok?xi(r.raw):{status:r.reason===`aborted`?`failed`:r.reason,error:{message:r.message}}}watchToolChanges(e){let t=!1,n=null;return this.#s().then(()=>{if(t||this.config.enabled!==!0)return;let r=this.#l();r&&typeof r.addEventListener==`function`&&(n=r,n.addEventListener(`toolchange`,e))}),()=>{t=!0,n?.removeEventListener(`toolchange`,e),n=null}}async#o(e,t,n,r){if(await this.#s(),this.config.enabled!==!0)return ci(`failed`,`WebMCP is not enabled on this widget.`);let i=this.#l();if(!i){let e=typeof document<`u`&&!!document.modelContext;return ci(`failed`,e?`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 a=ui(e),o;try{o=(await i.getTools()).filter(wi)}catch(e){let t=e instanceof Error?e.message:String(e);return ci(`failed`,`Failed to read WebMCP registry: ${t}`)}this.#a.recordToolDisplayTitles(o);let s=o.find(e=>e.name===a);if(!s)return ci(`stale`,`WebMCP tool not registered on this page: ${a}`);if(!this.#d(a))return ci(`stale`,`WebMCP tool not allowed by client allowlist: ${a}`);if(n?.aborted)return ci(`aborted`,`Aborted by cancel()`);let c=this.#a.getToolDisplayTitle(a),l=hi(s.annotations),u={toolName:a,args:t,description:s.description,...l?{annotations:l}:{},...c?{title:c}:{},...n?{signal:n}:{},reason:`gate`};if(!(r&&l?.readOnlyHint===!0)&&!await this.#u(u))return ci(`denied`,`User declined the tool call.`);if(n?.aborted)return ci(`aborted`,`Aborted by cancel()`);let d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},this.#t),m=()=>d.abort();n&&(n.aborted?d.abort():n.addEventListener(`abort`,m,{once:!0}));try{return{ok:!0,raw:await i.executeTool(s,vi(t),{signal:d.signal})}}catch(e){if(f)return ci(`timeout`,`WebMCP tool '${a}' timed out after ${this.#t}ms`);if(n?.aborted)return ci(`aborted`,`Aborted by cancel()`);let t=e instanceof Error?e.message:String(e);return ci(`failed`,t)}finally{clearTimeout(p),n&&n.removeEventListener(`abort`,m)}}#s(){return this.config.enabled===!0?(this.#r||=this.#c(),this.#r):Promise.resolve()}async#c(){try{if(this.#l()){this.#n=!0;return}let e=await this.#a.loadPolyfill();`initializeWebMCPPolyfill`in e?e.initializeWebMCPPolyfill():e.installWebMCP(),this.#n=!0}catch(e){di.warn(`Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.`,e),this.#n=!1}}#l(){if(typeof document>`u`)return null;let e=document.modelContext;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.getTools!=`function`||typeof t.executeTool!=`function`?(this.#i||(this.#i=!0,di.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):e}async#u(e){let t=this.#e??Si;try{return await t(e)}catch(t){return di.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,t),!1}}#d(e){let t=this.config.allowlist;return!t||t.length===0||t.some(t=>pi(e,t))}},pi=(e,t)=>{if(t===`*`)return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^`+n.replace(/\*/g,`.*`)+`$`).test(e)},mi={type:`object`,properties:{}},hi=e=>{if(!e||typeof e!=`object`)return;let t={};for(let n of[`readOnlyHint`,`destructiveHint`,`consequentialHint`,`untrustedContentHint`,`idempotentHint`,`openWorldHint`,`debugging`]){let r=e[n];typeof r==`boolean`&&(t[n]=r)}return Object.keys(t).length>0?t:void 0},gi=e=>{if(e===void 0||e===``)return{...mi};if(typeof e==`object`)return e!==null&&!Array.isArray(e)?e:{...mi};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{...mi}}catch{return{...mi}}},_i=e=>{if(e==null)return{content:[{type:`text`,text:``}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:`text`,text:e}]}}return typeof t==`object`&&t&&Array.isArray(t.content)?t:{content:[{type:`text`,text:typeof t==`string`?t:Ti(t)}]}},vi=e=>{let t;try{t=JSON.stringify(e)??`{}`}catch{t=`{}`}let n=JSON.parse(t);if(typeof n!=`object`||!n)throw TypeError(`WebMCP tool arguments must be an object or array.`);return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},yi=e=>({isError:!0,content:[{type:`text`,text:e}]}),bi=e=>Array.isArray(e)?e.map(e=>e&&typeof e==`object`&&typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
10
|
+
`):``,xi=e=>{if(e==null)return{status:`completed`};let t;try{t=JSON.parse(e)}catch{return{status:`completed`,result:e}}return typeof t==`object`&&t&&t.isError===!0?{status:`failed`,error:{message:bi(t.content)||`The page tool reported an error.`}}:t===void 0?{status:`completed`}:{status:`completed`,result:t}},Si=async e=>{if(typeof window>`u`||typeof window.confirm!=`function`)return!1;let t=Ci(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`\n\nArguments:\n${t}`:``)+(e.description?`\n\n${e.description}`:``);return window.confirm(n)},Ci=e=>{if(e==null)return``;try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+`…`:t}catch{return String(e)}},wi=e=>(e.window===void 0||typeof window<`u`&&e.window===window)&&(e.origin===void 0||typeof location<`u`&&e.origin===location.origin),Ti=e=>{if(e===void 0)return``;try{return JSON.stringify(e)}catch{return String(e)}}})),Di=/* @__PURE__ */ s({WebMcpBridge:()=>fi}),Oi=o((()=>{Ei()}));Pe();const{setLoader:Q,load:ki}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Oi(),Di))}),Ai=ki;function ji(e){return e.origin===`webmcp`&&!e.name.startsWith(Ni)?Ni+e.name:e.name}function Mi(e,t){let n=!1,r=Promise.resolve(),i=null,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=()=>{r=r.then(async()=>{let r=n?null:await e.snapshot().catch(()=>null);if(!r||n||r.fingerprint===i)return;let o=r.tools.map(e=>({...e,name:ji(e)})),s={type:`client_tools`,fingerprint:r.fingerprint,tools:o};t.send(s)&&(i=r.fingerprint,a=new Map(o.map(e=>[e.name,e])))})},c=e=>{for(let[t,n]of o)(e===void 0||n.delegationId===e)&&(o.delete(t),n.abort.abort())},l=e.onChange(s);return s(),{abort:c,close(){n=!0,l(),c()},call(r){let{delegationId:s,toolCallId:c}=r;if(n||typeof s!=`string`||!s||typeof c!=`string`||!c)return;let l=new AbortController;o.get(c)?.abort.abort(),o.set(c,{delegationId:s,abort:l});let u=({status:e,result:r,error:i})=>{o.get(c)?.abort===l&&(o.delete(c),!(n||t.cancelled(s))&&t.send({type:`client_tool_result`,delegationId:s,toolCallId:c,status:e,...r!==void 0&&{result:r},...i&&{error:{message:i.message}}}))},d=typeof r.name==`string`?r.name:``,f=a.get(d)??a.get(Ni+d);if(!f||r.fingerprint!==i)return u({status:`stale`,error:{message:f?`The page's tools changed.`:`Unknown tool: ${d}`}});let p=r.arguments&&typeof r.arguments==`object`&&!Array.isArray(r.arguments)?r.arguments:{},m=typeof r.timeoutMs==`number`&&r.timeoutMs>0?r.timeoutMs:0,h,g=e.execute(f.name,p,{signal:l.signal,autoConfirmReadOnly:!0}).catch(e=>({status:`failed`,error:{message:e instanceof Error?e.message:String(e)}})),_=new Promise(e=>{m&&(h=setTimeout(()=>{l.abort(),e({status:`timeout`,error:{message:`Page tool exceeded ${m}ms.`}})},m))});Promise.race([g,_]).then(e=>{clearTimeout(h),u(e)})}}}var Ni,Pi=o((()=>{Ni=`webmcp:`})),Fi=/* @__PURE__ */ s({createVoiceClientToolsSession:()=>Mi,voiceClientToolName:()=>ji}),Ii=o((()=>{Pi()}));Pe();const{setLoader:Li,load:Ri}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Ii(),Fi))}),zi=Ri;function Bi(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function $(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=Bi(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=Bi(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw 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 Vi(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Hi(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Ui(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var Wi=o((()=>{}));Wi();const Gi=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),Ki=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qi=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=Gi(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:Ki(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},Ji=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=qi(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n};var Yi=`4.29.1`,Xi,Zi=o((()=>{Xi=Yi})),Qi=/* @__PURE__ */ s({deleteAllConversations:()=>pa,deleteConversation:()=>fa,finalizeDisplayProjections:()=>da,getConversation:()=>ua,historyErrorFor:()=>aa,listConversations:()=>la,readErrorCode:()=>ra,recoverFromUnauthorized:()=>ia,resetVisitor:()=>ma});function $i(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function ea(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function ta(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;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 na(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,va);return i}async function ra(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function ia(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,ya);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,ba);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,xa);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function aa(e,t,n){let r=await ra(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,va);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,ya)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,ba):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,xa):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function oa(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`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(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function sa(e,t,n){ca(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;ea(e,n.scope)===`verified-user`&&(a=await ta(e,i,r),a&&(i=await na(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch($i(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":Xi,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await ia(e,await ra(e,u),a,r);continue}if(!u.ok)throw await aa(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return oa(e,d,a!==null,r),f}}function ca(e){if(!e.isClientTokenMode())throw 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 la(e,t){let n=await sa(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(_a),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function ua(e,t,n){let r=await sa(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:_a(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function da(e,t,n){ca(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>ha)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${ha} character limit`);r+=n}if(r>ga)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${ga} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await sa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=ga,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function fa(e,t,n){let r=await sa(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function pa(e,t){let n=await sa(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 ma(e){ca(e),e.setHistoryIdentityStatus({state:`resetting`});try{await sa(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var ha,ga,_a,va,ya,ba,xa,Sa=o((()=>{Zi(),ha=32768,ga=49152,_a=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:``}},va=`The identity proof was not admitted; account history is unavailable`,ya=`The identity proof was rejected`,ba=`The request carried no visitor credential`,xa=`The stored visitor belongs to a different signed-in user`}));Pe();const{setLoader:Ca,load:wa,provide:Ta}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Sa(),Qi))}),Ea=wa;function Da(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Oa(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function ka(e){return{type:`text`,text:e}}function Aa(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}function ja(e){return za.includes(e)||e.startsWith(`image/`)}function Ma(e){return ja(e.type)}function Na(e,t,n){return{type:`file`,data:e,mimeType:t,filename:n}}async function Pa(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Ma(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Fa(e,t=Va,n=10485760){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 Ia(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function La(e,t){let n=Ia(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 Ra,za,Ba,Va,Ha=o((()=>{Ra=`[Image]`,za=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Ba=[`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`],Va=[...za,...Ba]}));function Ua(e){if(typeof e!=`string`||e===``)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Wa(e){return typeof e==`string`?e:void 0}function Ga(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.type){case`text`:return typeof t.text==`string`?ka(t.text):null;case`image`:return typeof t.image==`string`?Aa(t.image,{mimeType:Wa(t.mimeType),alt:Wa(t.alt)}):null;case`file`:return typeof t.data==`string`&&typeof t.mimeType==`string`&&typeof t.filename==`string`?Na(t.data,t.mimeType,t.filename):null;case`audio`:return typeof t.audio==`string`?{type:`audio`,audio:t.audio,...Wa(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case`video`:return typeof t.video==`string`?{type:`video`,video:t.video,...Wa(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Ka(e,t){let n=Ua(t),r=e.map(e=>Ua(e.timestamp)),i=Array(e.length),a=0;for(;a<r.length;){let e=r[a];if(e!==null){i[a]=e,a+=1;continue}let t=a;for(;t+1<r.length&&r[t+1]===null;)t+=1;let o=t-a+1,s=a>0?i[a-1]:null,c=t+1<r.length?r[t+1]:null,l=c!==null&&n!==null?Math.min(c,n):c??n;for(let e=0;e<o;e+=1)i[a+e]=l===null?s===null?Za+e:s+e+1:l-(o-e);a=t+1}return i.map(e=>new Date(e).toISOString())}function qa(e,t){let n=Ka(e,t?.beforeCreatedAt),r=[];return e.forEach((e,t)=>{if(typeof e?.id!=`string`||e.id===``||!Xa.includes(e.role))return;let i=e.role,a=n[t];if(e.displayAvailable===!1)r.push({id:e.id,role:i,content:``,createdAt:a,agentMetadata:{historyDisplayUnavailable:!0}});else if(typeof e.displayContent==`string`)r.push({id:e.id,role:i,content:e.displayContent,createdAt:a});else if(typeof e.content==`string`)r.push({id:e.id,role:i,content:e.content,createdAt:a});else if(Array.isArray(e.content)){let t=e.content.map(Ga).filter(e=>e!==null),n=Da(t);r.push({id:e.id,role:i,content:n||(Oa(t)?`[Image]`:``),createdAt:a,...t.length>0&&{contentParts:t}})}else r.push({id:e.id,role:i,content:``,createdAt:a})}),r}function Ja(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 Ya(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}var Xa,Za,Qa=o((()=>{Ha(),Xa=[`user`,`assistant`,`system`],Za=0})),$a,eo,to=o((()=>{$a=`reconnect-failed-`,eo=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`)}));E(),Br(),Tn(),Zi(),Qa(),to(),Wr();var no=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const ro=e=>`reason`in e?e.reason:void 0,io=(e,t)=>e instanceof no&&e.code===t,ao=e=>e.voiceCaption||eo(e)?!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),oo=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),so=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function co(e){switch(e){case`json`:return Cn;case`regex-json`:return Sn;case`xml`:return wn;default:return xn}}var lo=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":Xi,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??co(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return Ai().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:b,getToolDisplayTitle:x,loadPolyfill:T});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await zi()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:h(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=$(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new no(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":Xi,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await Ea();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await Ea()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){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`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&ro(t)===ro(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Xi},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new no(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new no(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new no(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new no(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!io(n,`not_found`)&&!io(n,`visitor_required`)&&!io(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new no(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new no(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Xi},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:no,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await Ea()).listConversations(this.#G(),e)}async getConversation(e,t){return(await Ea()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await Ea()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await Ea()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await Ea()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await Ea()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),ai().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=Ui();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(ao).map(e=>{let t=l?Ja(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Xi,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new no(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new no(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof no)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await ai()).resolveApproval(this.#U(),e,t,n)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?h(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await ai()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=Ji(oo(e),e=>ao(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?so(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...zr(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=Ji(oo(e),e=>ao(e)?so(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...zr(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=oi()??await ai();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}};function uo(e){return e instanceof fo}var fo,po=o((()=>{fo=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryProviderError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}}})),mo,ho=o((()=>{Tr(),mo=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(e,i,a)=>{let o=i.trim();if(!o||!r.current)return;let s=e.getAttribute(`data-tool-call-id`)??``,c=a.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{toolUseId:s,answer:o,answers:a.structured,values:a.values??(a.source===`multi`?o.split(`, `):[o]),isFreeText:c,source:a.source},bubbles:!0,composed:!0})),xr(n,s);let l=r.current.getMessages().find(e=>e.toolCall?.id===s);l?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(l,a.structured??o):r.current.sendMessage(o)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:mr(e,i),currentIndex:cr(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=cr(t);if(n>=ur(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(wr(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let e=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:e},bubbles:!0,composed:!0})),xr(n,e);let i=r.current?.getMessages().find(t=>t.toolCall?.id===e);i?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(i),r.current?.resolveAskUserQuestion(i,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=dr(u);if(n&&t){let t=or(u)[cr(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Cr(u,Array.from(n)),a(u);return}if(n){Cr(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Sr(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Sr(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(dr(u)){Cr(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=or(u)[cr(u)];(typeof e!=`string`||e!==i)&&Cr(u,i)}let o=d===`next`?1:-1,s=cr(u)+o;wr(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Cr(u,n);let a=mr(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:cr(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=dr(u),d=cr(u),f=d>=ur(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:s},bubbles:!0,composed:!0})),xr(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Cr(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=mr(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}wr(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(dr(n)?(Cr(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function go(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
|
|
11
|
+
`:r===``||xo.test(r)}function _o(e,t,n=`@`,r=`anywhere`,i=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let o=e[a];if(o===n)return go(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
|
|
12
|
+
`||o===``||!i&&xo.test(o))return null;a--}return null}function vo(e,t,n){for(let r of n){let n=_o(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function yo(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}function bo(e,t,n){return{value:e.slice(0,t.triggerIndex)+e.slice(n),caret:t.triggerIndex}}var xo,So=o((()=>{xo=/\s/}));function Co(e){return[{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},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var wo=o((()=>{}));function To(e){e.delayMs!==void 0&&(jo=Po(e.delayMs)),e.skipDelayMs!==void 0&&(Mo=Po(e.skipDelayMs))}function Eo(e){Lo.get(e)?.hide()}function Do(e){Lo.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=Oo,viewportPadding:s=ko}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>Po(e.delayMs??jo),x=()=>Po(e.skipDelayMs??Mo),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&Io(x())},w=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Ho(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Ho(v,s,y),x=r.left+r.width/2,S=Math.max(Ao,i.width-Ao),C=Ho(x-m,Ao,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},T=()=>{if(_||!a||u||!t.isConnected||zo(t))return;let e=v(),n=Vo(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(Ur);let o=i.getComputedStyle?.(t);if(o){for(let e of Uo){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),w(),u.dataset.state=`open`;let h=()=>{t.isConnected?(d&&(d.textContent=v()),f&&(f.textContent=y()),w()):C()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.getRootNode(),b=Bo(g)?g:r.documentElement,x=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});x?.observe(b,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),x?.disconnect()}},E=e=>{_||u||(S(),e||b()<=0||Fo()?T():m=l().setTimeout(()=>{m=void 0,T()},b()))},D=()=>{h||g?E(g):C()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,D())},k=()=>{h=!1,D()},A=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}D()},j=()=>{g=!1,D()},ee=()=>{h=!1,g=!1,C()},M=e=>{e.key===`Escape`&&ee()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,A),t.addEventListener(`blur`,j),t.addEventListener(`keydown`,M),t.addEventListener(`click`,ee);let N={get isOpen(){return u!==null},show:T,hide:C,reposition:w,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,A),t.removeEventListener(`blur`,j),t.removeEventListener(`keydown`,M),t.removeEventListener(`click`,ee),Lo.delete(t))}};return Lo.set(t,N),N}var Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo=o((()=>{Wr(),ve(),Oo=8,ko=8,Ao=10,jo=200,Mo=300,No=0,Po=e=>Math.max(0,e),Fo=()=>Date.now()<No,Io=e=>{No=e>0?Date.now()+e:0},Lo=/* @__PURE__ */ new WeakMap,Ro=`data-persona-tooltip-suppressed`,zo=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Bo=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Vo=e=>{let t=e.getRootNode?.();return Bo(t)?t:e.ownerDocument.body},Ho=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Uo=[...[`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 Go(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 r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function Ko(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function qo(e,t){e.style.maxHeight=`${t*Go(e)}px`,e.style.overflowY=`auto`}function Jo(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 Yo(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Xo(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!Yo(t)}function Zo(e){return(e.submitKey??`enter`)===`enter`?Yo(e)?`enter`:`send`:`enter`}function Qo(e,t){e.setAttribute(`enterkeyhint`,Zo(t))}function $o(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function es(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 ts=o((()=>{})),ns,rs,is,as,os,ss,cs,ls,us,ds,fs=o((()=>{H(),W(),Ae(),Ha(),Wo(),ts(),ns=`persona-composer-control`,rs=`persona-composer-control--glyph`,is=(e,t,n)=>{let r=e.ownerDocument?.defaultView;if(!r)return;let i=r.getComputedStyle(e);for(let e of n){let n=i.getPropertyValue(e).trim();n?t.style.setProperty(e,n):t.style.removeProperty(e)}},as=(e,t)=>{let n=B(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,Qo(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Jo(n)}),$o(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 r=Ko(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*Go(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}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:o}},os=(e,t,n=`send`)=>{let r=V(`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`),r.append(e,t),r},ss=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,r=t.iconText??`↑`,i=t.iconName,a=t.stopIconName??`square`,o=t.tooltipText??`Send message`,s=t.stopTooltipText??`Stop generating`,c=e?.copy?.sendButtonLabel??`Send`,l=e?.copy?.stopButtonLabel??`Stop`,u=t.showTooltip??!1,d=t.size,f=parseFloat(d??``)||40,p=t.backgroundColor,m=t.textColor,h=B(`div`,`persona-send-button-wrapper`),g=V(`button`,{className:Me(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,n?`persona-flex persona-items-center persona-justify-center ${ns}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,n&&!p&&`persona-bg-persona-primary`,!n&&!m&&`persona-text-white`),attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`},style:{width:n?d:void 0,height:n?d:void 0,minWidth:n?d:void 0,minHeight:n?d:void 0,fontSize:n?`18px`:void 0,lineHeight:n?`1`:void 0,color:n?m||`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:m||void 0,backgroundColor:n&&p||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}}),_=null,v=null,y=null;if(n){let e=parseFloat(t.iconSize??``)||Math.round(f*.5),n=t.iconStrokeWidth??2,o=m?.trim()||`currentColor`;if(i&&(_=U(i,e,o,n)),v=U(a,e,o,n),!t.iconSize)for(let t of[_,v])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);_&&v?(y=os(_,v),g.appendChild(y)):_?g.appendChild(_):(g.textContent=r,v=null)}else g.textContent=c;g.setAttribute(`aria-label`,o),h.appendChild(g),Do({anchor:g,trigger:h,text:()=>g.getAttribute(`aria-label`)??``,enabled:u});let b=`send`;return{button:g,wrapper:h,setMode:e=>{if(e===b)return;b=e;let t=e===`stop`?s:o;g.setAttribute(`aria-label`,t),g.setAttribute(`data-persona-send-mode`,e),n?(g.querySelector(`[data-persona-glyph-stack]`)??y)?.setAttribute(`data-mode`,e):g.textContent=e===`stop`?l:c},glyphStack:y}},cs=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`;if(!(n||r||i))return null;let a=t.iconName??`mic`,o=t.iconSize,s=parseFloat(o??``)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,l=t.iconColor??e?.sendButton?.textColor,u=B(`div`,`persona-send-button-wrapper`),d=V(`button`,{className:Me(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer`,ns,!o&&`persona-composer-control--glyph`),attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:`18px`,lineHeight:`1`,color:l||`var(--persona-text, #111827)`,backgroundColor:c||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}}),f=U(a,s,l||`currentColor`,1.5);f?d.appendChild(f):d.textContent=`🎤`,u.appendChild(d);let p=t.tooltipText??`Start voice recognition`;return Do({anchor:d,trigger:u,text:()=>d.getAttribute(`aria-label`)??p,enabled:t.showTooltip??!1}),{button:d,wrapper:u}},ls=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=B(`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 r=B(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Va).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=B(`div`,`persona-send-button-wrapper`),o=V(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ns} ${rs}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=U(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return Do({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},us=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=B(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),dt(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=B(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},ds=()=>V(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function ps(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=B(`div`,`persona-send-button-wrapper`),o=V(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${ns} ${rs}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=U(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),Do({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var ms=o((()=>{H(),W(),Wo(),fs()})),hs,gs,_s,vs=o((()=>{hs=null,gs=e=>{hs=e},_s=(e,t,n,r)=>hs?.(e,t,n,r)??null}));function ys(e){let{ref:t,config:n,onRemove:r}=e;if(n.renderMentionChip){let e=`resolving`,i,a=n.renderMentionChip({ref:t,status:e,payload:i,remove:r});return{get el(){return a},setStatus:(o,s)=>{if(o===e&&s===i)return;e=o,i=s;let c=n.renderMentionChip({ref:t,status:e,payload:i,remove:r});a.replaceWith(c),a=c}}}let i=t.iconName??n.chipIconName??`at-sign`,a=V(`div`,{className:`persona-mention-chip`,attrs:{"data-persona-mention-chip":``,"data-status":`resolving`,title:t.label}}),o=B(`span`,`persona-mention-chip-icon`),s=e=>{o.replaceChildren();let t=_s(e,13,`currentColor`,2);t&&o.appendChild(t)};s(i);let c=B(`span`,`persona-mention-chip-spinner`),l=V(`span`,{className:`persona-mention-chip-label`,text:t.label}),d=V(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label} context`}}),f=j(u.X,11,`currentColor`,2.5);return f?d.appendChild(f):d.textContent=`×`,d.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(c),a.appendChild(l),a.appendChild(d),{el:a,setStatus:e=>{a.setAttribute(`data-status`,e),e===`resolving`?(c.parentNode!==a&&a.insertBefore(c,l),o.parentNode===a&&o.remove(),a.setAttribute(`title`,t.label)):(c.parentNode===a&&c.remove(),o.parentNode!==a&&a.insertBefore(o,l),e===`error`?(s(`triangle-alert`),a.setAttribute(`title`,`Couldn't add ${t.label} to context`)):(s(i),a.setAttribute(`title`,t.label)))}}}var bs=o((()=>{H(),ee(),vs()}));function xs(e){e.style.display=e.childElementCount>0?`flex`:`none`}function Ss(e){let t=e.querySelector(Cs);if(t)return t;let n=V(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}var Cs,ws=o((()=>{H(),Cs=`[data-persona-composer-chip-row]`}));function Ts(e){let t=0;for(let n of e.split(`
|
|
13
|
+
`)){let e=/^ {0,3}(`+)/.exec(n);e&&e[1].length>t&&(t=e[1].length)}return t}function Es(e,t){let n="`".repeat(Math.max(3,Ts(t)+1));return`${n}${e}\n${t}\n${n}`}function Ds(e,t,n){return t.includes(`</document_content>`)?Es(e,t):`<document index="${n+1}">\n<source>${e}</source>\n<document_content>\n${t}\n</document_content>\n</document>`}function Os(e,t,n=`fenced`){if(typeof n==`function`)try{return n(e,t)}catch(t){return console.warn(`[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention`,t),Es(e.label,e.text)}return n===`document`?Ds(e.label,e.text,t):Es(e.label,e.text)}var ks=o((()=>{}));function As(e,t){return{sourceId:e.id,itemId:t.id,label:t.label,iconName:t.iconName,color:t.color}}var js,Ms,Ns=o((()=>{bs(),ws(),ks(),js=(e,t)=>`${e}\u0000${t}`,Ms=class{#e;constructor(e){this.mentions=[],this.#e=e,this.#o()}get#t(){return this.#e.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,t,n=``){let r=js(e.id,t.id);if(this.mentions.some(e=>e.key===r))return this.#n(e,t,`duplicate`);if(this.atLimit())return this.#n(e,t,`limit`);let i=As(e,t),a={key:r,source:e,item:t,ref:i,status:`resolving`,args:n};return a.chip=ys({ref:i,config:this.#e.mentionConfig,onRemove:()=>this.remove(r)}),a.chip.el.setAttribute(`data-persona-chip-enter`,``),a.chip.el.addEventListener(`animationend`,()=>a.chip?.el.removeAttribute(`data-persona-chip-enter`),{once:!0}),this.#e.contextRow.appendChild(a.chip.el),this.#r(a),this.#o(),!0}atLimit(){return this.mentions.length>=this.#t}admit(e,t){return!this.atLimit()||this.#n(e,t,`limit`)}track(e,t,n,r=``,i){let a={key:e,source:t,item:n,ref:As(t,n),status:`resolving`,args:r,reportStatus:i};this.#r(a)}#n(e,t,n){return this.#e.mentionConfig.onMentionRejected?.(t,n),this.#e.emit?.(`rejected`,{sourceId:e.id,itemId:t.id,reason:n}),!1}#r(e){this.mentions.push(e),e.source.resolveOn===`submit`?(e.status=`ready`,e.chip?.setStatus(`ready`),e.reportStatus?.(`resolved`)):e.resolvePromise=this.#a(e),this.#e.announce(`Added ${e.ref.label} to context`)}#i(e,t,n=this.#e.getComposerText()){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:n,args:t,signal:e}}async#a(e){let t=new AbortController;e.abort=t;try{let n=await e.source.resolve(e.item,this.#i(t.signal,e.args));if(t.signal.aborted)return;e.payload=n,e.status=`ready`,e.chip?.setStatus(`ready`,n),e.reportStatus?.(`resolved`)}catch(n){if(t.signal.aborted)return;e.status=`error`,e.chip?.setStatus(`error`),e.reportStatus?.(`error`),(this.#e.announceError??this.#e.announce)(`Couldn't attach ${e.ref.label} to context`),this.#e.mentionConfig.onMentionResolveError?.(e.item,n),this.#e.emit?.(`resolve-error`,{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let t=this.mentions.findIndex(t=>t.key===e);if(t===-1)return;let[n]=this.mentions.splice(t,1);n.abort?.abort(),n.chip?.el.remove(),this.#o(),this.#e.announce(`Removed ${n.ref.label} from context`)}getRefs(){return this.mentions.map(e=>e.ref)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.#o()}collectForSubmit(){let e=[...this.mentions],t=e.map(e=>e.ref),n=this.#e.getComposerText();for(let t of e)t.chip?.el.remove();return this.mentions.length=0,this.#o(),{refs:t,finalize:async()=>{let t=await Promise.all(e.map(async e=>{try{return e.source.resolveOn===`submit`?await e.source.resolve(e.item,this.#i(new AbortController().signal,e.args,n)):(e.resolvePromise&&await e.resolvePromise,e.payload??null)}catch(t){try{this.#e.mentionConfig.onMentionResolveError?.(e.item,t)}catch(e){typeof console<`u`&&console.warn(`[Persona] onMentionResolveError callback threw`,e)}return this.#e.emit?.(`resolve-error`,{sourceId:e.source.id,itemId:e.item.id}),null}})),r=[],i=[],a={},o=/* @__PURE__ */ new Set;for(let n=0;n<e.length;n++){let s=e[n],c=t[n];if(!c)continue;let l=js(s.source.id,s.item.id);if(!o.has(l)){if(o.add(l),c.llmAppend&&c.llmAppend.trim())try{r.push(Os({label:s.ref.label,text:c.llmAppend,ref:s.ref,item:s.item},r.length,this.#e.mentionConfig.llmFormat))}catch(e){typeof console<`u`&&console.warn(`[Persona] context-mention llmFormat threw`,e)}c.contentParts?.length&&i.push(...c.contentParts),c.context&&((a[s.source.id]??={})[s.item.id]=c.context)}}return{blocks:r,contentParts:i,context:a}}}}#o(){xs(this.#e.contextRow)}}}));function Ps(e){let t=e.getRootNode?.();return t&&Vs(t)||t&&Bs(t)?t:e.ownerDocument??document}function Fs(e,t,n){let r=Bs(e)?e.head:e,i=t.replace(/["\\]/g,`\\$&`);if(r.querySelector(`style[data-persona-plugin-style="${i}"]`))return;let a=(Bs(e)?e:e.ownerDocument??document).createElement(`style`);a.setAttribute(`data-persona-plugin-style`,t),a.textContent=n,r.appendChild(a)}function Is(e,t,n){if(Bs(e)||Vs(e)){Fs(e,t,n);return}let r=e;if(r.isConnected){Fs(Ps(r),t,n);return}let i=r.ownerDocument??document;Fs(i,t,n),queueMicrotask(()=>{let e=Ps(r);e!==i&&Fs(e,t,n)})}function Ls(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Rs(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??Ls(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}function zs(e){return(typeof e.composedPath==`function`?e.composedPath():[]).some(e=>e instanceof HTMLElement&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable))}var Bs,Vs,Hs=o((()=>{Bs=e=>e.nodeType===Node.DOCUMENT_NODE,Vs=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host!==void 0})),Us,Ws=o((()=>{Us=`
|
|
14
14
|
.persona-mention-menu {
|
|
15
15
|
box-sizing: border-box;
|
|
16
16
|
display: flex;
|
|
@@ -168,32 +168,32 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
168
168
|
min-height: 36px;
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
|
-
`}));function Ls(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 Rs=o((()=>{}));function zs(e){let{config:t,listboxId:n}=e,r=B(`div`,{className:`persona-mention-menu`,attrs:{"data-persona-mention-menu":``}}),i=B(`div`,{className:`persona-mention-search`,style:{display:`none`}}),a=z(`span`,`persona-mention-search-icon`),o=h(u.Search,15,`currentColor`,2);o&&a.appendChild(o);let s=B(`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…`,autocomplete:`off`,autocapitalize:`off`,spellcheck:`false`}});i.append(a,s),s.addEventListener(`input`,()=>e.onSearchInput?.(s.value)),s.addEventListener(`keydown`,t=>e.onSearchKeydown?.(t));let c=B(`div`,{className:`persona-mention-list`,attrs:{role:`listbox`,id:n,"aria-label":`Context mentions`}});r.append(i,c);let l=[],d=[],f=-1,p=/* @__PURE__ */ new Map,m=(e,t)=>`${e}${t}`,g=e=>`${n}-opt-${e}`,_=e=>`${n}-grp-${e}`,v=(e,t)=>{let n=l[e];n&&(t?n.setAttribute(`data-active`,`true`):n.removeAttribute(`data-active`),n.setAttribute(`aria-selected`,t?`true`:`false`),d[e]?.(t))},y=(e,t=!0)=>{f>=0&&f!==e&&v(f,!1),f=e;let n=l[e];n?(v(e,!0),t&&n.scrollIntoView?.({block:`nearest`}),c.setAttribute(`aria-activedescendant`,n.id),s.setAttribute(`aria-activedescendant`,n.id)):(c.removeAttribute(`aria-activedescendant`),s.removeAttribute(`aria-activedescendant`))},b=(e,t)=>{let n=_(t),r=B(`div`,{className:`persona-mention-group`,attrs:{role:`group`,"aria-labelledby":n}});return r.appendChild(B(`div`,{className:`persona-mention-group-header`,attrs:{id:n},text:e})),r},x=()=>{let n=B(`div`,{className:`persona-mention-option`,attrs:{role:`option`,"aria-selected":`false`}}),r=z(`span`,`persona-mention-option-icon`);n.appendChild(r);let i=``,a=z(`span`,`persona-mention-option-text`),o=z(`span`,`persona-mention-option-labelline`),s=z(`span`,`persona-mention-option-label`);o.appendChild(s),a.appendChild(o),n.appendChild(a);let c=null,l=null,u={el:n,index:0,update:(e,d,f)=>{u.index=d,n.id=g(d),n.setAttribute(`aria-setsize`,String(f)),n.setAttribute(`aria-posinset`,String(d+1)),n.removeAttribute(`data-active`),n.setAttribute(`aria-selected`,`false`);let p=e.iconName??t.chipIconName??`at-sign`;if(p!==i){i=p;let e=Vs(p,15,2);r.replaceChildren(...e?[e]:[])}s.textContent!==e.label&&(s.textContent=e.label);let m=e.commandArgsPlaceholder?`‹${e.commandArgsPlaceholder}›`:null;m?(c||(c=z(`span`,`persona-mention-option-arghint`),o.appendChild(c)),c.textContent!==m&&(c.textContent=m)):c&&=(c.remove(),null),e.description?(l||(l=z(`span`,`persona-mention-option-desc`),a.appendChild(l)),l.textContent!==e.description&&(l.textContent=e.description)):l&&=(l.remove(),null)}};return n.addEventListener(`mousedown`,t=>{t.button===0&&(t.preventDefault(),e.onSelectIndex(u.index))}),n.addEventListener(`mouseenter`,()=>e.onHoverIndex(u.index)),u},S=(n,r,i,a,o)=>{let s=B(`div`,{className:`persona-mention-option`,attrs:{role:`option`,id:g(a),"aria-selected":`false`,"aria-setsize":String(o),"aria-posinset":String(a+1)}}),c=e=>{s.replaceChildren(t.renderMentionItem({item:n,source:r,query:i,active:e,index:a}))};return c(!1),s.addEventListener(`mousedown`,t=>{t.button===0&&(t.preventDefault(),e.onSelectIndex(a))}),s.addEventListener(`mouseenter`,()=>e.onHoverIndex(a)),{el:s,paint:c}},C=t=>{let n=B(`div`,{className:`persona-mention-status persona-mention-error`});if(n.appendChild(B(`span`,{className:`persona-mention-error-text`,text:`Couldn't load ${t.label}`})),e.onRetry){let r=B(`button`,{className:`persona-mention-retry`,attrs:{type:`button`},text:`Retry`});r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n=>{n.preventDefault(),e.onRetry(t.id)}),n.appendChild(r)}return n};return{el:r,render:e=>{c.replaceChildren(),l=[],d=[],f=-1;let n=/* @__PURE__ */ new Set,r=0,i=0,a=0,o=0,u=0,h=e.groups.reduce((e,t)=>t.status===`ready`?e+t.items.length:e,0);for(let s of e.groups)if(s.status===`loading`){a++;let e=b(s.source.label,u++);e.appendChild(B(`div`,{className:`persona-mention-status persona-mention-loading`,attrs:{role:`presentation`},text:`Loading…`})),c.appendChild(e)}else if(s.status===`error`){o++;let e=b(s.source.label,u++);e.appendChild(C(s.source)),c.appendChild(e)}else if(s.status===`ready`&&s.items.length>0){let a=/* @__PURE__ */ new Map;for(let e of s.items){let t=e.group??s.source.label,n=a.get(t);n?n.push(e):a.set(t,[e])}let o=Array.from(a.entries());o.forEach(([a,f],g)=>{let _=b(a,u++);for(let a of f){let o=r++,c;if(t.renderMentionItem){let t=S(a,s.source,e.query,o,h);c=t.el,d.push(t.paint)}else{let e=m(s.source.id,a.id),t=n.has(e)?void 0:p.get(e);t||(t=x(),n.has(e)||p.set(e,t)),n.add(e),t.update(a,o,h),c=t.el,d.push(null)}l.push(c),_.appendChild(c),i++}s.truncated&&g===o.length-1&&_.appendChild(B(`div`,{className:`persona-mention-hint`,attrs:{role:`presentation`},text:`Keep typing to narrow…`})),c.appendChild(_)})}for(let e of p.keys())n.has(e)||p.delete(e);i===0&&a===0&&o===0&&c.appendChild(B(`div`,{className:`persona-mention-empty`,attrs:{role:`presentation`},text:`No matches`})),l.length>0?y(Math.min(Math.max(0,e.activeIndex),l.length-1)):(c.removeAttribute(`aria-activedescendant`),s.removeAttribute(`aria-activedescendant`))},setActiveIndex:y,destroy:()=>{c.replaceChildren(),l=[],p.clear(),r.remove()},showSearch:(e,t)=>{s.value=e,t&&(s.placeholder=t),i.style.display=``,s.setAttribute(`aria-expanded`,`true`),s.focus(),typeof requestAnimationFrame==`function`&&requestAnimationFrame(()=>{i.style.display!==`none`&&s.focus()})},hideSearch:()=>{i.style.display=`none`,s.value=``,s.setAttribute(`aria-expanded`,`false`),s.removeAttribute(`aria-activedescendant`)}}}var Bs,Vs,Hs=o((()=>{H(),g(),us(),Bs=/* @__PURE__ */ new Map,Vs=(e,t,n)=>{let r=`${e}|${t}|${n}`,i=Bs.get(r);return i===void 0&&(i=ls(e,t,`currentColor`,n),Bs.set(r,i)),i?i.cloneNode(!0):null}})),Us,Ws,Gs,Ks=o((()=>{Ps(),Is(),mo(),go(),Rs(),Hs(),Ts(),Us=e=>!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`,Ws=0,Gs=class{#e;#t;#n;#r;#i;#a;#o;#s=null;#c=null;#l=!1;#u=``;#d=null;#f=0;#p=null;#m=!1;#h=null;#g=[];#_=[];#v=0;#y=null;#b=null;#x=/* @__PURE__ */ new Set;#S=/* @__PURE__ */ new Set;#C=-1;#w=null;#T=null;constructor(e){this.#e=e;let t=e.mentionConfig,n=ho(t),r=n.filter(e=>e.sources.length>0);this.#t=r.length>0?r:[n[0]],this.#n=this.#t[0],this.#r=t.maxItemsPerGroup??6,this.#i=t.searchDebounceMs??150,this.#o=`persona-mention-listbox-${++Ws}`,this.#a=e.mentionConfig.renderMentionMenu?this.#E():zs({config:e.mentionConfig,listboxId:this.#o,onSelectIndex:e=>this.#G(e),onHoverIndex:e=>this.#H(e,!1),onRetry:e=>this.#W(e),onSearchInput:e=>this.#N(e),onSearchKeydown:e=>{this.handleKeydown(e)}});let i=e.composerInput.element;i.setAttribute(`aria-haspopup`,`listbox`),i.setAttribute(`aria-controls`,this.#o)}get input(){return this.#e.composerInput}#E(){let e=document.createElement(`div`);e.setAttribute(`data-persona-mention-menu`,``),e.setAttribute(`role`,`listbox`),e.id=this.#o;let t=()=>{let t=this.#e.mentionConfig.renderMentionMenu({query:this.#u,groups:this.#g.map(e=>({source:e.source,items:e.items})),status:Object.fromEntries(this.#g.map(e=>[e.source.id,e.status])),activeIndex:this.#f,select:e=>{let t=this.#g.find(t=>t.items.includes(e));t&&this.#J(t.source,e)},close:()=>this.close()});e.replaceChildren(t)};return{el:e,render:t,setActiveIndex:t,destroy:()=>e.remove()}}isOpen(){return this.#l}openFromButton(e){let t=e&&this.#t.find(t=>t.trigger===e)||this.#t[0],n=this.input.getSelection().start,r=lo(this.input.getLogicalText(),n,[t]);if(r){this.#m=!1,this.#d=r.match,this.#l?(this.#D(t),this.#N(r.match.query)):this.#O(r.match.query,t),this.input.focus();return}let i=this.#h;this.#m=!0,this.#h=t.trigger,this.#d=null,this.#l?(i&&i!==t.trigger&&this.#e.onPickerOpenChange?.(!1,i,this.#o),this.#D(t),this.#N(``)):this.#O(``,t),this.#a.showSearch?this.#a.showSearch(``,t.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,t.trigger,this.#o)}onInput(){let e=this.input.getSelection().start,t=lo(this.input.getLogicalText(),e,this.#t);t?this.#Q(t.channel,t.match.query)?(this.#d=null,this.#l&&this.close(!1)):(this.#d=t.match,this.#l?(this.#D(t.channel),this.#T!==t.match.triggerIndex&&this.#M(),this.#N(t.match.query)):this.#O(t.match.query,t.channel)):this.#l&&this.close()}#D(e){e!==this.#n&&(this.#n=e,this.#g=[],this.#f=0)}#O(e,t){if(this.#l=!0,this.#n=t,this.#g=[],this.#f=0,this.#C=-1,!this.#s){let e=this.#j();if(this.#s=As({anchor:this.#e.anchor,content:this.#a.el,placement:`top-start`,matchAnchorWidth:!e,offset:6,container:this.#e.popoverContainer,horizontalOffset:e?()=>this.#w?.x??null:void 0,verticalOffset:e?()=>this.#w?.y??null:void 0,onDismiss:()=>this.close(!1)}),e){let e=this.#e.anchor.getBoundingClientRect().width;this.#a.el.style.minWidth=`${Math.min(220,e)}px`}}this.#M(),this.#s.open(),Os(this.#a.el,`persona-mention-menu`,Fs),this.#k(),this.#e.emit?.(`opened`,{trigger:t.trigger}),this.#N(e)}#k(){typeof ResizeObserver>`u`||this.#c||(this.#c=new ResizeObserver(()=>{this.#l&&(this.#M(),this.#s?.reposition())}),this.#c.observe(this.#e.anchor))}#A(){this.#c?.disconnect(),this.#c=null}#j(){return this.#Y()&&!!this.input.getLogicalRangeRect}#M(){let e=this.#d,t=this.input.getLogicalRangeRect;if(this.#T=e?.triggerIndex??null,this.#w=null,!e||!t)return;let n=t(e.triggerIndex,e.triggerIndex+1);if(!n)return;let r=this.#e.anchor.getBoundingClientRect(),i=n.top-r.top,a=this.input.element,o=typeof getComputedStyle==`function`&&getComputedStyle(a).direction===`rtl`;this.#w={x:o?null:n.left-r.left,y:i}}close(e=!0){this.#l&&(this.#l=!1,this.#A(),this.#b&&clearTimeout(this.#b),this.#y?.abort(),this.#v++,this.#s?.close(),this.input.element.removeAttribute(`aria-activedescendant`),this.#m&&(this.#m=!1,this.#a.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#h??this.#n.trigger,this.#o),this.#h=null,e&&this.input.focus()))}#N(e){this.#u=e,this.#f=0,this.#p=null;let t=++this.#v;this.#S.clear(),this.#y?.abort(),this.#y=new AbortController;for(let e of this.#n.sources)this.#x.has(e.id)?this.#I(e.id,`loading`):(this.#S.add(e.id),this.#P(e,t));this.#V(),this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{if(t===this.#v)for(let e of this.#n.sources)this.#x.has(e.id)&&!this.#S.has(e.id)&&this.#P(e,t)},this.#i)}#P(e,t){let n={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#y.signal},r;try{r=e.search(this.#u,n)}catch{this.#I(e.id,`error`),this.#V();return}Us(r)?(this.#x.add(e.id),this.#I(e.id,`loading`),r.then(n=>{t===this.#v&&(this.#L(e.id,n),this.#V())}).catch(()=>{t===this.#v&&(this.#I(e.id,`error`),this.#V())})):this.#L(e.id,r)}#F(e){let t=this.#g.find(t=>t.source.id===e.id);if(!t){t={source:e,items:[],status:`loading`,truncated:!1};let n=this.#n.sources;this.#g.push(t),this.#g.sort((e,t)=>n.findIndex(t=>t.id===e.source.id)-n.findIndex(e=>e.id===t.source.id))}return t}#I(e,t){let n=this.#n.sources.find(t=>t.id===e);n&&(this.#F(n).status=t)}#L(e,t){let n=this.#n.sources.find(t=>t.id===e);if(!n)return;let r=this.#F(n);r.truncated=t.length>this.#r,r.items=t.slice(0,this.#r),r.status=r.items.length===0?`empty`:`ready`}#R(e){return JSON.stringify([e.source.id,e.item.id])}#z(){this.#_=[];for(let e of this.#g)if(e.status===`ready`)for(let t of e.items)this.#_.push({source:e.source,item:t});if(this.#p){let e=this.#_.findIndex(e=>this.#R(e)===this.#p);this.#f=e>=0?e:Math.min(this.#f,Math.max(0,this.#_.length-1))}else this.#f>=this.#_.length&&(this.#f=Math.max(0,this.#_.length-1))}#B(){return{query:this.#u,groups:this.#g,activeIndex:this.#f}}#V(){this.#z(),this.#a.render(this.#B()),this.#U(),this.#s?.reposition();let e=this.#g.some(e=>e.status===`loading`);this.#_.length===0&&e||this.#_.length!==this.#C&&(this.#C=this.#_.length,this.#e.announce(this.#_.length===0?`No matches`:this.#_.length===1?`1 result`:`${this.#_.length} results`),this.#e.emit?.(`searched`,{query:this.#u,results:this.#_.length}))}#H(e,t=!0){e<0||e>=this.#_.length||(this.#f=e,this.#p=this.#R(this.#_[e]),this.#a.setActiveIndex(e,t),this.#U())}#U(){this.#l&&!this.#m&&this.#f>=0&&this.#f<this.#_.length?this.input.element.setAttribute(`aria-activedescendant`,`${this.#o}-opt-${this.#f}`):this.input.element.removeAttribute(`aria-activedescendant`)}#W(e){let t=this.#n.sources.find(t=>t.id===e);t&&this.#y&&(this.#I(e,`loading`),this.#V(),this.#P(t,this.#v),this.#V())}handleKeydown(e){if(!this.#l)return!1;switch(e.key){case`ArrowDown`:return this.#_.length===0||(e.preventDefault(),this.#H((this.#f+1)%this.#_.length)),!0;case`ArrowUp`:return this.#_.length===0||(e.preventDefault(),this.#H((this.#f-1+this.#_.length)%this.#_.length)),!0;case`Home`:return this.#_.length===0||(e.preventDefault(),this.#H(0)),!0;case`End`:return this.#_.length===0||(e.preventDefault(),this.#H(this.#_.length-1)),!0;case`Enter`:case`Tab`:return this.#_.length===0?(this.close(),!1):(e.preventDefault(),this.#G(this.#f),!0);case`Escape`:return e.preventDefault(),this.close(),!0;case`Backspace`:return this.#u.length===0&&this.close(),!1;default:return!1}}#G(e){let t=this.#_[e];t&&this.#J(t.source,t.item)}#K(e){return Ls(e).args}#q(e){return e.command===`server`||e.commandArgsPlaceholder!=null}#J(e,t){let n=t.command;if(this.#q(t))this.#Z(e,t);else if(n===`action`){let n=this.#K(this.#u);this.#ie(),this.close(),this.#te(t,n),this.#e.emit?.(`command`,{sourceId:e.id,itemId:t.id,kind:`action`,args:n}),this.input.focus()}else if(n===`prompt`){let n=this.#K(this.#u),r=this.#ne();this.close(),this.#re(e,t,n,r),this.#e.emit?.(`command`,{sourceId:e.id,itemId:t.id,kind:`prompt`,args:n})}else this.#Y()?this.#X(e,t):(this.#e.onSelect(e,t,``)&&(this.#ie(),this.#e.emit?.(`selected`,{sourceId:e.id,itemId:t.id,label:t.label})),this.close(),this.input.focus())}#Y(){return this.#e.mentionConfig.display===`inline`&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#X(e,t){if(this.#e.admitMention&&!this.#e.admitMention(e,t)){this.close(),this.input.focus();return}let n=Ss(e,t),r=this.#d?this.input.insertMentionAtTrigger(n,this.#d):this.input.insertMentionAtSelection?.(n)??null;r?(this.#e.onInsertMention(r,e,t,``),this.#e.emit?.(`selected`,{sourceId:e.id,itemId:t.id,label:t.label})):(this.#e.mentionConfig.onMentionRejected?.(t,`stale`),this.#e.emit?.(`rejected`,{sourceId:e.id,itemId:t.id,reason:`stale`})),this.#d=null,this.close(),this.input.focus()}#Z(e,t){let n=`${this.#n.trigger}${t.label} `,r=this.input.getSelection().start,i=this.#d?this.#d.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(i,r,n);else{let e=this.input.getValue();this.input.setValueWithCaret(e.slice(0,i)+n+e.slice(r),i+n.length)}this.#d=null,this.close(),this.#e.emit?.(`command`,{sourceId:e.id,itemId:t.id,kind:t.command??`prompt`,phase:`armed`}),this.input.dispatchInput(),this.input.focus()}#Q(e,t){let{name:n}=Ls(t);return!n||t.length<=n.length?!1:e.sources.some(e=>{let t=e.matchCommand?.(n);return!!t&&this.#q(t)})}#$(e){for(let t of this.#t){if(!t.trigger)continue;let n=t.position===`anywhere`?[e]:t.position===`line-start`?e.split(`
|
|
171
|
+
`}));function Gs(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 Ks=o((()=>{}));function qs(e){let{config:t,listboxId:n}=e,r=V(`div`,{className:`persona-mention-menu`,attrs:{"data-persona-mention-menu":``}}),i=V(`div`,{className:`persona-mention-search`,style:{display:`none`}}),a=B(`span`,`persona-mention-search-icon`),o=j(u.Search,15,`currentColor`,2);o&&a.appendChild(o);let s=V(`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…`,autocomplete:`off`,autocapitalize:`off`,spellcheck:`false`}});i.append(a,s),s.addEventListener(`input`,()=>e.onSearchInput?.(s.value)),s.addEventListener(`keydown`,t=>e.onSearchKeydown?.(t));let c=V(`div`,{className:`persona-mention-list`,attrs:{role:`listbox`,id:n,"aria-label":`Context mentions`}});r.append(i,c);let l=[],d=[],f=-1,p=/* @__PURE__ */ new Map,m=(e,t)=>`${e}${t}`,h=e=>`${n}-opt-${e}`,g=e=>`${n}-grp-${e}`,_=(e,t)=>{let n=l[e];n&&(t?n.setAttribute(`data-active`,`true`):n.removeAttribute(`data-active`),n.setAttribute(`aria-selected`,t?`true`:`false`),d[e]?.(t))},v=(e,t=!0)=>{f>=0&&f!==e&&_(f,!1),f=e;let n=l[e];n?(_(e,!0),t&&n.scrollIntoView?.({block:`nearest`}),c.setAttribute(`aria-activedescendant`,n.id),s.setAttribute(`aria-activedescendant`,n.id)):(c.removeAttribute(`aria-activedescendant`),s.removeAttribute(`aria-activedescendant`))},y=(e,t)=>{let n=g(t),r=V(`div`,{className:`persona-mention-group`,attrs:{role:`group`,"aria-labelledby":n}});return r.appendChild(V(`div`,{className:`persona-mention-group-header`,attrs:{id:n},text:e})),r},b=()=>{let n=V(`div`,{className:`persona-mention-option`,attrs:{role:`option`,"aria-selected":`false`}}),r=B(`span`,`persona-mention-option-icon`);n.appendChild(r);let i=``,a=B(`span`,`persona-mention-option-text`),o=B(`span`,`persona-mention-option-labelline`),s=B(`span`,`persona-mention-option-label`);o.appendChild(s),a.appendChild(o),n.appendChild(a);let c=null,l=null,u={el:n,index:0,update:(e,d,f)=>{u.index=d,n.id=h(d),n.setAttribute(`aria-setsize`,String(f)),n.setAttribute(`aria-posinset`,String(d+1)),n.removeAttribute(`data-active`),n.setAttribute(`aria-selected`,`false`);let p=e.iconName??t.chipIconName??`at-sign`;if(p!==i){i=p;let e=Ys(p,15,2);r.replaceChildren(...e?[e]:[])}s.textContent!==e.label&&(s.textContent=e.label);let m=e.commandArgsPlaceholder?`‹${e.commandArgsPlaceholder}›`:null;m?(c||(c=B(`span`,`persona-mention-option-arghint`),o.appendChild(c)),c.textContent!==m&&(c.textContent=m)):c&&=(c.remove(),null),e.description?(l||(l=B(`span`,`persona-mention-option-desc`),a.appendChild(l)),l.textContent!==e.description&&(l.textContent=e.description)):l&&=(l.remove(),null)}};return n.addEventListener(`mousedown`,t=>{t.button===0&&(t.preventDefault(),e.onSelectIndex(u.index))}),n.addEventListener(`mouseenter`,()=>e.onHoverIndex(u.index)),u},x=(n,r,i,a,o)=>{let s=V(`div`,{className:`persona-mention-option`,attrs:{role:`option`,id:h(a),"aria-selected":`false`,"aria-setsize":String(o),"aria-posinset":String(a+1)}}),c=e=>{s.replaceChildren(t.renderMentionItem({item:n,source:r,query:i,active:e,index:a}))};return c(!1),s.addEventListener(`mousedown`,t=>{t.button===0&&(t.preventDefault(),e.onSelectIndex(a))}),s.addEventListener(`mouseenter`,()=>e.onHoverIndex(a)),{el:s,paint:c}},S=t=>{let n=V(`div`,{className:`persona-mention-status persona-mention-error`});if(n.appendChild(V(`span`,{className:`persona-mention-error-text`,text:`Couldn't load ${t.label}`})),e.onRetry){let r=V(`button`,{className:`persona-mention-retry`,attrs:{type:`button`},text:`Retry`});r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n=>{n.preventDefault(),e.onRetry(t.id)}),n.appendChild(r)}return n};return{el:r,render:e=>{c.replaceChildren(),l=[],d=[],f=-1;let n=/* @__PURE__ */ new Set,r=0,i=0,a=0,o=0,u=0,h=e.groups.reduce((e,t)=>t.status===`ready`?e+t.items.length:e,0);for(let s of e.groups)if(s.status===`loading`){a++;let e=y(s.source.label,u++);e.appendChild(V(`div`,{className:`persona-mention-status persona-mention-loading`,attrs:{role:`presentation`},text:`Loading…`})),c.appendChild(e)}else if(s.status===`error`){o++;let e=y(s.source.label,u++);e.appendChild(S(s.source)),c.appendChild(e)}else if(s.status===`ready`&&s.items.length>0){let a=/* @__PURE__ */ new Map;for(let e of s.items){let t=e.group??s.source.label,n=a.get(t);n?n.push(e):a.set(t,[e])}let o=Array.from(a.entries());o.forEach(([a,f],g)=>{let _=y(a,u++);for(let a of f){let o=r++,c;if(t.renderMentionItem){let t=x(a,s.source,e.query,o,h);c=t.el,d.push(t.paint)}else{let e=m(s.source.id,a.id),t=n.has(e)?void 0:p.get(e);t||(t=b(),n.has(e)||p.set(e,t)),n.add(e),t.update(a,o,h),c=t.el,d.push(null)}l.push(c),_.appendChild(c),i++}s.truncated&&g===o.length-1&&_.appendChild(V(`div`,{className:`persona-mention-hint`,attrs:{role:`presentation`},text:`Keep typing to narrow…`})),c.appendChild(_)})}for(let e of p.keys())n.has(e)||p.delete(e);i===0&&a===0&&o===0&&c.appendChild(V(`div`,{className:`persona-mention-empty`,attrs:{role:`presentation`},text:`No matches`})),l.length>0?v(Math.min(Math.max(0,e.activeIndex),l.length-1)):(c.removeAttribute(`aria-activedescendant`),s.removeAttribute(`aria-activedescendant`))},setActiveIndex:v,destroy:()=>{c.replaceChildren(),l=[],p.clear(),r.remove()},showSearch:(e,t)=>{s.value=e,t&&(s.placeholder=t),i.style.display=``,s.setAttribute(`aria-expanded`,`true`),s.focus(),typeof requestAnimationFrame==`function`&&requestAnimationFrame(()=>{i.style.display!==`none`&&s.focus()})},hideSearch:()=>{i.style.display=`none`,s.value=``,s.setAttribute(`aria-expanded`,`false`),s.removeAttribute(`aria-activedescendant`)}}}var Js,Ys,Xs=o((()=>{H(),ee(),vs(),Js=/* @__PURE__ */ new Map,Ys=(e,t,n)=>{let r=`${e}|${t}|${n}`,i=Js.get(r);return i===void 0&&(i=_s(e,t,`currentColor`,n),Js.set(r,i)),i?i.cloneNode(!0):null}})),Zs,Qs,$s,ec=o((()=>{Hs(),Ws(),So(),wo(),Ks(),Xs(),Ns(),Zs=e=>!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`,Qs=0,$s=class{#e;#t;#n;#r;#i;#a;#o;#s=null;#c=null;#l=!1;#u=``;#d=null;#f=0;#p=null;#m=!1;#h=null;#g=[];#_=[];#v=0;#y=null;#b=null;#x=/* @__PURE__ */ new Set;#S=/* @__PURE__ */ new Set;#C=-1;#w=null;#T=null;constructor(e){this.#e=e;let t=e.mentionConfig,n=Co(t),r=n.filter(e=>e.sources.length>0);this.#t=r.length>0?r:[n[0]],this.#n=this.#t[0],this.#r=t.maxItemsPerGroup??6,this.#i=t.searchDebounceMs??150,this.#o=`persona-mention-listbox-${++Qs}`,this.#a=e.mentionConfig.renderMentionMenu?this.#E():qs({config:e.mentionConfig,listboxId:this.#o,onSelectIndex:e=>this.#G(e),onHoverIndex:e=>this.#H(e,!1),onRetry:e=>this.#W(e),onSearchInput:e=>this.#N(e),onSearchKeydown:e=>{this.handleKeydown(e)}});let i=e.composerInput.element;i.setAttribute(`aria-haspopup`,`listbox`),i.setAttribute(`aria-controls`,this.#o)}get input(){return this.#e.composerInput}#E(){let e=document.createElement(`div`);e.setAttribute(`data-persona-mention-menu`,``),e.setAttribute(`role`,`listbox`),e.id=this.#o;let t=()=>{let t=this.#e.mentionConfig.renderMentionMenu({query:this.#u,groups:this.#g.map(e=>({source:e.source,items:e.items})),status:Object.fromEntries(this.#g.map(e=>[e.source.id,e.status])),activeIndex:this.#f,select:e=>{let t=this.#g.find(t=>t.items.includes(e));t&&this.#J(t.source,e)},close:()=>this.close()});e.replaceChildren(t)};return{el:e,render:t,setActiveIndex:t,destroy:()=>e.remove()}}isOpen(){return this.#l}openFromButton(e){let t=e&&this.#t.find(t=>t.trigger===e)||this.#t[0],n=this.input.getSelection().start,r=vo(this.input.getLogicalText(),n,[t]);if(r){this.#m=!1,this.#d=r.match,this.#l?(this.#D(t),this.#N(r.match.query)):this.#O(r.match.query,t),this.input.focus();return}let i=this.#h;this.#m=!0,this.#h=t.trigger,this.#d=null,this.#l?(i&&i!==t.trigger&&this.#e.onPickerOpenChange?.(!1,i,this.#o),this.#D(t),this.#N(``)):this.#O(``,t),this.#a.showSearch?this.#a.showSearch(``,t.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,t.trigger,this.#o)}onInput(){let e=this.input.getSelection().start,t=vo(this.input.getLogicalText(),e,this.#t);t?this.#Q(t.channel,t.match.query)?(this.#d=null,this.#l&&this.close(!1)):(this.#d=t.match,this.#l?(this.#D(t.channel),this.#T!==t.match.triggerIndex&&this.#M(),this.#N(t.match.query)):this.#O(t.match.query,t.channel)):this.#l&&this.close()}#D(e){e!==this.#n&&(this.#n=e,this.#g=[],this.#f=0)}#O(e,t){if(this.#l=!0,this.#n=t,this.#g=[],this.#f=0,this.#C=-1,!this.#s){let e=this.#j();if(this.#s=Rs({anchor:this.#e.anchor,content:this.#a.el,placement:`top-start`,matchAnchorWidth:!e,offset:6,container:this.#e.popoverContainer,horizontalOffset:e?()=>this.#w?.x??null:void 0,verticalOffset:e?()=>this.#w?.y??null:void 0,onDismiss:()=>this.close(!1)}),e){let e=this.#e.anchor.getBoundingClientRect().width;this.#a.el.style.minWidth=`${Math.min(220,e)}px`}}this.#M(),this.#s.open(),Is(this.#a.el,`persona-mention-menu`,Us),this.#k(),this.#e.emit?.(`opened`,{trigger:t.trigger}),this.#N(e)}#k(){typeof ResizeObserver>`u`||this.#c||(this.#c=new ResizeObserver(()=>{this.#l&&(this.#M(),this.#s?.reposition())}),this.#c.observe(this.#e.anchor))}#A(){this.#c?.disconnect(),this.#c=null}#j(){return this.#Y()&&!!this.input.getLogicalRangeRect}#M(){let e=this.#d,t=this.input.getLogicalRangeRect;if(this.#T=e?.triggerIndex??null,this.#w=null,!e||!t)return;let n=t(e.triggerIndex,e.triggerIndex+1);if(!n)return;let r=this.#e.anchor.getBoundingClientRect(),i=n.top-r.top,a=this.input.element,o=typeof getComputedStyle==`function`&&getComputedStyle(a).direction===`rtl`;this.#w={x:o?null:n.left-r.left,y:i}}close(e=!0){this.#l&&(this.#l=!1,this.#A(),this.#b&&clearTimeout(this.#b),this.#y?.abort(),this.#v++,this.#s?.close(),this.input.element.removeAttribute(`aria-activedescendant`),this.#m&&(this.#m=!1,this.#a.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#h??this.#n.trigger,this.#o),this.#h=null,e&&this.input.focus()))}#N(e){this.#u=e,this.#f=0,this.#p=null;let t=++this.#v;this.#S.clear(),this.#y?.abort(),this.#y=new AbortController;for(let e of this.#n.sources)this.#x.has(e.id)?this.#I(e.id,`loading`):(this.#S.add(e.id),this.#P(e,t));this.#V(),this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{if(t===this.#v)for(let e of this.#n.sources)this.#x.has(e.id)&&!this.#S.has(e.id)&&this.#P(e,t)},this.#i)}#P(e,t){let n={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#y.signal},r;try{r=e.search(this.#u,n)}catch{this.#I(e.id,`error`),this.#V();return}Zs(r)?(this.#x.add(e.id),this.#I(e.id,`loading`),r.then(n=>{t===this.#v&&(this.#L(e.id,n),this.#V())}).catch(()=>{t===this.#v&&(this.#I(e.id,`error`),this.#V())})):this.#L(e.id,r)}#F(e){let t=this.#g.find(t=>t.source.id===e.id);if(!t){t={source:e,items:[],status:`loading`,truncated:!1};let n=this.#n.sources;this.#g.push(t),this.#g.sort((e,t)=>n.findIndex(t=>t.id===e.source.id)-n.findIndex(e=>e.id===t.source.id))}return t}#I(e,t){let n=this.#n.sources.find(t=>t.id===e);n&&(this.#F(n).status=t)}#L(e,t){let n=this.#n.sources.find(t=>t.id===e);if(!n)return;let r=this.#F(n);r.truncated=t.length>this.#r,r.items=t.slice(0,this.#r),r.status=r.items.length===0?`empty`:`ready`}#R(e){return JSON.stringify([e.source.id,e.item.id])}#z(){this.#_=[];for(let e of this.#g)if(e.status===`ready`)for(let t of e.items)this.#_.push({source:e.source,item:t});if(this.#p){let e=this.#_.findIndex(e=>this.#R(e)===this.#p);this.#f=e>=0?e:Math.min(this.#f,Math.max(0,this.#_.length-1))}else this.#f>=this.#_.length&&(this.#f=Math.max(0,this.#_.length-1))}#B(){return{query:this.#u,groups:this.#g,activeIndex:this.#f}}#V(){this.#z(),this.#a.render(this.#B()),this.#U(),this.#s?.reposition();let e=this.#g.some(e=>e.status===`loading`);this.#_.length===0&&e||this.#_.length!==this.#C&&(this.#C=this.#_.length,this.#e.announce(this.#_.length===0?`No matches`:this.#_.length===1?`1 result`:`${this.#_.length} results`),this.#e.emit?.(`searched`,{query:this.#u,results:this.#_.length}))}#H(e,t=!0){e<0||e>=this.#_.length||(this.#f=e,this.#p=this.#R(this.#_[e]),this.#a.setActiveIndex(e,t),this.#U())}#U(){this.#l&&!this.#m&&this.#f>=0&&this.#f<this.#_.length?this.input.element.setAttribute(`aria-activedescendant`,`${this.#o}-opt-${this.#f}`):this.input.element.removeAttribute(`aria-activedescendant`)}#W(e){let t=this.#n.sources.find(t=>t.id===e);t&&this.#y&&(this.#I(e,`loading`),this.#V(),this.#P(t,this.#v),this.#V())}handleKeydown(e){if(!this.#l)return!1;switch(e.key){case`ArrowDown`:return this.#_.length===0||(e.preventDefault(),this.#H((this.#f+1)%this.#_.length)),!0;case`ArrowUp`:return this.#_.length===0||(e.preventDefault(),this.#H((this.#f-1+this.#_.length)%this.#_.length)),!0;case`Home`:return this.#_.length===0||(e.preventDefault(),this.#H(0)),!0;case`End`:return this.#_.length===0||(e.preventDefault(),this.#H(this.#_.length-1)),!0;case`Enter`:case`Tab`:return this.#_.length===0?(this.close(),!1):(e.preventDefault(),this.#G(this.#f),!0);case`Escape`:return e.preventDefault(),this.close(),!0;case`Backspace`:return this.#u.length===0&&this.close(),!1;default:return!1}}#G(e){let t=this.#_[e];t&&this.#J(t.source,t.item)}#K(e){return Gs(e).args}#q(e){return e.command===`server`||e.commandArgsPlaceholder!=null}#J(e,t){let n=t.command;if(this.#q(t))this.#Z(e,t);else if(n===`action`){let n=this.#K(this.#u);this.#ie(),this.close(),this.#te(t,n),this.#e.emit?.(`command`,{sourceId:e.id,itemId:t.id,kind:`action`,args:n}),this.input.focus()}else if(n===`prompt`){let n=this.#K(this.#u),r=this.#ne();this.close(),this.#re(e,t,n,r),this.#e.emit?.(`command`,{sourceId:e.id,itemId:t.id,kind:`prompt`,args:n})}else this.#Y()?this.#X(e,t):(this.#e.onSelect(e,t,``)&&(this.#ie(),this.#e.emit?.(`selected`,{sourceId:e.id,itemId:t.id,label:t.label})),this.close(),this.input.focus())}#Y(){return this.#e.mentionConfig.display===`inline`&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#X(e,t){if(this.#e.admitMention&&!this.#e.admitMention(e,t)){this.close(),this.input.focus();return}let n=As(e,t),r=this.#d?this.input.insertMentionAtTrigger(n,this.#d):this.input.insertMentionAtSelection?.(n)??null;r?(this.#e.onInsertMention(r,e,t,``),this.#e.emit?.(`selected`,{sourceId:e.id,itemId:t.id,label:t.label})):(this.#e.mentionConfig.onMentionRejected?.(t,`stale`),this.#e.emit?.(`rejected`,{sourceId:e.id,itemId:t.id,reason:`stale`})),this.#d=null,this.close(),this.input.focus()}#Z(e,t){let n=`${this.#n.trigger}${t.label} `,r=this.input.getSelection().start,i=this.#d?this.#d.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(i,r,n);else{let e=this.input.getValue();this.input.setValueWithCaret(e.slice(0,i)+n+e.slice(r),i+n.length)}this.#d=null,this.close(),this.#e.emit?.(`command`,{sourceId:e.id,itemId:t.id,kind:t.command??`prompt`,phase:`armed`}),this.input.dispatchInput(),this.input.focus()}#Q(e,t){let{name:n}=Gs(t);return!n||t.length<=n.length?!1:e.sources.some(e=>{let t=e.matchCommand?.(n);return!!t&&this.#q(t)})}#$(e){for(let t of this.#t){if(!t.trigger)continue;let n=t.position===`anywhere`?[e]:t.position===`line-start`?e.split(`
|
|
172
172
|
`):[e.split(`
|
|
173
|
-
`)[0]];for(let e of n){if(!e.startsWith(t.trigger))continue;let{name:n,args:r}=
|
|
174
|
-
`,l=
|
|
175
|
-
`?0:1);return{doc:{blocks:l},caret:u}}function
|
|
176
|
-
`}));function
|
|
173
|
+
`)[0]];for(let e of n){if(!e.startsWith(t.trigger))continue;let{name:n,args:r}=Gs(e.slice(t.trigger.length));if(n)for(let e of t.sources){let t=e.matchCommand?.(n);if(t&&this.#q(t))return{source:e,item:t,args:r}}}}return null}async dispatchInlineCommand(e){let t=this.#$(e);if(!t)return null;let{source:n,item:r,args:i}=t,a=r.command??`prompt`;if(this.#e.emit?.(`command`,{sourceId:n.id,itemId:r.id,kind:a,args:i}),a===`action`)return this.#te(r,i),{kind:`action`};if(a===`prompt`){let t;try{t=await n.resolve(r,this.#ee(i,e))}catch(e){return typeof console<`u`&&console.warn(`[Persona] inline prompt command resolve failed`,e),null}return{kind:`prompt`,sendText:t.insertText??t.llmAppend??e}}return{kind:`server`,mentions:{refs:[],finalize:async()=>{let t=await n.resolve(r,this.#ee(i,e)),a={};return t.context&&(a[n.id]={[r.id]:t.context}),{blocks:[],contentParts:t.contentParts??[],context:a}}}}}#ee(e,t){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:t,args:e,signal:new AbortController().signal}}#te(e,t){if(e.action)try{Promise.resolve(e.action({args:t,config:this.#e.getConfig(),messages:this.#e.getMessages(),composer:this.input})).catch(e=>{typeof console<`u`&&console.warn(`[Persona] context-mention command action failed`,e)})}catch(e){typeof console<`u`&&console.warn(`[Persona] context-mention command action failed`,e)}}#ne(){return this.#d?{value:this.input.getValue(),start:this.#d.triggerIndex,end:this.input.getSelection().start}:null}async#re(e,t,n,r){let i=this.input,a;try{a=await e.resolve(t,{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:i.getValue(),args:n,signal:new AbortController().signal})}catch(e){typeof console<`u`&&console.warn(`[Persona] context-mention prompt resolve failed`,e);return}let o=a.insertText??a.llmAppend??``;t.insertMode===`insert-at-caret`&&r?i.replaceLogicalRange?(i.replaceLogicalRange(r.start,r.end,o),i.dispatchInput()):i.setValue(r.value.slice(0,r.start)+o+r.value.slice(r.end)):i.setValue(o),t.submitOnSelect&&i.submit()}#ie(){if(!this.#d)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.#d.triggerIndex,e,``);else{let t=bo(this.input.getValue(),this.#d,e);this.input.setValueWithCaret(t.value,t.caret)}this.input.dispatchInput(),this.#d=null}destroy(){this.#A(),this.#b&&clearTimeout(this.#b),this.#y?.abort(),this.#s?.destroy(),this.#a.destroy();let e=this.input.element;e.removeAttribute(`aria-haspopup`),e.removeAttribute(`aria-controls`),e.removeAttribute(`aria-activedescendant`)}}}));function tc(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function nc(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:(t,n=t)=>{e.setSelectionRange(t,n)},setValueWithCaret:(t,n)=>{e.value=t,e.setSelectionRange(n,n)},setValue:n=>{e.value=n,e.setSelectionRange(n.length,n.length),t(),e.focus()},submit:()=>tc(e.form),dispatchInput:t,focus:()=>e.focus()}}var rc=o((()=>{}));function ic(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 r=t.getRootNode();typeof ShadowRoot<`u`&&r instanceof ShadowRoot?(Object.assign(n.style,ac),document.body.appendChild(n)):t.appendChild(n);let i;return{announce:e=>{i!==void 0&&clearTimeout(i),n.textContent=``,i=setTimeout(()=>{i=void 0,n.textContent=e},0)},destroy:()=>{i!==void 0&&clearTimeout(i),n.remove()}}}var ac,oc=o((()=>{ac={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 sc(e){let t=e.composerInput??nc(e.textarea),n=ic(`polite`,e.liveRegionHost),r=ic(`assertive`,e.liveRegionHost),i=e=>n.announce(e),a=new Ms({mentionConfig:e.mentionConfig,contextRow:e.contextRow,getMessages:e.getMessages,getConfig:e.getConfig,getComposerText:()=>t.getValue(),announce:i,announceError:e=>r.announce(e),emit:e.emit}),o=()=>new $s({mentionConfig:e.mentionConfig,composerInput:t,anchor:e.anchor,getMessages:e.getMessages,getConfig:e.getConfig,onSelect:(e,t,n)=>a.add(e,t,n),onInsertMention:(e,n,r,i)=>a.track(e,n,r,i,n=>t.setMentionStatus?.(e,n)),admitMention:(e,t)=>a.admit(e,t),announce:i,popoverContainer:e.popoverContainer,onPickerOpenChange:e.onPickerOpenChange,emit:e.emit}),s=o();return{openMenu:e=>s.openFromButton(e),isMenuOpen:()=>s.isOpen(),handleInput:()=>s.onInput(),handleKeydown:e=>s.handleKeydown(e),hasMentions:()=>a.hasMentions(),getMentionRefs:()=>a.getRefs(),removeLastChip:()=>a.removeLast(),dispatchInlineCommand:e=>s.dispatchInlineCommand(e),collectForSubmit:()=>a.hasMentions()?a.collectForSubmit():null,untrackMention:e=>a.remove(e),rebindComposer:e=>{e!==t&&(s.destroy(),t=e,s=o())},clear:()=>a.clear(),destroy:()=>{s.destroy(),a.clear(),n.destroy(),r.destroy()}}}var cc=o((()=>{Ns(),ec(),rc(),oc(),vs()})),lc=/* @__PURE__ */ s({mountContextMentions:()=>sc,setMentionIconRenderer:()=>gs}),uc=o((()=>{cc()})),dc,fc,pc,mc=o((()=>{Pe(),{setLoader:dc,load:fc}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(uc(),lc))}),pc=fc}));function hc(e){return e.kind===`text`?e.value.length:1}function gc(e){let t=[],n=e=>{let n=t[t.length-1];n&&n.kind===`text`?n.value+=e:t.push({kind:`text`,value:e})};(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 e=t[t.length-1];(!e||e.kind!==`text`)&&t.push({kind:`text`,value:``}),t.push({kind:`mention`,id:r.id,ref:r.ref}),t.push({kind:`text`,value:``})}let r=t[t.length-1];return(!r||r.kind!==`text`)&&t.push({kind:`text`,value:``}),t}function _c(){return{blocks:[{kind:`text`,value:``}]}}function vc(e){return{blocks:[{kind:`text`,value:e}]}}function yc(e){return e.blocks.map(e=>e.kind===`text`?e.value:`${Oc}${e.ref.label}`).join(``)}function bc(e){return e.blocks.map(e=>e.kind===`text`?e.value:``).join(``)}function xc(e){return e.blocks.reduce((e,t)=>e+hc(t),0)}function Sc(e){let t=[];for(let n of e.blocks)n.kind===`mention`&&t.push({id:n.id,ref:n.ref});return t}function Cc(e,t){let n=[],r=[],i=0;for(let a of e){let e=hc(a),o=i+e;if(o<=t)n.push(a);else if(i>=t)r.push(a);else if(a.kind===`text`){let o=t-i;o>0&&n.push({kind:`text`,value:a.value.slice(0,o)}),o<e&&r.push({kind:`text`,value:a.value.slice(o)})}else r.push(a);i=o}return{left:n,right:r}}function wc(e,t,n,r){let i=Cc(e.blocks,t.start).left,a=Cc(e.blocks,t.end).right,o=a[0],s=o?.kind===`text`?o.value.charAt(0):``,c=s!==` `&&s!==` `&&s!==`
|
|
174
|
+
`,l=gc([...i,{kind:`mention`,id:r,ref:n},...c?[{kind:`text`,value:` `}]:[],...a]),u=t.start+1+(s===`
|
|
175
|
+
`?0:1);return{doc:{blocks:l},caret:u}}function Tc(e,t){let n=0,r=0,i=!1;for(let a of e.blocks)a.kind===`mention`&&a.id===t&&(n=r,i=!0),r+=hc(a);return i?{doc:{blocks:gc(e.blocks.filter(e=>e.kind!==`mention`||e.id!==t))},caret:n}:{doc:e,caret:r}}function Ec(e,t,n,r){let i=xc(e),a=Math.max(0,Math.min(t,n,i)),o=Math.min(i,Math.max(t,n,0)),s=Cc(e.blocks,a).left,c=Cc(e.blocks,o).right;return{doc:{blocks:gc([...s,{kind:`text`,value:r},...c])},caret:a+r.length}}function Dc(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:yc(e),contextMentions:Sc(e).map(e=>e.ref),contentSegments:t}}var Oc,kc=o((()=>{So(),Oc=`@`}));function Ac(e){return e.nodeType===1&&e.hasAttribute(zc)}function jc(e){return e.nodeType===1&&e.tagName===`BR`}function Mc(e){return e.nodeType===3?e.data.length:Ac(e)||jc(e)?1:e.textContent?.length??0}function Nc(e,t,n){let r=0;for(let i of Array.from(e.childNodes)){if(i===t)return i.nodeType===3?r+n:r+(n>0?Mc(i):0);if(i.contains(t))return Ac(i)?r+1:r+Pc(i,t,n);r+=Mc(i)}if(t===e){let t=0,r=Array.from(e.childNodes);for(let e=0;e<Math.min(n,r.length);e++)t+=Mc(r[e]);return t}return r}function Pc(e,t,n){let r=0,i=e=>{if(e===t)return r+=e.nodeType===3?n:0,!0;if(e.nodeType===3)return r+=e.data.length,!1;for(let t of Array.from(e.childNodes))if(i(t))return!0;return!1};return i(e),r}function Fc(e,t){let n=0,r=Array.from(e.childNodes);for(let i=0;i<r.length;i++){let a=r[i],o=Mc(a);if(t<=n+o)return a.nodeType===3?{node:a,offset:t-n}:{node:e,offset:t<=n?i:i+1};n+=o}return{node:e,offset:r.length}}function Ic(e,t){let n=[];for(let r of Array.from(e.childNodes))if(Ac(r)){let e=r.getAttribute(zc),i=t.get(e);i&&n.push({kind:`mention`,id:e,ref:i})}else if(jc(r))n.push({kind:`text`,value:Hc});else if(r.nodeType===3)n.push({kind:`text`,value:r.data});else{let e=r.textContent??``;e&&n.push({kind:`text`,value:e})}return n.length===0&&n.push({kind:`text`,value:``}),{blocks:n}}function Lc(e){let t=e.renderToken,n=/* @__PURE__ */ new Map,r=e.element??document.createElement(`div`);r.setAttribute(`contenteditable`,`true`),r.setAttribute(`data-persona-composer-input`,``),r.setAttribute(`role`,`textbox`),r.setAttribute(`aria-multiline`,`true`),r.setAttribute(`dir`,`auto`),r.classList.add(`persona-composer-contenteditable`),e.placeholder!=null&&r.setAttribute(`data-placeholder`,e.placeholder);let i=!1,a=0,o=()=>Ic(r,n),s=e=>{r.replaceChildren();for(let i of e.blocks)if(i.kind===`text`)i.value.length>0&&r.appendChild(document.createTextNode(i.value));else{n.set(i.id,i.ref);let e=t(i.ref);e.setAttribute(`contenteditable`,`false`),e.setAttribute(zc,i.id),r.appendChild(e)}},c=()=>{let e=r.getRootNode().activeElement;return e===r||e!=null&&r.contains(e)},l=(e,t)=>{if(a=e,!t?.focus&&!c())return;let n=typeof window<`u`?window.getSelection():null;if(!n)return;let i=Fc(r,e);try{let e=document.createRange();e.setStart(i.node,i.offset),e.collapse(!0),n.removeAllRanges(),n.addRange(e)}catch{}},u=()=>{r.dispatchEvent(new Event(`input`,{bubbles:!0}))},d=()=>{let e={start:a,end:a},t=typeof window<`u`?window.getSelection():null;if(!t||t.rangeCount===0)return e;let n=t.getRangeAt(0);if(!r.contains(n.startContainer))return e;let i=Nc(r,n.startContainer,n.startOffset),o=n.collapsed?i:Nc(r,n.endContainer,n.endOffset);return{start:Math.min(i,o),end:Math.max(i,o)}},f=()=>{let t=/* @__PURE__ */ new Set;for(let e of Array.from(r.childNodes))Ac(e)&&t.add(e.getAttribute(zc));for(let r of Array.from(n.keys()))t.has(r)||(n.delete(r),e.onMentionRemoved?.(r))},p=()=>{i||n.size!==0&&f()},m=()=>{i=!0},h=()=>{i=!1,f()},g=e=>{e.preventDefault();let t=e.clipboardData?.getData(`text/plain`)??``;if(typeof document.execCommand==`function`)document.execCommand(`insertText`,!1,t);else{let{start:e,end:n}=d(),r=Ec(o(),e,n,t);s(r.doc),l(r.caret,{focus:!0}),f()}u()},_=e=>{if(i)return;let t=e.inputType;if(t===`insertParagraph`){e.preventDefault();let{start:t,end:r}=d(),i=Ec(o(),t,r,Hc);s(i.doc),l(i.caret,{focus:!0}),n.size>0&&f(),u();return}if(t!==`deleteContentBackward`&&t!==`deleteContentForward`||n.size===0)return;let{start:r,end:a}=d();if(r!==a)return;let c=o(),p=bc(c),m=t===`deleteContentBackward`?r-1:r;if(m<0||m>=p.length||p[m]!==``)return;let h=0,g=null;for(let e of c.blocks){let t=e.kind===`text`?e.value.length:1;if(e.kind===`mention`&&m>=h&&m<h+t){g=e.id;break}h+=t}if(!g)return;e.preventDefault();let _=Tc(c,g);s(_.doc),l(_.caret,{focus:!0}),f(),u()};return r.addEventListener(`input`,p),r.addEventListener(`compositionstart`,m),r.addEventListener(`compositionend`,h),r.addEventListener(`paste`,g),r.addEventListener(`beforeinput`,_),s(_c()),{element:r,getValue:()=>yc(o()),getLogicalText:()=>bc(o()),getDocument:o,getSelection:d,setSelection:(e,t=e)=>{let n=typeof window<`u`?window.getSelection():null;if(n)try{let i=Fc(r,e),a=Fc(r,t),o=document.createRange();o.setStart(i.node,i.offset),o.setEnd(a.node,a.offset),n.removeAllRanges(),n.addRange(o)}catch{}},setValueWithCaret:(e,t)=>{s(vc(e)),l(t)},getLogicalRangeRect:(e,t)=>{if(!Number.isFinite(e)||!Number.isFinite(t)||t<=e)return null;try{let n=Fc(r,e),i=Fc(r,t),a=document.createRange();a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset);let o=a.getBoundingClientRect();return o.width===0&&o.height===0?null:o}catch{return null}},setValue:e=>{s(vc(e)),r.focus(),l(e.length,{focus:!0}),u()},replaceLogicalRange:(e,t,n)=>{let r=Ec(o(),e,t,n);s(r.doc),l(r.caret,{focus:!0})},insertMentionAtTrigger:(t,n)=>{let r=o(),i=bc(r),a=n.triggerIndex,c=n.triggerIndex+1+n.query.length;if(a<0||c>i.length||i.slice(a+1,c)!==n.query)return null;let d=e.generateId(),f=wc(r,{start:a,end:c},t,d);return s(f.doc),l(f.caret,{focus:!0}),e.onMentionInserted?.(d,t),u(),d},insertMentionAtSelection:t=>{let n=o(),i=d(),a=typeof window<`u`&&window.getSelection()?.rangeCount&&r.contains(window.getSelection().getRangeAt(0).startContainer)?{start:i.start,end:i.end}:{start:xc(n),end:xc(n)},c=e.generateId(),f=wc(n,a,t,c);return s(f.doc),l(f.caret,{focus:!0}),e.onMentionInserted?.(c,t),u(),c},setMentionStatus:(e,t)=>{for(let i of Array.from(r.childNodes))if(Ac(i)&&i.getAttribute(zc)===e){let r=t===`error`;if(i.classList.toggle(Rc,r),r){i.hasAttribute(Bc)||(i.setAttribute(Bc,i.getAttribute(`aria-label`)??``),i.setAttribute(Vc,i.getAttribute(`title`)??``));let t=n.get(e)?.label??``;i.setAttribute(`title`,`${t}: failed to attach context`),i.setAttribute(`aria-label`,`${t}, failed to attach context`)}else if(i.hasAttribute(Bc)){let e=i.getAttribute(Bc),t=i.getAttribute(Vc);e?i.setAttribute(`aria-label`,e):i.removeAttribute(`aria-label`),t?i.setAttribute(`title`,t):i.removeAttribute(`title`),i.removeAttribute(Bc),i.removeAttribute(Vc)}return}},submit:()=>tc(r.closest(`form`)),dispatchInput:u,focus:()=>r.focus(),destroy:()=>{r.removeEventListener(`input`,p),r.removeEventListener(`compositionstart`,m),r.removeEventListener(`compositionend`,h),r.removeEventListener(`paste`,g),r.removeEventListener(`beforeinput`,_)}}}var Rc,zc,Bc,Vc,Hc,Uc=o((()=>{kc(),rc(),Rc=`persona-mention-token-error`,zc=`data-mention-id`,Bc=`data-mention-prev-label`,Vc=`data-mention-prev-title`,Hc=`
|
|
176
|
+
`}));function Wc(e,t){t.className=`${e.className} persona-composer-contenteditable`.trim();for(let n=0;n<e.style.length;n++){let r=e.style.item(n);r!==`height`&&t.style.setProperty(r,e.style.getPropertyValue(r),e.style.getPropertyPriority(r))}let n=e.getAttribute(`placeholder`);n&&(t.setAttribute(`data-placeholder`,n),t.setAttribute(`aria-placeholder`,n));let r=e.getAttribute(`aria-label`)??n;r&&t.setAttribute(`aria-label`,r)}function Gc(e,t,n){Object.defineProperty(e,"value",{configurable:!0,get:()=>t.getValue(),set:e=>{t.setValueWithCaret(e,e.length),t.dispatchInput()}}),Object.defineProperty(e,"placeholder",{configurable:!0,get:()=>e.getAttribute(`data-placeholder`)??``,set:t=>{t?(e.setAttribute(`data-placeholder`,t),e.setAttribute(`aria-placeholder`,t),n||e.setAttribute(`aria-label`,t)):(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=(e,n)=>t.setSelection(e??0,n??e??0)}function Kc(e){let{textarea:t}=e,n=Lc({generateId:Jc,renderToken:e.renderToken,onMentionRemoved:e.onMentionRemoved,placeholder:t.getAttribute(`placeholder`)??void 0}),r=n.element,i=t.getAttribute(`aria-label`)!=null;Wc(t,r),Gc(r,n,i),r.getInlineMessageFields=()=>Dc(n.getDocument?.()??{blocks:[]});let a=t.selectionStart??t.value.length;return n.setValueWithCaret(t.value,a),{input:n,element:r,destroy:n.destroy}}var qc,Jc,Yc=o((()=>{Uc(),kc(),qc=0,Jc=()=>`pmention-${++qc}`})),Xc=/* @__PURE__ */ s({mountInlineComposer:()=>Kc}),Zc=o((()=>{Yc()})),Qc,$c,el,tl=o((()=>{Pe(),{setLoader:Qc,load:$c}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Zc(),Xc)),resetOnSetLoader:!0}),el=$c}));function nl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=V(`span`,{className:Me(`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 r=U(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=B(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(V(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var rl=o((()=>{H(),W()}));function il(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??al,a=e.config.contextMentions;if(!a?.enabled)return null;let o=Co(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
|
|
177
177
|
`).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
|
|
178
|
-
`)[0]).startsWith(t.trigger):!1),l=(e,t)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${e}`,{detail:t}))}catch{}},u=!e.chipRow,d=e.chipRow??B(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Jc(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!uo(e))return;let t=m,n=t.selectionStart??0;lo(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Zc,Qc=o((()=>{H(),mo(),go(),os(),oc(),ze(),qc(),Yc(),Zc={loadContextMentions:()=>ac(),loadContextMentionsInline:()=>Kc(),renderLucideIcon:(...e)=>U(...e),createMentionButton:(...e)=>as(...e)}})),$c=/* @__PURE__ */ s({createAskUserSheetHandlers:()=>ao,createContextMentionOrchestrator:()=>Xc}),el=o((()=>{oo(),Qc()}));io(),ve();const{setLoader:tl,load:nl,provide:rl,getSync:il}=_e({fallbackImport:()=>Promise.resolve().then(()=>(el(),$c))}),al=nl,ol=il;var sl=/* @__PURE__ */ s({resolveApproval:()=>cl,resolveAskUserQuestion:()=>ll,resolveWebMcpToolCall:()=>hl,resolveWebMcpToolCallBatch:()=>ml});async function cl(e,t,n,r){let i=`approval-${t.id}`,a=`approval-error-${t.id}`,o={};e.s.approvalTokens.set(i,o);let s={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(e=>e.id===i),l={id:i,role:`assistant`,content:``,createdAt:c?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),...c?.sequence===void 0?{}:{sequence:c.sequence},streaming:!1,variant:`approval`,approval:s};e.s.upsertMessage(l),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let u=e.s.config.approval,d=u&&typeof u==`object`?u.onDecision:void 0;try{let c;if(c=d?await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let r=null;if(c instanceof Response){if(!c.ok){let n=await c.json().catch(()=>null),r=n?.message??n?.error??`Approval request failed: ${c.status}`,u=n?.code===`APPROVAL_ALREADY_RESOLVED`||c.status===404&&/no paused execution/i.test(String(n?.error)),d=e.s.messages.find(e=>e.id===i);throw e.s.approvalTokens.get(i)===o&&d?.approval?.resolvedAt===s.resolvedAt&&(e.s.upsertMessage({...l,approval:u?{...s,status:`timeout`}:t}),u&&e.settleApprovalPausedToolCall(i),e.s.upsertMessage({id:a,role:`assistant`,content:r,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),Error(r)}r=c.body}else c instanceof ReadableStream&&(r=c);e.s.approvalTokens.get(i)===o&&e.s.messages.some(e=>e.id===a)&&(e.s.messages=e.s.messages.filter(e=>e.id!==a),e.s.callbacks.onMessagesChanged([...e.s.messages])),r?await e.s.connectStream(r,{allowReentry:!0}):(n===`denied`&&(e.settleApprovalPausedToolCall(i),e.appendMessage({id:`denial-${t.id}`,role:`assistant`,content:`Tool execution was denied by user.`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.approvalTokens.get(i)===o&&e.s.approvalTokens.delete(i)}}async function ll(e,t,n){if(e.s.messages.find(e=>e.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,i=t.toolCall?.name;if(!r||!i){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`resolveAskUserQuestion: message is missing executionId or toolCall.name`));return}let a=typeof n==`string`?void 0:n;if(a===void 0&&typeof n==`string`){let e=t.toolCall?.args,r=Array.isArray(e?.questions)?e.questions:[];if(r.length===1){let e=typeof r[0]?.question==`string`?r[0].question:``;e&&(a={[e]:n})}}e.s.markAskUserQuestionResolved(t,a),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let o=t.toolCall.id,s=t.toolCall?.args,c=Array.isArray(s?.questions)?s.questions:[];if(c.length===0){let t=typeof n==`string`?n:Object.entries(n).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `);e.appendMessage({id:`ask-user-answer-${o}`,role:`user`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let t=a??{};c.forEach((n,r)=>{let i=typeof n?.question==`string`?n.question:``;if(!i)return;let a=t[i],s=Array.isArray(a)?a.join(`, `):typeof a==`string`?a:``;e.appendMessage({id:`ask-user-q-${o}-${r}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${o}-${r}`,role:`user`,content:s||`*Skipped*`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let t=await e.s.client.resumeFlow(r,{[i]:n},{after:e.resumeAfter(r)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${t.status}`)}t.body?await e.s.connectStream(t.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}}function ul(e,t){let n=[e.s.messages.find(e=>e.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let e of n)if(typeof e==`number`&&Number.isFinite(e))return e;return Date.now()}function dl(e,t){return t.toolCall?.name===`suggest_replies`&&(e.s.messages.find(e=>e.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function fl(e,t){let n=ul(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 pl(e,t,n,r,i=Date.now(),a){e.s.messages.some(e=>e.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:`complete`,result:n,startedAt:r,completedAt:i,duration:void 0,durationMs:Math.max(0,i-r)}:t.toolCall})}async function ml(e,t,n){let r=[],i=new AbortController;e.s.webMcpResolveControllers.add(i),e.setStreaming(!0);let a=async n=>{let a=n.toolCall?.name,o=n.toolCall?.id;if(!a||!o)return null;let s=`${t}:${o}`;if(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||dl(e,n))return null;e.s.webMcpInflightKeys.add(s),r.push(s);let c=fl(e,n),l=n.agentMetadata?.webMcpToolCallId??a;if(a===`suggest_replies`)return{dedupeKey:s,resumeKey:l,output:Tr(),toolMessage:n,startedAt:c,completedAt:Date.now()};let u=e.s.client.executeWebMcpToolCall(a,n.toolCall?.args,i.signal),d;if(!u)d={isError:!0,content:[{type:`text`,text:`WebMCP not enabled on this widget.`}]};else try{d=await u}catch(t){let r=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));return r||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t))),pl(e,n,_l(r?`Aborted by cancel()`:vl(t)),c),e.s.webMcpInflightKeys.delete(s),null}return i.signal.aborted?(pl(e,n,_l(`Aborted by cancel()`),c),e.s.webMcpInflightKeys.delete(s),null):{dedupeKey:s,resumeKey:l,output:d,toolMessage:n,startedAt:c,completedAt:Date.now()}},o;if(e.s.config.webmcp?.execution===`sequential`){o=[];for(let e of n)o.push(await a(e))}else o=await Promise.all(n.map(a));let s=[];try{if(s=o.filter(e=>e!==null),s.length===0)return;let n={};for(let e of s)n[e.resumeKey]=e.output;let r=await e.s.client.resumeFlow(t,n,{signal:i.signal,after:e.resumeAfter(t)});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${r.status}`)}let a=s[0].dedupeKey;for(let t of s){e.s.webMcpResolvedKeys.add(t.dedupeKey);let n=t.toolMessage.toolCall?.name,r=t.toolMessage.agentMetadata?.webMcpToolCallId;pl(e,t.toolMessage,t.output,t.startedAt,t.completedAt,{...n===`suggest_replies`?{suggestRepliesResolved:!0}:{},...n&&r?{clientToolAnswer:{toolCallId:r,toolName:n,args:t.toolMessage.toolCall?.args,result:t.output,batch:a}}:{}})}r.body&&await e.s.connectStream(r.body,{allowReentry:!0})}catch(t){if(!(t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`))))e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)));else for(let t of s)pl(e,t.toolMessage,_l(`Aborted by cancel()`),t.startedAt)}finally{for(let t of r)e.s.webMcpInflightKeys.delete(t);e.s.webMcpResolveControllers.delete(i),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function hl(e,t){let n=t.agentMetadata?.executionId,r=t.toolCall?.name,i=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`WebMCP await missing executionId: dispatch left paused.`));return}if(!r)return;if(!i){let t=`${n}:__no_tool_id__:${r}`;if(e.s.webMcpInflightKeys.has(t)||e.s.webMcpResolvedKeys.has(t))return;e.s.webMcpInflightKeys.add(t);try{await gl(e,n,r,{isError:!0,content:[{type:`text`,text:`WebMCP await missing toolCall.id: cannot execute the page tool.`}]}),e.s.webMcpResolvedKeys.add(t)}catch(t){e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.webMcpInflightKeys.delete(t)}return}let a=`${n}:${i}`;if(!(e.s.webMcpInflightKeys.has(a)||e.s.webMcpResolvedKeys.has(a)||dl(e,t)))return ml(e,n,[t])}async function gl(e,t,n,r,i){let a=await e.s.client.resumeFlow(t,{[n]:r},{signal:i?.signal,after:e.resumeAfter(t)});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}i?.onHttpOk?.(),a.body?await e.s.connectStream(a.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var _l,vl,yl=o((()=>{Mr(),_l=e=>({isError:!0,content:[{type:`text`,text:e}]}),vl=(e,t=`WebMCP tool execution failed.`)=>e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:t}));ve();const{setLoader:bl,load:xl,provide:Sl,getSync:Cl}=_e({fallbackImport:()=>Promise.resolve().then(()=>(yl(),sl))}),wl=xl,Tl=Cl;La(),xs();const El=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function Dl(e){let t=e?.text?.trim()??``;return t?vs(El(e),t):``}function Ol(e){let t=Dl(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[wa(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
178
|
+
`)[0]).startsWith(t.trigger):!1),l=(e,t)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${e}`,{detail:t}))}catch{}},u=!e.chipRow,d=e.chipRow??V(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>nl(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!yo(e))return;let t=m,n=t.selectionStart??0;vo(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var al,ol=o((()=>{H(),So(),wo(),ms(),mc(),W(),tl(),rl(),al={loadContextMentions:()=>pc(),loadContextMentionsInline:()=>el(),renderLucideIcon:(...e)=>U(...e),createMentionButton:(...e)=>ps(...e)}})),sl=/* @__PURE__ */ s({createAskUserSheetHandlers:()=>mo,createContextMentionOrchestrator:()=>il}),cl=o((()=>{ho(),ol()}));po(),Pe();const{setLoader:ll,load:ul,provide:dl,getSync:fl}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(cl(),sl))}),pl=ul,ml=fl;var hl=/* @__PURE__ */ s({resolveApproval:()=>gl,resolveAskUserQuestion:()=>_l,resolveWebMcpToolCall:()=>Cl,resolveWebMcpToolCallBatch:()=>Sl});async function gl(e,t,n,r){let i=`approval-${t.id}`,a=`approval-error-${t.id}`,o=Hi(),s={};e.s.approvalTokens.set(i,s);let c={...t,status:n,resolvedAt:Date.now()},l=e.s.messages.find(e=>e.id===i),u={id:i,role:`assistant`,content:``,createdAt:l?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),...l?.sequence===void 0?{}:{sequence:l.sequence},streaming:!1,variant:`approval`,approval:c};e.s.upsertMessage(u),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,f=d&&typeof d==`object`?d.onDecision:void 0;try{let l;if(l=f?await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n,{assistantMessageId:o}),l){let r=null;if(l instanceof Response){if(!l.ok){let n=await l.json().catch(()=>null),r=n?.message??n?.error??`Approval request failed: ${l.status}`,o=n?.code===`APPROVAL_ALREADY_RESOLVED`||l.status===404&&/no paused execution/i.test(String(n?.error)),d=e.s.messages.find(e=>e.id===i);throw e.s.approvalTokens.get(i)===s&&d?.approval?.resolvedAt===c.resolvedAt&&(e.s.upsertMessage({...u,approval:o?{...c,status:`timeout`}:t}),o&&e.settleApprovalPausedToolCall(i),e.s.upsertMessage({id:a,role:`assistant`,content:r,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),Error(r)}r=l.body}else l instanceof ReadableStream&&(r=l);e.s.approvalTokens.get(i)===s&&e.s.messages.some(e=>e.id===a)&&(e.s.messages=e.s.messages.filter(e=>e.id!==a),e.s.callbacks.onMessagesChanged([...e.s.messages])),r?await e.s.connectStream(r,{allowReentry:!0,assistantMessageId:o}):(n===`denied`&&(e.settleApprovalPausedToolCall(i),e.appendMessage({id:`denial-${t.id}`,role:`assistant`,content:`Tool execution was denied by user.`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.approvalTokens.get(i)===s&&e.s.approvalTokens.delete(i)}}async function _l(e,t,n){if(e.s.messages.find(e=>e.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,i=t.toolCall?.name;if(!r||!i){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`resolveAskUserQuestion: message is missing executionId or toolCall.name`));return}let a=typeof n==`string`?void 0:n;if(a===void 0&&typeof n==`string`){let e=t.toolCall?.args,r=Array.isArray(e?.questions)?e.questions:[];if(r.length===1){let e=typeof r[0]?.question==`string`?r[0].question:``;e&&(a={[e]:n})}}e.s.markAskUserQuestionResolved(t,a),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let o=t.toolCall.id,s=t.toolCall?.args,c=Array.isArray(s?.questions)?s.questions:[];if(c.length===0){let t=typeof n==`string`?n:Object.entries(n).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `);e.appendMessage({id:`ask-user-answer-${o}`,role:`user`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let t=a??{};c.forEach((n,r)=>{let i=typeof n?.question==`string`?n.question:``;if(!i)return;let a=t[i],s=Array.isArray(a)?a.join(`, `):typeof a==`string`?a:``;e.appendMessage({id:`ask-user-q-${o}-${r}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${o}-${r}`,role:`user`,content:s||`*Skipped*`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let t=Hi(),a=await e.s.client.resumeFlow(r,{[i]:n},{after:e.resumeAfter(r),assistantMessageId:t});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}a.body?await e.s.connectStream(a.body,{allowReentry:!0,assistantMessageId:t}):(e.setStreaming(!1),e.s.abortController=null)}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}}function vl(e,t){let n=[e.s.messages.find(e=>e.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let e of n)if(typeof e==`number`&&Number.isFinite(e))return e;return Date.now()}function yl(e,t){return t.toolCall?.name===`suggest_replies`&&(e.s.messages.find(e=>e.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function bl(e,t){let n=vl(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 xl(e,t,n,r,i=Date.now(),a){e.s.messages.some(e=>e.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:`complete`,result:n,startedAt:r,completedAt:i,duration:void 0,durationMs:Math.max(0,i-r)}:t.toolCall})}async function Sl(e,t,n){let r=[],i=new AbortController;e.s.webMcpResolveControllers.add(i),e.setStreaming(!0);let a=async n=>{let a=n.toolCall?.name,o=n.toolCall?.id;if(!a||!o)return null;let s=`${t}:${o}`;if(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||yl(e,n))return null;e.s.webMcpInflightKeys.add(s),r.push(s);let c=bl(e,n),l=n.agentMetadata?.webMcpToolCallId??a;if(a===`suggest_replies`)return{dedupeKey:s,resumeKey:l,output:kr(),toolMessage:n,startedAt:c,completedAt:Date.now()};let u=e.s.client.executeWebMcpToolCall(a,n.toolCall?.args,i.signal),d;if(!u)d={isError:!0,content:[{type:`text`,text:`WebMCP not enabled on this widget.`}]};else try{d=await u}catch(t){let r=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));return r||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t))),xl(e,n,Tl(r?`Aborted by cancel()`:El(t)),c),e.s.webMcpInflightKeys.delete(s),null}return i.signal.aborted?(xl(e,n,Tl(`Aborted by cancel()`),c),e.s.webMcpInflightKeys.delete(s),null):{dedupeKey:s,resumeKey:l,output:d,toolMessage:n,startedAt:c,completedAt:Date.now()}},o;if(e.s.config.webmcp?.execution===`sequential`){o=[];for(let e of n)o.push(await a(e))}else o=await Promise.all(n.map(a));let s=[];try{if(s=o.filter(e=>e!==null),s.length===0)return;let n={};for(let e of s)n[e.resumeKey]=e.output;let r=Hi(),a=await e.s.client.resumeFlow(t,n,{signal:i.signal,after:e.resumeAfter(t),assistantMessageId:r});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}let c=s[0].dedupeKey;for(let t of s){e.s.webMcpResolvedKeys.add(t.dedupeKey);let n=t.toolMessage.toolCall?.name,r=t.toolMessage.agentMetadata?.webMcpToolCallId;xl(e,t.toolMessage,t.output,t.startedAt,t.completedAt,{...n===`suggest_replies`?{suggestRepliesResolved:!0}:{},...n&&r?{clientToolAnswer:{toolCallId:r,toolName:n,args:t.toolMessage.toolCall?.args,result:t.output,batch:c}}:{}})}a.body&&await e.s.connectStream(a.body,{allowReentry:!0,assistantMessageId:r})}catch(t){if(!(t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`))))e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)));else for(let t of s)xl(e,t.toolMessage,Tl(`Aborted by cancel()`),t.startedAt)}finally{for(let t of r)e.s.webMcpInflightKeys.delete(t);e.s.webMcpResolveControllers.delete(i),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function Cl(e,t){let n=t.agentMetadata?.executionId,r=t.toolCall?.name,i=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`WebMCP await missing executionId: dispatch left paused.`));return}if(!r)return;if(!i){let t=`${n}:__no_tool_id__:${r}`;if(e.s.webMcpInflightKeys.has(t)||e.s.webMcpResolvedKeys.has(t))return;e.s.webMcpInflightKeys.add(t);try{await wl(e,n,r,{isError:!0,content:[{type:`text`,text:`WebMCP await missing toolCall.id: cannot execute the page tool.`}]}),e.s.webMcpResolvedKeys.add(t)}catch(t){e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.webMcpInflightKeys.delete(t)}return}let a=`${n}:${i}`;if(!(e.s.webMcpInflightKeys.has(a)||e.s.webMcpResolvedKeys.has(a)||yl(e,t)))return Sl(e,n,[t])}async function wl(e,t,n,r,i){let a=Hi(),o=await e.s.client.resumeFlow(t,{[n]:r},{signal:i?.signal,after:e.resumeAfter(t),assistantMessageId:a});if(!o.ok){let e=await o.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${o.status}`)}i?.onHttpOk?.(),o.body?await e.s.connectStream(o.body,{allowReentry:!0,assistantMessageId:a}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var Tl,El,Dl=o((()=>{Wi(),Ir(),Tl=e=>({isError:!0,content:[{type:`text`,text:e}]}),El=(e,t=`WebMCP tool execution failed.`)=>e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:t}));Pe();const{setLoader:Ol,load:kl,provide:Al,getSync:jl}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Dl(),hl))}),Ml=kl,Nl=jl,Pl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Fl=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!Pl(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=Pl(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})};Ha(),ks();const Il=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function Ll(e){let t=e?.text?.trim()??``;return t?Es(Il(e),t):``}function Rl(e){let t=Ll(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[ka(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
179
179
|
|
|
180
|
-
`)}:{}}function
|
|
180
|
+
`)}:{}}function zl(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Bl(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function Vl(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function Hl(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return Vl(e,n.id)?n.id:null}return null}function Ul(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}function Wl(e){for(let t of[`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)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var Gl=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):Wl(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Kl=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},ql=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}},Jl,Yl=o((()=>{Jl=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function Xl(e,t){let n=t.slice(0,wu).trim(),r=Cu-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>Tu&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
|
|
181
181
|
`)}`]:[];return n&&a.push(n),a.join(`
|
|
182
182
|
|
|
183
|
-
`)}function Vl(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Xl?new Uint8Array(e,44):new Uint8Array(e)}function Hl(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function Ul(e){return Hl(e).replace(/^ws/i,`http`)}function Wl(e){return typeof e!=`number`||!Number.isFinite(e)?eu:Math.min(nu,Math.max(tu,Math.round(e)))}var Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u=o((()=>{zl(),Ki(),Gl=16e3,Kl=24e3,ql=4096,Jl=Gl*2*8,Yl=4,Xl=1380533830,Zl=3e4,Ql=1e3,$l=5e3,eu=3e4,tu=3e4,nu=6e5,ru=`full-duplex-v1`,iu=300,au=2e3,ou=2e3,su=`runtype-browser-v1`,cu=54e4,lu=`You're talking to an AI assistant. Voice is processed by OpenAI.`,uu=/* @__PURE__ */ 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.`]]),du=[`provider_error`,`server_restart`],fu=`Voice connection lost.`,pu=8e3,mu=4e3,hu=2e3,gu=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<Zl)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${Ul(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=Wl(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,$l)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=[`partial_transcript`,`context`];this.bridge&&this.config?.clientDelegation!==!1&&(r.push(`client_delegation`,`delegation_update`,`delegation_read_back`,`delegation_stream`),this.bridge.clientTools?.()&&r.push(`client_tools`)),n&&r.unshift(`attach`);let i=new URLSearchParams({voiceProtocol:su,clientVersion:`persona/${Gi}`,voiceCapabilities:ru,clientCapabilities:r.join(`,`)});return n?.forEach((e,t)=>i.set(t,e)),`${Hl(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Gl,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Gl});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:Ql))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${fu} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Rl(Kl);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=du.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${fu} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(du.includes(e))return this.#D=fu,this.#xe(/* @__PURE__ */ Error(fu)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||uu.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||lu:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+au,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(ql,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>Jl;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*Yl));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge?.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[]},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return Bl(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),ou)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,cu),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=Vl(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+iu)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}}})),vu,yu=o((()=>{vu=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}}}));function bu(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new gu(e.runtype);case`browser`:if(!vu.isSupported())throw Error(`Browser speech recognition not supported`);return new vu(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw 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 Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function xu(e){if(e?.type===`custom`&&e.custom)return bu({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return bu({type:`runtype`,runtype:e.runtype});if(vu.isSupported())return bu({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function Su(e){try{return xu(e),!0}catch{return!1}}var Cu=o((()=>{_u(),yu()})),wu,Tu,Eu=o((()=>{wu=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``),Tu=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=wu(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:wu(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}}));function Du(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(Nu.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*Ou(e,t){let n=new RegExp(Pu.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&Du(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function ku(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function Au(e){let t=0;for(let n of Ou(e.slice(0,220),!0))t=n;if(t)return t;let n=ku(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var ju,Mu,Nu,Pu,Fu,Iu=o((()=>{ju=30,Mu=6,Nu=/* @__PURE__ */ new Set(/* @__PURE__ */ `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`.split(`,`)),Pu=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g,Fu=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?Au(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?Au(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=Ou(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=ju||t>=Mu){let t=ku(e,220);if(t)return t}}return e.length>220?Au(e):0}}}));function Lu(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(e=>Lu(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=Lu(n,t+1);return r&&(t?`${Qu(e)} ${r}`:`${Qu(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function Ru(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=Wu-t.length-119-2;return`${t}\n${e.map(t=>{let r=[Qu(t.toolName)];t.description&&r.push(`(${Zu(t.description.trim(),160)})`);let i=Lu(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${Zu(t.reason.trim(),160)}`),Zu(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
|
|
184
|
-
`)}\n\n${
|
|
183
|
+
`)}function Zl(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ou?new Uint8Array(e,44):new Uint8Array(e)}function Ql(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 $l(e){return Ql(e).replace(/^ws/i,`http`)}function eu(e){return typeof e!=`number`||!Number.isFinite(e)?uu:Math.min(fu,Math.max(du,Math.round(e)))}var tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu,yu,bu,xu,Su,Cu,wu,Tu,Eu,Du=o((()=>{Yl(),Zi(),tu=16e3,nu=24e3,ru=4096,iu=tu*2*8,au=4,ou=1380533830,su=3e4,cu=1e3,lu=5e3,uu=3e4,du=3e4,fu=6e5,pu=`full-duplex-v1`,mu=300,hu=2e3,gu=2e3,_u=`runtype-browser-v1`,vu=54e4,yu=`You're talking to an AI assistant. Voice is processed by OpenAI.`,bu=/* @__PURE__ */ 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.`]]),xu=[`provider_error`,`server_restart`],Su=`Voice connection lost.`,Cu=8e3,wu=4e3,Tu=2e3,Eu=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<su)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${$l(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=eu(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,lu)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let i=new URLSearchParams({voiceProtocol:_u,clientVersion:`persona/${Xi}`,voiceCapabilities:pu,clientCapabilities:r});return n?.forEach((e,t)=>i.set(t,e)),`${Ql(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:tu,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:tu});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:cu))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${Su} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Jl(nu);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=xu.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${Su} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(xu.includes(e))return this.#D=Su,this.#xe(/* @__PURE__ */ Error(Su)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||bu.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||yu:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+hu,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(ru,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>iu;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*au));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return Xl(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),gu)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,vu),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=Zl(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+mu)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}}})),Ou,ku=o((()=>{Ou=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}}}));function Au(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new Eu(e.runtype);case`browser`:if(!Ou.isSupported())throw Error(`Browser speech recognition not supported`);return new Ou(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw 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 Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function ju(e){if(e?.type===`custom`&&e.custom)return Au({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return Au({type:`runtype`,runtype:e.runtype});if(Ou.isSupported())return Au({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function Mu(e){try{return ju(e),!0}catch{return!1}}var Nu=o((()=>{Du(),ku()})),Pu,Fu,Iu=o((()=>{Pu=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``),Fu=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=Pu(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:Pu(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}}));function Lu(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(Uu.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*Ru(e,t){let n=new RegExp(Wu.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&Lu(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function zu(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function Bu(e){let t=0;for(let n of Ru(e.slice(0,220),!0))t=n;if(t)return t;let n=zu(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var Vu,Hu,Uu,Wu,Gu,Ku=o((()=>{Vu=30,Hu=6,Uu=/* @__PURE__ */ new Set(/* @__PURE__ */ `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`.split(`,`)),Wu=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g,Gu=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?Bu(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?Bu(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=Ru(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=Vu||t>=Hu){let t=zu(e,220);if(t)return t}}return e.length>220?Bu(e):0}}}));function qu(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(e=>qu(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=qu(n,t+1);return r&&(t?`${cd(e)} ${r}`:`${cd(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function Ju(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=ed-t.length-119-2;return`${t}\n${e.map(t=>{let r=[cd(t.toolName)];t.description&&r.push(`(${sd(t.description.trim(),160)})`);let i=qu(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${sd(t.reason.trim(),160)}`),sd(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
|
|
184
|
+
`)}\n\n${ad}`}function Yu(e){let t=null,n=null,r=()=>e.track(t??n),i=[],a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=(e,t)=>{a.set(e,[...a.get(e)??[],t]),a.size>32&&a.delete(a.keys().next().value)},c=t=>e.messages().find(e=>e.id===t),l=e=>e.approvals.filter(e=>c(e)?.approval?.status===`pending`),u=e=>cd(c(e)?.approval?.toolName??``),d=(t,n,r)=>{t.outcome={status:n,text:r};for(let n of l(t))e.decide(n)},f=t=>t.flatMap(t=>e.messages().find(e=>e.id===t)??[]).filter(e=>!e.variant&&e.content.trim()).map(e=>e.content.trim()).join(`
|
|
185
185
|
|
|
186
|
-
`),p=async t=>{do await
|
|
186
|
+
`),p=async t=>{do await od();while(e.busy()&&!(t&&(e.parked()||t.failed)))};return{clientTools:e.clientTools,recordDirectTurn:e.recordDirect,getHistory:()=>{let t=e.messages().filter(e=>(e.role===`user`||e.role===`assistant`)&&!e.variant&&!e.voiceProcessing&&!e.streaming&&e.content),n=!1,r=[];for(let e=t.length-1;e>=0;--e){let i=t[e];if(i.role===`user`)n=!1;else if(!i.voiceCaption)n=!0;else if(n)continue;r.unshift({role:i.role,content:i.content})}return r},dropDelegation(t,n){o.set(t,!!n),o.size>32&&o.delete(o.keys().next().value);let r=n&&i.find(e=>e.delegationId===t);r&&!r.outcome&&d(r,`timeout`,``);for(let n of a.get(t)??[])n.stopStream?.(),n.dropped=!0,n.ids.length&&e.unspoken(n.ids)},async runDelegatedTurn({delegationId:m,userText:h,userUtteranceIds:g,stream:_,priorToolResults:v}){let y=i.filter(e=>l(e).length),b=y.flatMap(l);if(b.length===1&&id(h)){let e=u(b[0]);return d(y[0],`denied`,``),{status:`denied`,text:`Okay, I cancelled the ${e} request. Nothing was done.`,inChat:!1}}let x=e.parked()&&e.messages().every(e=>!ld(e)||b.includes(e.id));e.busy()&&!x&&await p();let S=new Set(e.messages().map(e=>e.id)),C=()=>e.messages().filter(e=>!S.has(e.id)&&e.variant===`approval`),w={ids:[],failed:!1},T=_?new Gu:null,E=``,D=``,O=!1,k=e=>{for(let t of e)D+=t,_(t)},A;T&&(w.onUpdate=()=>{if(O)return;let e=f(w.ids);if(!e.startsWith(E)){O=!0,clearTimeout(A);return}if(e.length===E.length)return;let t=e.slice(E.length);E=e,k(T.push(t)),clearTimeout(A),A=setTimeout(()=>{O||k(T.idle())},Xu)},w.stopStream=()=>{clearTimeout(A),O=!0,w.onUpdate=void 0}),s(m,w),t=w,r();try{await e.send(h,{userMessageId:e.claim(h,g),priorToolResults:v}),await p(w)}catch{w.failed=!0}finally{t=null,r()}T&&(w.onUpdate?.(),clearTimeout(A),O||k(T.flush()),w.onUpdate=void 0,w.stopStream=void 0);let j=e=>{let t=Zu(D,e);return t>0?{streamedChars:t}:{}},ee=w.ids.flatMap(t=>e.messages().find(e=>e.id===t)??[]),M=f(w.ids),N=w.failed?[]:C().filter(ld),P=new Set(N.map(e=>cd(e.approval.toolName)));for(let t of y){if(t.outcome)continue;for(let n of l(t).filter(e=>P.has(u(e))))t.replaced.add(n),e.decide(n);let n=u(t.approvals[0]);(t.approvals.every(e=>t.replaced.has(e))||x&&t.approvals.every(e=>c(e)?.approval?.status===`denied`))&&(t.outcome={status:`cancelled`,text:`The earlier ${n} request was replaced by the new one; it was not done.`})}if(N.length){let c=new Set(N.map(e=>e.id)),p={delegationId:m,approvals:[...c],at:Date.now(),replaced:/* @__PURE__ */ new Set};return i.push(p),o.get(m)&&d(p,`timeout`,``),M=`${M}\n\n${Ju(N.map(e=>e.approval))}`.trim(),{status:`pending_approval`,text:M,...j(M),followUp:async({signal:o,approvalTimeoutMs:h=td,readBack:g=!0,onUpdate:_})=>{let v={ids:[],failed:!1};a.delete(m),s(m,v);let y=()=>C().filter(e=>c.has(e.id)||v.ids.includes(e.id)),b=()=>C().filter(e=>ld(e)&&!c.has(e.id)&&!i.some(t=>t.approvals.includes(e.id))&&(v.ids.includes(e.id)||e.approval?.toolType===`webmcp`&&n===v)),x=()=>{n=v,r()};g&&x();try{for(;!o.aborted&&!p.outcome&&(t||e.busy()||y().some(ld));){g&&n!==v&&!l(p).length&&x();let t=b();if(t.length){for(let e of t)c.add(e.id),p.approvals.push(e.id);p.at=Date.now(),_?.(Ju(t.map(e=>e.approval)))}if(Date.now()-p.at>=h&&l(p).length&&(!e.busy()||e.parked())){d(p,`timeout`,`That ${u(p.approvals[0])} request expired, so nothing was done.`);break}await od()}}finally{n===v&&(n=null,r()),i.splice(i.indexOf(p),1)}if(o.aborted)return null;if(p.outcome)return p.outcome;if(v.failed)return{status:`failed`,text:`The ${u(p.approvals[0])} request didn't complete.`};let S=y(),w=e=>S.filter(e).map(e=>cd(e.approval.toolName)).join(`, `),T=S.some(e=>e.approval?.status===`approved`),E=w(e=>e.approval?.status===`denied`&&!p.replaced.has(e.id)),D=w(e=>p.replaced.has(e.id)),O=w(e=>e.approval?.status===`timeout`),k=[T?f(v.ids):``,E&&`The user declined the ${E} request in the chat, so ${T?`that part was not done`:`nothing was done`}.`,D&&`The earlier ${D} request was replaced by the new one; it was not done.`,O&&`The ${O} request timed out, so it was not done.`].filter(Boolean).join(`
|
|
187
187
|
|
|
188
|
-
`);return{status:T?`completed`:E?`denied`:D?`cancelled`:O?`timeout`:`completed`,text:k}}}}return!
|
|
188
|
+
`);return{status:T?`completed`:E?`denied`:D?`cancelled`:O?`timeout`:`completed`,text:k}}}}return!w.failed&&e.parked()||ee.some(e=>e.agentMetadata?.awaitingLocalTool&&!e.agentMetadata.askUserQuestionAnswered&&!e.toolCall?.name?.startsWith(`webmcp:`))?(M=`${M}\n\n${$u}`.trim(),{status:w.failed?`failed`:`completed`,text:M,...j(M)}):{status:!w.failed&&M?`completed`:`failed`,text:M,...j(M)}}}}var Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud=o((()=>{Ku(),Xu=200,Zu=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},Qu=50,$u=`I need your answer in the chat before I can continue.`,ed=1e3,td=3e5,nd=`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)`,rd=RegExp(`^(?:${nd})(?: (?:${nd}))?(?: thanks| thank you)?$`),id=e=>rd.test(e.toLowerCase().replace(/[^a-z' ]+/g,` `).replace(/\s+/g,` `).trim()),ad=`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.`,od=()=>new Promise(e=>setTimeout(e,Qu)),sd=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,cd=e=>e.replace(/^webmcp:/,``).replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_\-.]+/g,` `).trim().toLowerCase(),ld=e=>e.variant===`approval`&&e.approval?.status===`pending`})),dd,fd=o((()=>{dd=(e,t,n,r)=>{let i=e.session;try{e.keyed=n?new n({find:e=>i.messages.find(t=>t.id===e),inject:e=>i.injectMessage(e),upsert:e=>i.upsertMessage(e),settle:e=>{i.messages=i.messages.map(t=>e.has(t.id)?{...t,streaming:!1,voiceProcessing:!1}:t),i.callbacks.onMessagesChanged([...i.messages])},setStreaming:t=>{(t||!e.busy())&&e.setStreaming(t)},markSpoken:e=>{i.ttsSpokenMessageIds.add(e)}}):null,r&&t.setSessionBridge&&t.setSessionBridge(r({messages:()=>i.messages,busy:()=>e.busy(),parked:()=>i.webMcpApprovalResolvers.size>0,claim:(t,n)=>e.keyed?.claimUserTurn(t,n)??null,send:(e,t)=>i.sendMessage(e,{viaVoice:!0,voiceTurn:t}),track:t=>{e.setDelegation(t)},unspoken:e=>{for(let t of e)i.ttsSpokenMessageIds.delete(t);i.streaming||i.speakLatestAssistantMessage(e)},clientTools:()=>i.getClient().getVoiceClientTools(),recordDirect:({delegationId:t,userText:n,userUtteranceIds:r,assistantText:a})=>{let o=e.keyed?.claimUserTurn(n,r),s=!1;i.messages=i.messages.map(e=>{if(e.id!==o||e.role!==`user`)return e;s=!0;let{voiceCaption:t,...n}=e;return{...n,viaVoice:!0}}),s?i.callbacks.onMessagesChanged([...i.messages]):n.trim()&&i.injectMessage({role:`user`,content:n.trim()});let c=a.trim();if(!c)return;let l=`voice-direct-${t}`;i.ttsSpokenMessageIds.add(l),i.injectMessage({id:l,role:`assistant`,content:c})},decide:e=>{if(i.webMcpApprovalResolvers.has(e))return i.resolveWebMcpApproval(e,`denied`);let t=i.messages.find(t=>t.id===e)?.approval;t?.status===`pending`&&i.resolveApproval(t,`denied`)}}));let a=e.generation(),o=()=>e.provider()===t&&a===e.generation(),s=(i.config.voiceRecognition??{}).processingErrorText??`Voice processing failed. Please try again.`;t.onResult(e=>{o()&&e.provider!==`runtype`&&e.text&&e.text.trim()&&i.sendMessage(e.text,{viaVoice:!0})}),t.onTranscript&&t.onTranscript((t,n,r,a)=>{if(o()){if(a?.turnId)e.keyed?.apply(t,n,r,a.turnId,a.startMs,a.caption);else if(t===`user`)e.pendingUser?i.upsertMessage({id:e.pendingUser,role:`user`,content:n,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,voiceProcessing:!r}):e.pendingUser=i.injectMessage({role:`user`,content:n,streaming:!1,voiceProcessing:!r}).id,r&&(e.turns().start(a?.turnId),e.pendingUser=null,e.pendingAssistant=i.injectMessage({role:`assistant`,content:``,streaming:!0,voiceProcessing:!0}).id,e.setStreaming(!0));else{if(!e.turns().accepts(a?.turnId))return;e.pendingAssistant?i.upsertMessage({id:e.pendingAssistant,role:`assistant`,content:n,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!r,voiceProcessing:!r}):e.pendingAssistant=i.injectMessage({role:`assistant`,content:n,streaming:!r,voiceProcessing:!r}).id,r&&(e.pendingAssistant&&i.ttsSpokenMessageIds.add(e.pendingAssistant),e.setStreaming(!1),e.pendingAssistant=null)}}}),t.onLevel&&t.onLevel(t=>{o()&&e.setLevel(Number.isFinite(t)?Math.max(0,Math.min(1,t)):0)}),t.onMetrics&&t.onMetrics(e=>{o()&&i.config.voiceRecognition?.onMetrics?.(e)}),t.onError(t=>{o()&&(console.error(`Voice error:`,t),e.pendingAssistant&&=(i.upsertMessage({id:e.pendingAssistant,role:`assistant`,content:s,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,voiceProcessing:!1}),e.setStreaming(!1),e.pendingUser=null,null),e.keyed?.fail(s))}),t.onStatusChange(t=>{o()&&(e.setStatus(t),(t===`listening`||t===`idle`||t===`disconnected`)&&e.settlePending(t!==`listening`),(t===`idle`||t===`disconnected`)&&e.keyed?.settle(),i.callbacks.onVoiceStatusChanged?.(t))}),t.connect()}catch(e){console.error(`Failed to setup voice:`,e)}}})),pd,md=o((()=>{pd=e=>{let t=t=>{if(e.original)return;let n=e.config().voiceRecognition??{};e.original={backgroundColor:t.style.backgroundColor,color:t.style.color,borderColor:t.style.borderColor,iconName:n.iconName??`mic`,iconSize:parseFloat(n.iconSize??``)||e.iconFallbackPx}},n=(t,n,r)=>{let i=t.querySelector(`svg`);i&&i.remove();let a=e.original?.iconSize??(parseFloat(e.config().voiceRecognition?.iconSize??``)||e.iconFallbackPx),o=e.renderIcon(n,a,r,1.5);o&&t.appendChild(o)},r=e=>{e.classList.remove(`persona-voice-recording`,`persona-voice-processing`,`persona-voice-speaking`)};return{recording:()=>{let n=e.mic();if(!n)return;t(n);let i=e.config().voiceRecognition??{},a=i.recordingBackgroundColor,o=i.recordingIconColor,s=i.recordingBorderColor;if(r(n),n.classList.add(`persona-voice-recording`),e.setMicState(`recording`),n.style.backgroundColor=a??`var(--persona-voice-recording-bg, #ef4444)`,n.style.color=o??`var(--persona-voice-recording-indicator, #ffffff)`,o){let e=n.querySelector(`svg`);e&&e.setAttribute(`stroke`,o)}s&&(n.style.borderColor=s),n.setAttribute(`aria-label`,`Stop voice recognition`)},processing:()=>{let i=e.mic();if(!i)return;t(i);let a=e.config().voiceRecognition??{},o=e.session().getVoiceInterruptionMode(),s=e.original,c=a.processingIconName??`loader`,l=a.processingIconColor??s?.color??``,u=a.processingBackgroundColor??s?.backgroundColor??``,d=a.processingBorderColor??s?.borderColor??``;r(i),i.classList.add(`persona-voice-processing`),e.setMicState(`processing`),i.style.backgroundColor=u,i.style.borderColor=d;let f=l||`currentColor`;i.style.color=f,n(i,c,f),i.setAttribute(`aria-label`,`Processing voice input`),o===`none`&&(i.style.cursor=`default`)},speaking:()=>{let i=e.mic();if(!i)return;t(i);let a=e.config().voiceRecognition??{},o=e.session().getVoiceInterruptionMode(),s=e.original,c=o===`cancel`?`square`:o===`barge-in`?`mic`:`volume-2`,l=a.speakingIconName??c,u=a.speakingIconColor??(o===`barge-in`?a.recordingIconColor??s?.color??``:s?.color??``),d=a.speakingBackgroundColor??(o===`barge-in`?a.recordingBackgroundColor??`var(--persona-voice-recording-bg, #ef4444)`:s?.backgroundColor??``),f=a.speakingBorderColor??(o===`barge-in`?a.recordingBorderColor??``:s?.borderColor??``);r(i),i.classList.add(`persona-voice-speaking`),e.setMicState(`speaking`),i.style.backgroundColor=d,i.style.borderColor=f;let p=u||`currentColor`;i.style.color=p,n(i,l,p);let m=o===`cancel`?`Stop playback and re-record`:o===`barge-in`?`Speak to interrupt`:`Agent is speaking`;i.setAttribute(`aria-label`,m),o===`none`&&(i.style.cursor=`default`),o===`barge-in`&&i.classList.add(`persona-voice-recording`)},reset:()=>{let t=e.mic();if(!t)return;r(t),e.setMicState(`idle`);let i=e.original;i&&(t.style.backgroundColor=i.backgroundColor??``,t.style.color=i.color??``,t.style.borderColor=i.borderColor??``,n(t,i.iconName,i.color||`currentColor`),e.original=null),t.style.cursor=``,t.setAttribute(`aria-label`,`Start voice recognition`)}}}})),hd=/* @__PURE__ */ s({BrowserVoiceProvider:()=>Ou,KeyedVoiceTranscript:()=>Fu,RuntypeVoiceProvider:()=>Eu,createBestAvailableVoiceProvider:()=>ju,createMicStateStyles:()=>pd,createVoiceProvider:()=>Au,createVoiceSessionBridge:()=>Yu,isVoiceSupported:()=>Mu,wireSessionVoice:()=>dd}),gd=o((()=>{Nu(),Du(),ku(),Iu(),ud(),fd(),md()}));Pe();const{setLoader:_d,load:vd,getSync:yd}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(gd(),hd))}),bd=vd,xd=yd;function Sd(e){if(!e)return``;let t=Cd(e);return wd(t===null?e:t)}function Cd(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 e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function wd(e){if(!e)return``;let t=e;return t=t.replace(/```[\s\S]*?```/g,` `),t=t.replace(/~~~[\s\S]*?~~~/g,` `),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,`$1`),t=t.replace(/<\/?[a-zA-Z][^>]*>/g,` `),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,``),t=t.replace(/^[ \t]*>[ \t]?/gm,``),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,``),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,``),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,` `),t=t.replace(/(\*\*|__)(.*?)\1/g,`$2`),t=t.replace(/(\*|_)(.*?)\1/g,`$2`),t=t.replace(/~~(.*?)~~/g,`$1`),t=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `),t=t.replace(/[ \t]+/g,` `),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
189
189
|
`),t=t.replace(/\n{2,}/g,`
|
|
190
|
-
`),t.trim()}function hd(e){return e.replace(/\/+$/,``)}async function gd(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 _d,vd=o((()=>{zl(),_d=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new Rl(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${hd(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await gd(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}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}}})),yd,bd=o((()=>{yd=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),xd=/* @__PURE__ */ s({FallbackSpeechEngine:()=>yd,RuntypeSpeechEngine:()=>_d}),Sd=o((()=>{vd(),bd()}));const Cd=()=>Promise.resolve().then(()=>(Sd(),xd));var wd=/* @__PURE__ */ s({createReconnectController:()=>Td});function Td(e){let t=0,n=null,r=null,i=!1,a=()=>{if(r&&=(clearTimeout(r),null),n){let e=n;n=null,e()}},o=()=>{let t=e.getStatus();(t===`resuming`||t===`paused`)&&a()},s=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&o()},c=()=>{o()},l=()=>{i||=(typeof document<`u`&&document.addEventListener(`visibilitychange`,s),typeof window<`u`&&window.addEventListener(`online`,c),!0)},u=()=>{i&&=(typeof document<`u`&&document.removeEventListener(`visibilitychange`,s),typeof window<`u`&&window.removeEventListener(`online`,c),!1)},d=e=>new Promise(t=>{n=t,r=setTimeout(()=>{r=null,n=null,t()},e)}),f=()=>{let n=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,u(),e.setAbortController(null);let r=!1;for(let t of e.getMessages())t.streaming&&(t.streaming=!1,r=!0);let i=e.buildErrorContent(`Connection lost and the response could not be resumed.`);i?e.appendMessage({id:`reconnect-failed-${n?.executionId??e.nextSequence()}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}):r&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus(`idle`),e.onError(/* @__PURE__ */ Error(`Durable session reconnect failed.`))},p=async()=>{let n=e.config.reconnect?.backoffMs??Ed,r=e.config.reconnect?.maxAttempts??n.length,i=e.config.reconnectStream;if(!i)e.setReconnecting(!1);else{for(;e.getResumable()&&t<r;){t+=1,e.setStatus(`resuming`);let a=e.getResumable(),o=a.lastEventId,s=new AbortController;e.setAbortController(s),e.emitReconnect({phase:`resuming`,handle:a,attempt:t});let c=null;try{let e=await i({executionId:a.executionId,after:a.lastEventId,signal:s.signal});e&&e.ok&&e.body&&(c=e.body)}catch{c=null}if(s.signal.aborted)return;if(c){let n=e.getMessages().find(e=>e.id===a.assistantMessageId)?.content,r=typeof n==`string`?n:``;try{await e.resumeConnect(c,a.assistantMessageId,r)}catch{}if(s.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,u(),e.emitReconnect({phase:`resumed`,handle:a});return}e.getResumable().lastEventId!==o&&(t=0)}if(e.getResumable()&&t<r&&(e.setStatus(`paused`),await d(n[Math.min(t-1,n.length-1)]??1e3),s.signal.aborted))return}e.getResumable()&&f()}};return{begin(){t=0,l(),p()},teardown(){r&&=(clearTimeout(r),null),n=null,t=0,u()},wake:a}}var Ed,Dd=o((()=>{Ed=[1e3,2e3,4e3,8e3,8e3]}));ve();const{setLoader:Od,load:kd}=_e({fallbackImport:()=>Promise.resolve().then(()=>(Dd(),wd))}),Ad=kd;Jt(),Mr(),La(),tn(),qa();const jd=/* @__PURE__ */ `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`.split(`.`);function Md(e,t){return jd.some(n=>e[n]!==t[n])}var Nd=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Pd(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`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?`${r}\n\n_Details: ${n.message}_`:r}const Fd=e=>Kt(e)||e===`suggest_replies`;var Id=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new Ll,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Il(()=>this.#W()),this.#Fe=null,this.#Ie=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&wl().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(Kt(r.name)||r.name===`suggest_replies`&&jr(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.#Re(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#qe(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Je()){this.#Xe();return}if(this.#rt(e.status),e.status===`connecting`)this.#it(!0);else if(e.status===`idle`||e.status===`error`){this.#Ye()||this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null,this.#De(),this.#Se());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#ze()}}else e.type===`error`?(this.#rt(`error`),this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#Ke(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ut()})),this.messages=this.#dt(this.messages),this.client=new to(e,this.historyInternals),this.#pe(),this.#Pe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ge(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&ud().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&Cd().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return st(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Fl.isSupported()?new Fl({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return Cd().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=ud().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#it(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!ot(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new Ll,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#it(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#ut()};this.#ct(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#pe()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#fe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new Nd(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new ro(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Nd(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new Nd(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Nd(`superseded`,`A later selection won`);this.#S=!0;try{await this.#ce(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#ue();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#le(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=Wa(this.messages,a.messages);this.messages=this.#dt(o.map(e=>this.#lt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new Nd(`superseded`,`A later action won`);await this.#ie(i)}async#ie(e){this.#de(),await this.#ce(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#le(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#ae(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new Nd(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#ae(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new Nd(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#ae(e){this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#oe(e)}async#oe(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ie(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#se(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#oe(this.#$()),this.#C===`new_conversation_required`))throw new Nd(`new_conversation_required`,`A new conversation is required before sending`)}async#ce(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#le(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#ue(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#ye(null)}#de(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.#ue(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#fe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#de(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#pe(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#me(e))))}#me(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#de():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#ye(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#he(){return this.#P?(this.#F||=this.#ge().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#ge(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#_e(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#_e(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=new Set(a.messages.map(e=>e.id)),s=this.messages.some(e=>o.has(e.id)),c=a.messages[0]?.createdAt,l;if(!s)l=a.messages.map(e=>this.#lt(e));else{let e=this.#r?this.#i:null;l=Wa(this.messages.filter(t=>o.has(t.id)||t.id===e?!0:c!==void 0&&t.createdAt<c),a.messages).map(e=>this.#lt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#le(),this.messages=this.#dt(l),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ye(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#be(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#xe(e){if(this.#ve())for(let t of e){let e=Ua(t);e!==void 0&&this.#O.set(t.id,e)}}#Se(){if(!this.#ve())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=Ua(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#ye({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ce(e,t))}#Ce(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#we(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#we(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#Ee(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#Ee(e,t)}catch(i){if(!n&&this.#Te(i)){await this.#we(e,r,!0);return}if(i instanceof Ja&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ee(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Te(e){return e instanceof Ja?e.code===`request_failed`:e instanceof Error}#Ee(e,t){let n=this.#be();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#ye(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#be();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#ye(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#ye(null):(this.#Ce(e.conversationId,t),await this.#D?.catch(()=>{}))}#De(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#he(),this.#C===`new_conversation_required`&&await this.#se()}static#ke(e){return e instanceof Ja&&e.code===`conversation_deleted`}async#Ae(t,n,r,i,a){this.#xe(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken},this.handleEvent);return}catch(t){if(!e.#ke(t))throw t;let o=await this.#je(i);if(!o)throw t;this.#xe([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken},this.handleEvent)}}async#je(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ie(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ct(n),this.#it(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=at(this.config,n),i=Md(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&ot(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#Ue();return}this.#Ve(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new to(this.config,this.historyInternals),a&&this.#Ue(),this.#Pe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?Ri():t===`assistant`?zi():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#ut(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?Ri():e===`assistant`?zi():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#ut(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#dt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Me(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
190
|
+
`),t.trim()}function Td(e){return e.replace(/\/+$/,``)}async function Ed(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 Dd,Od=o((()=>{Yl(),Dd=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new Jl(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${Td(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Ed(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}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}}})),kd,Ad=o((()=>{kd=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),jd=/* @__PURE__ */ s({FallbackSpeechEngine:()=>kd,RuntypeSpeechEngine:()=>Dd}),Md=o((()=>{Od(),Ad()}));const Nd=()=>Promise.resolve().then(()=>(Md(),jd));var Pd=/* @__PURE__ */ s({createReconnectController:()=>Fd});function Fd(e){let t=0,n=null,r=null,i=!1,a=()=>{if(r&&=(clearTimeout(r),null),n){let e=n;n=null,e()}},o=()=>{let t=e.getStatus();(t===`resuming`||t===`paused`)&&a()},s=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&o()},c=()=>{o()},l=()=>{i||=(typeof document<`u`&&document.addEventListener(`visibilitychange`,s),typeof window<`u`&&window.addEventListener(`online`,c),!0)},u=()=>{i&&=(typeof document<`u`&&document.removeEventListener(`visibilitychange`,s),typeof window<`u`&&window.removeEventListener(`online`,c),!1)},d=e=>new Promise(t=>{n=t,r=setTimeout(()=>{r=null,n=null,t()},e)}),f=()=>{let n=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,u(),e.setAbortController(null);let r=!1;for(let t of e.getMessages())t.streaming&&(t.streaming=!1,r=!0);let i=e.buildErrorContent(`Connection lost and the response could not be resumed.`);i?e.appendMessage({id:`${$a}${n?.executionId??e.nextSequence()}`,role:`assistant`,content:i,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}):r&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus(`idle`),e.onError(/* @__PURE__ */ Error(`Durable session reconnect failed.`))},p=async()=>{let n=e.config.reconnect?.backoffMs??Id,r=e.config.reconnect?.maxAttempts??n.length,i=e.config.reconnectStream;if(!i)e.setReconnecting(!1);else{for(;e.getResumable()&&t<r;){t+=1,e.setStatus(`resuming`);let a=e.getResumable(),o=a.lastEventId,s=new AbortController;e.setAbortController(s),e.emitReconnect({phase:`resuming`,handle:a,attempt:t});let c=null;try{let e=await i({executionId:a.executionId,after:a.lastEventId,signal:s.signal});e&&e.ok&&e.body&&(c=e.body)}catch{c=null}if(s.signal.aborted)return;if(c){let n=e.getMessages().find(e=>e.id===a.assistantMessageId)?.content,r=typeof n==`string`?n:``;try{await e.resumeConnect(c,a.assistantMessageId,r)}catch{}if(s.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,u(),e.emitReconnect({phase:`resumed`,handle:a});return}e.getResumable().lastEventId!==o&&(t=0)}if(c&&e.getResumable()&&e.settleParked(a.executionId)){t=0,u();return}if(e.getResumable()&&t<r&&(e.setStatus(`paused`),await d(n[Math.min(t-1,n.length-1)]??1e3),s.signal.aborted))return}e.getResumable()&&f()}};return{begin(){t=0,l(),p()},teardown(){r&&=(clearTimeout(r),null),n=null,t=0,u()},wake:a}}var Id,Ld=o((()=>{to(),Id=[1e3,2e3,4e3,8e3,8e3]}));Pe();const{setLoader:Rd,load:zd}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Ld(),Pd))}),Bd=zd;E(),Ir(),Wi(),Ha(),an(),Qa();const Vd=/* @__PURE__ */ `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`.split(`.`);function Hd(e,t){return Vd.some(n=>e[n]!==t[n])}var Ud=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function Wd(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`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?`${r}\n\n_Details: ${n.message}_`:r}const Gd=e=>w(e)||e===`suggest_replies`;var Kd=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new ql,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Kl(()=>this.#W()),this.#Ie=null,this.#Le=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&Ml().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(w(r.name)||r.name===`suggest_replies`&&Fr(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#ze(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#Je(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Ye()){this.#Ze();return}if(this.#st(e.status),e.status===`connecting`)this.#ct(!0);else if(e.status===`idle`||e.status===`error`){this.#Xe()||this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null,this.#Oe(),this.#Ce());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#Be()}}else e.type===`error`?(this.#st(`error`),this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#qe(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...O(e),sequence:e.sequence??this.#mt()})),this.messages=this.#ht(this.messages),this.client=new lo(e,this.historyInternals),this.#me(),this.#Fe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ke(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&bd().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&Nd().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return _t(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Gl.isSupported()?new Gl({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return Nd().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=bd().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#ct(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!ht(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new ql,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#ct(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#mt()};this.#ft(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#me()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#pe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new Ud(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new fo(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Ud(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new Ud(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new Ud(`superseded`,`A later selection won`);this.#S=!0;try{await this.#le(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#de();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#ue(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ie(a.messages),s=Ya(this.messages,o);this.messages=this.#ht(s.map(e=>this.#pt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:o,nextMessageCursor:a.nextCursor}}#ie(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&D(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return O(e)})}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new Ud(`superseded`,`A later action won`);await this.#ae(i)}async#ae(e){this.#fe(),await this.#le(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#ue(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#oe(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new Ud(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#oe(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new Ud(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#oe(e){this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#se(e)}async#se(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ae(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#ce(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#se(this.#$()),this.#C===`new_conversation_required`))throw new Ud(`new_conversation_required`,`A new conversation is required before sending`)}async#le(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#ue(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#de(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#be(null)}#fe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.#de(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#pe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#fe(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#me(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#he(e))))}#he(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#fe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#be(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#ge(){return this.#P?(this.#F||=this.#_e().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#_e(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#ve(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#ve(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=this.#ie(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#pt(e));else{let e=this.#r?this.#i:null;u=Ya(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#pt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#ue(),this.messages=this.#ht(u),this.callbacks.onMessagesChanged([...this.messages])}#ye(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#be(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#xe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#Se(e){if(this.#ye())for(let t of e){let e=Ja(t);e!==void 0&&this.#O.set(t.id,e)}}#Ce(){if(!this.#ye())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=Ja(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#be({conversationId:e,messageIds:t.map(e=>e.id)}),this.#we(e,t))}#we(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#Te(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#Te(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#De(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#De(e,t)}catch(i){if(!n&&this.#Ee(i)){await this.#Te(e,r,!0);return}if(i instanceof no&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#De(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Ee(e){return e instanceof no?e.code===`request_failed`:e instanceof Error}#De(e,t){let n=this.#xe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#be(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ye())return;let e=this.#xe();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#be(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#be(null):(this.#we(e.conversationId,t),await this.#D?.catch(()=>{}))}#Oe(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#ke(){await this.awaitHistorySettled(),await this.#ge(),this.#C===`new_conversation_required`&&await this.#ce()}static#Ae(e){return e instanceof no&&e.code===`conversation_deleted`}async#je(t,n,r,i,a){this.#Se(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent);return}catch(t){if(!e.#Ae(t))throw t;let o=await this.#Me(i);if(!o)throw t;this.#Se([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Me(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ae(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ft(n),this.#ct(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=mt(this.config,n),i=Hd(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&ht(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#We();return}this.#He(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new lo(this.config,this.historyInternals),a&&this.#We(),this.#Fe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?Vi():t===`assistant`?Hi():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#mt(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?Vi():e===`assistant`?Hi():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#mt(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#ht([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Ne(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
191
191
|
|
|
192
192
|
`),a=[i,t].filter(Boolean).join(`
|
|
193
193
|
|
|
194
|
-
`),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(wa(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(wa(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#Ve(),this.#Ie++,this.#et();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Ri(),s=zi();this.#i=null;let c=t?.contentParts&&Ca(t.contentParts)?Na:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#ut(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ct(l),this.#it(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Me(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Ol({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(/* @__PURE__ */ new Date()).toISOString()}]:[...this.messages];try{await this.#Ae(d,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=Pd(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,sequence:this.#ut()};this.#ct(e)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=Al(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?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}},c=i?this.#Ne(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Ne(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.abortController?.abort(),this.#et();let e=zi();this.#i=null,this.#it(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=Pd(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,sequence:this.#ut()};this.#ct(t)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#it(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#at(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ot(i);return}this.#at(i),this.#rt(`error`),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Pe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t={id:`webmcp-${++this.#d}`,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${t.id}`;return this.upsertMessage({id:n,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:t}),new Promise(t=>{this.webMcpApprovalResolvers.set(n,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(n,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Fe;#Ie;#Le(e){let t=this.#Fe??={s:this,setStreaming:e=>this.#it(e),appendMessage:e=>this.#ct(e),nextSequence:()=>this.#ut(),settleApprovalPausedToolCall:e=>this.#st(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=Tl();if(n)return e(n,t);let r=this.#Ie;return wl().then(n=>r===this.#Ie?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Le((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Le((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Le((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#Re(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#ze(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Be(e)})}#Be(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Le((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#Ve(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#it(!1),this.#rt(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ge()}clearArtifacts(){this.#We()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ge(),e.transcript!==!1&&this.#He(n),n}#He(e){let t=`artifact-ref-${e.id}`,n=en($t(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#Ue(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=en($t(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...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}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#We(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ge())}#Ge(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#Ke(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ge()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#dt(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ut()}))),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ge()}#qe(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#nt(n)}#Je(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ye()}#Ye(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Xe(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#it(!0),this.#rt(`resuming`),this.#Ze().then(e=>{this.#a&&this.#r&&e.begin()}))}#Ze(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=Ad().then(({createReconnectController:e})=>{let t=e(this.#Qe());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#Qe(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#tt(),getStatus:()=>e.status,setStatus:t=>e.#rt(t),setStreaming:t=>e.#it(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ct(t),nextSequence:()=>e.#ut(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Pd(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Xe()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;let t=this.#$e();t||(t=zi(),this.#ct({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#ut()})),this.#i=t,this.agentExecution||={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Xe()}#$e(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#et(){this.#a=!1,this.#o?.teardown(),this.#tt()}#tt(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#nt(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#rt(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#it(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#at(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=fd(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Pl(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=fd(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#at(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#st(t))}#ot(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#st(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ct(e){let t=this.#lt(e);this.messages=this.#dt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#lt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ct(t):(this.messages=this.messages.map((e,r)=>{if(r!==n)return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&Fd(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&Fd(a)&&e.toolCall?.status===`complete`;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#dt(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#lt(e){return e.sequence===void 0?{...e,sequence:this.#ut()}:{...e}}#ut(){return this.#n++}#dt(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};H(),g(),ze(),La();const Ld={add:e=>ka(e)},Rd=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,zd={allowedTypes:Ia,maxFileSize:10485760,maxFiles:4};function Bd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Vd(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?u.FileText:e.includes(`excel`)||e.includes(`spreadsheet`)?u.FileSpreadsheet:e===`application/json`?u.FileCode:u.File}var Hd=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??zd.allowedTypes,maxFileSize:e.maxFileSize??zd.maxFileSize,maxFiles:e.maxFiles??zd.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:Ld}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:zd.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=Aa(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:Bd(),file:n,previewUrl:Da(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=Rd(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=Da(e.file),n=z(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=z(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=z(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=Vd(e.file.type),i=h(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=z(`span`);a.textContent=Ma(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=B(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=z(`div`,`persona-attachment-progress`);i.appendChild(z(`div`,`persona-attachment-progress__bar`));let a=B(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=U(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=z(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=h(u.X,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){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})}};const Ud=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Wd=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function Gd(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),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:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{Wd(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{Ud(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{Ud(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}H();const Kd=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},qd=(e,t)=>{let n=z(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function Jd(e,t={}){let n=Kd(e,`[data-persona-composer-form]`),r=Kd(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:Kd(e,`[data-persona-composer-header]`),body:Kd(e,`[data-persona-composer-body]`),actionsStart:Kd(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:Kd(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:Kd(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:Kd(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:Kd(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=qd(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=qd(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=Kd(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:Kd(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:Kd(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:Kd(e,`[data-persona-composer-submit]`)??void 0,micButton:Kd(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}Ps(),H(),ze(),is();const Yd=[`--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`],Xd=`data-persona-menu-focus`,Zd=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function Qd(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const $d=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function ef(e){let t=e.label,n=!1,r=z(`div`,`persona-send-button-wrapper`),i=B(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Jo} ${Yo}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=B(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=U(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&Qd(t)===e;t.toggleAttribute(Xd,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(Qd).filter(e=>!$d(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=As({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(Xd);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,Xo(i,a,Yd),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},O=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},k=e=>{switch(Zd.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,O),a.addEventListener(`keydown`,k),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(Xd);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,O),a.removeEventListener(`keydown`,k),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}H(),ze(),Io(),is();const tf={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},nf=`data-persona-composer-action`,rf=`data-persona-composer-disable-when-streaming`,af=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function of(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 r=z(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function sf(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const cf=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},lf=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function uf(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?cf(t,`[Persona] composer action "${e.id}" is already contributed by ${df(i)}; the ${df(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?lf(r,e.id):e.id,s=e.order??tf.custom;e.placement===`end`&&s>=tf.send&&(cf(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${tf.send-1}.`),s=tf.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const df=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,ff=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,pf=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function mf(e,t){if(!e||e===`always`)return!0;let n=pf(t);return e===`when-text`?n:!n}const hf=e=>e.kind===`custom`,gf=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,_f=e=>{let t=gf(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function vf(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const yf=e=>vf(e).length===0;function bf(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=z(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=U(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=z(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(rf,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=V(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,Jo,Yo,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=U(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=z(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=yo({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=B(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=z(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(nf,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(nf,t.id),r.element.toggleAttribute(rf,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?hf(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=ef({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=sf(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??sf(e);n!==g&&(g=n,T())}),h.observe(e)))},b=(e,t)=>{let n=of(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||sf(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=af(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},S=e=>{let t=e.menuSlot;if(!t)return;if(!yf(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=_f(e.element);n?(e.menuLabel||=z(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},C=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!hf(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=B(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[Ao]:``}});t.appendChild(e.element),vo(gf(e.element)),e.menuSlot=t;let n=t=>{let n=gf(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,S(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},w=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},T=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||ff(r.visible,a,!0)&&mf(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=C(n,x(n,s,c)),r){let e=ff(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!hf(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(S(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();w(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:tf.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=uf(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&hf(r)!==hf(i)||r&&i&&hf(r)&&hf(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!hf(i)?o(n,i):i&&n.element.toggleAttribute(rf,i.disableWhenStreaming===!0)}n=i,T()},sync:T,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}Ps(),H(),ze(),is();const xf=[`--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`],Sf=()=>({wrapper:B(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:B(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Cf(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=B(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=B(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=Sf();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=B(`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`}}),a=z(`span`,`persona-composer-model-picker-label`),o=z(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=B(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=As({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),Xo(n,s,xf),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=B(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=U(e.icon,16,`currentColor`,1.5);if(n){let e=z(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=z(`span`,`persona-composer-model-option-body`),r=z(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=z(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=z(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=U(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=Sf();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}H(),ze(),gs();function wf(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=B(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=z(`span`,`persona-mention-chip-icon`),r=U(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=z(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=B(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=U(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),ps(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}ps(t)},destroy:()=>{r=!0,c(),ps(t)}}}const Tf=e=>`core:mode:${e}`,Ef=e=>Math.min(300+e,499),Df=e=>`core:mode-group:${e}`;function Of(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function kf(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function Af(e,t){return e?.length?e.filter(e=>!Of(e.groupId,t)&&!kf(e.groupId,t)):[]}const jf=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function Mf(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(jf(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function Nf(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Pf(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Ff(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}H(),ze();function If(e){let t=null;return{action:{id:Df(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=B(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=B(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=U(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=z(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}H(),ze();function Lf(e){let t=B(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=z(`span`,`persona-composer-quote-bar`),i=z(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=z(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=B(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=kl(n.text),i.appendChild(a);let o=B(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=U(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}H(),ze();function Rf(e){let t=B(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=B(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=U(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=kl(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=z(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=B(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}H();function zf(e){let t=B(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=B(`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 r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=z(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=B(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Bf(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 Vf(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function Hf(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function Uf(e){return e.wrapped||e.text.includes(`
|
|
195
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Wf(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Gf(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function Kf(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 qf(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const Jf=e=>typeof e?.then==`function`;function Yf(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Xf(e,t,n){let r;try{r=e(Kf(t),{signal:n})}catch(e){return{status:`error`,error:e}}return Jf(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:Yf(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):Yf(t,r)}const Zf=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),Qf={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`};he();const $f=`16px`,ep=`transparent`,tp={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:(()=>{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})(),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`}},np={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`}},rp={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:se,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:$f,canvasBackground:ep,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`}}},ip=tp.colors.gray,ap={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},op={...tp,colors:{...tp.colors,gray:ip}},sp={...tp,colors:{...tp.colors,gray:ap},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},cp=np,lp={...np,colors:{...np.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...np.typography,fontSize:`14px`,lineHeight:`1.5`}},up=rp,dp={...rp,launcher:Qf,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:{...rp.input,borderRadius:`palette.radius.full`},introCard:{...rp.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...rp.suggestion.chip,fontWeight:`400`},card:{...rp.suggestion.card,fontWeight:`400`},list:{...rp.suggestion.list,fontWeight:`400`}},panel:{...rp.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...rp.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:{...rp.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...rp.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:{...rp.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...rp.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)`}},fp=e=>re({future:e}),pp=e=>fp(e)===`v5`?{palette:sp,semantic:lp,components:dp}:{palette:op,semantic:cp,components:up};function mp(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?mp(e,r):r}function hp(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=mp(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function gp(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 _p(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?_p(t,r):r}return n}function vp(e,t){return t?_p(e,t):e}function yp(e,t={}){let n=pp(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:vp(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=gp(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const bp=e=>e.trim()===`0`?`0px`:e,xp=`--persona-`,Sp=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Cp=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[xp+n],t!==void 0)break;t!==void 0&&(e[xp+n]=t)}};function wp(e){let t=hp(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}Cp(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 r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],Cp(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`]]),Cp(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`]}`,Cp(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`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,Cp(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`]]),Cp(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],Cp(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`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],Cp(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),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 e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}Cp(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,Cp(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`]]),Cp(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 _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),Cp(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`]]),Cp(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),Cp(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),Cp(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),Cp(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`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}Cp(n,[[`message-border`,`components-message-border`,`border`]]),Cp(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 S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.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 T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=bp(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=bp(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=mp(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=bp(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=mp(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=mp(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=mp(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=mp(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=mp(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=mp(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=mp(e,D.background)??D.background));let O=n[`--persona-surface`],k=n[`--persona-container`],A=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,j=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,M=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,ee=!k||k===O,N=Sp(O??n[`--persona-background`]),P=ee&&N!==void 0&&N<.179,F=P?`rgba(255, 255, 255, 0.08)`:A,te=P?`rgba(255, 255, 255, 0.12)`:j,ne=P?`rgba(255, 255, 255, 0.16)`:M,I=ee?F:k,re=ee?te:k;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??I,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??re,ee&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??ne),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??I,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??I,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??I,n}he(),y();const Tp=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),Ep=(e,t)=>{if(!t||!Tp(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Lp(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:re(t)===`v5`?`400px`:`420px`}}}:e},Dp={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`}}},Op={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)`}}}},kp=Dp,Ap={...kp,colors:{...kp.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`}}},jp=Op,Mp={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:{...Op.components,button:{...Op.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:{...Op.components?.eventStream,badge:{...Op.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`}}}}},Np=e=>re({future:e})===`v5`?{palette:Ap,components:Mp}:{palette:kp,components:jp},Pp=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},Fp=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Ip=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:Fp()},Lp=e=>Ip(e),Rp=(e,t={})=>yp(e,t),zp=(e,t={})=>{let n=Np(t.future),r=_(n.components,e??{})??{};return yp({...r,palette:{...r.palette,colors:re(t)===`v5`?_(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Bp=e=>{let t=Lp(e),n=Pp(e?.theme),r=_({components:{launcher:Zf(e)===`circle`?Qf:{...up.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}}}},n),i=Pp(e?.darkTheme);return Ep(t===`dark`?zp(_(r??{},i??{}),{future:e?.future}):Rp(r,{future:e?.future}),e)},Vp=e=>wp(e),Hp=(e,t)=>{let n=Bp(t),r=Vp(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,Lp(t)),e.setAttribute(`data-persona-defaults`,re(t))},Up=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(Fp())});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)`),r=()=>e(Fp());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Wp=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Gp=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Kp=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},qp=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,im,am,om=o((()=>{Jp=null,Yp=()=>{if(Jp!==null)return Jp;if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},Xp=`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`,Zp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Qp=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return Zp(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Zp(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},$p=e=>Xp.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),em=(e,t)=>{let n=Qp(e);if(!n)return``;let r=Yp(),i=$p(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},tm=e=>em(e,!1),nm=e=>em(e,!0),rm=(e,t)=>t.key?.toLowerCase()===e.key&&(Yp()?t.metaKey:t.ctrlKey)===e.mod&&!(Yp()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,im=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},am=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(rm(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!im(n))){e.preventDefault();try{i.run(e)}catch(e){Zp(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=Qp(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(Zp(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,nm(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}}}));om();const sm=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;m.Idiomorph.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},cm=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),lm={index:-1,draft:``};function um(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function dm(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 fm(){return/* @__PURE__ */ new Map}function pm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function mm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function hm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function gm(e){return e.role!==`assistant`||e.variant===`tool`||e.variant===`reasoning`?!1:e.variant===`approval`||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function _m(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function vm(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ym(e,t){return vm(e)-e.scrollTop<=t}function bm(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function xm(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function Sm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Cm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function wm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Tm=o((()=>{})),Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm=o((()=>{Em={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},Dm=[`pre`,`code`,`a`,`script`,`style`],Om=e=>({type:e?.type??Em.type,placeholder:e?.placeholder??Em.placeholder,speed:e?.speed??Em.speed,duration:e?.duration??Em.duration,buffer:e?.buffer??Em.buffer}),km=[{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`}],Am=/* @__PURE__ */ new Map;for(let e of km)Am.set(e.name,e);jm=[`wipe`,`glyph-cycle`],Mm=e=>{Am.set(e.name,e)},Nm=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Am.get(e)??null,Pm=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
|
|
196
|
-
`);return t<0?``:e.slice(0,t)}return e},
|
|
194
|
+
`),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(ka(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(ka(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.stopSpeaking(),this.abortController?.abort(),this.#He(),this.#Le++,this.#it();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Vi(),s=Hi();this.#i=null;let c=t?.contentParts&&Oa(t.contentParts)?Ra:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#mt(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ft(l),this.#ct(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Ne(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Rl({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=(/* @__PURE__ */ new Date()).toISOString(),f=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:d}]:[...this.messages],p=(a??this.messages.find(e=>e.id===o))?.createdAt??d,m=Fl(t?.voiceTurn?.priorToolResults,p);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#ft(e),f.push({...e,createdAt:d}));let h=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:n,args:r,result:i}=e.clientToolAnswer;return{toolCallId:t,name:n,arguments:r,result:i}});try{await this.#je(f,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...h.length>0&&{voicePriorToolResults:h}})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=Wd(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,localOnly:!0,sequence:this.#mt()};this.#ft(e)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=Bl(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?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}},c=i?this.#Pe(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Pe(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.abortController?.abort(),this.#it();let e=Hi();this.#i=null,this.#ct(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=Wd(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,localOnly:!0,sequence:this.#mt()};this.#ft(t)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#lt(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ut(i);return}this.#lt(i),this.#st(`error`),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Fe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do t=`webmcp-${++this.#d}`;while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let n={id:t,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:n}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(r,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Ie;#Le;#Re(e){let t=this.#Ie??={s:this,setStreaming:e=>this.#ct(e),appendMessage:e=>this.#ft(e),nextSequence:()=>this.#mt(),settleApprovalPausedToolCall:e=>this.#dt(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=Nl();if(n)return e(n,t);let r=this.#Le;return Ml().then(n=>r===this.#Le?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Re((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Re((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Re((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ze(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#Be(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Ve(e)})}#Ve(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Re((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#He(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ct(!1),this.#st(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ke()}clearArtifacts(){this.#Ge()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ke(),e.transcript!==!1&&this.#Ue(n),n}#Ue(e){let t=`artifact-ref-${e.id}`,n=rn(nn(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#We(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=rn(nn(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...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}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ge(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ke())}#Ke(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#qe(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ke()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ht(e.map(e=>({...O(e),streaming:!1,sequence:e.sequence??this.#mt()}))),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ke()}#Je(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#ot(n)}#Ye(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Xe()}#Xe(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Ze(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#ct(!0),this.#st(`resuming`),this.#Qe().then(e=>{this.#a&&this.#r&&e.begin()}))}#Qe(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=Bd().then(({createReconnectController:e})=>{let t=e(this.#$e());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#$e(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#at(),getStatus:()=>e.status,setStatus:t=>e.#st(t),setStreaming:t=>e.#ct(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ft(t),settleParked:t=>e.#et(t),nextSequence:()=>e.#mt(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Wd(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Ze()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;if(this.#Xe()){this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#i??``,status:`running`};return}let t=this.#nt(e.executionId)?Hi():this.#rt();t||(t=Hi(),this.#ft({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#mt()})),this.#i=t,this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Ze()}#et(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#Xe()){if(!this.#nt(e))return!1;this.#at()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!1),this.abortController=null}return this.#st(`idle`),!0}#tt(e){this.agentExecution||={executionId:e,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0}}#nt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>e?.interrupted===!0))}#rt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#it(){this.#a=!1,this.#o?.teardown(),this.#at()}#at(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#ot(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#st(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ct(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#lt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Sd(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Wl(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Sd(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#lt(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#dt(t))}#ut(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#dt(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ft(e){let t=this.#pt(e);this.messages=this.#ht([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#pt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ft(t):(this.messages=this.messages.map((e,r)=>{if(r!==n||e.toolCall?.name&&w(e.toolCall.name)&&e.toolCall.status===`complete`&&t.toolCall?.id===e.toolCall.id&&t.toolCall.status!==`complete`&&(t.toolCall.status===`pending`&&!t.toolCall.name||!e.toolCall.interrupted&&(e.toolCall.result!==void 0||e.toolCall.success!==void 0)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&Gd(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&Gd(a)&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#ht(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#pt(e){return e.sequence===void 0?{...e,sequence:this.#mt()}:{...e}}#mt(){return this.#n++}#ht(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};H(),ee(),W(),Ha();const qd={add:e=>Pa(e)},Jd=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Yd={allowedTypes:Va,maxFileSize:10485760,maxFiles:4};function Xd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Zd(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?u.FileText:e.includes(`excel`)||e.includes(`spreadsheet`)?u.FileSpreadsheet:e===`application/json`?u.FileCode:u.File}var Qd=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??Yd.allowedTypes,maxFileSize:e.maxFileSize??Yd.maxFileSize,maxFiles:e.maxFiles??Yd.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:qd}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Yd.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=Fa(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:Xd(),file:n,previewUrl:Ma(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=Jd(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=Ma(e.file),n=B(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=B(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=B(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=Zd(e.file.type),i=j(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=B(`span`);a.textContent=La(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=V(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=B(`div`,`persona-attachment-progress`);i.appendChild(B(`div`,`persona-attachment-progress__bar`));let a=V(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=U(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=B(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=j(u.X,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){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})}};const $d=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),ef=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function tf(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),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:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{ef(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{$d(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{$d(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}H();const nf=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},rf=(e,t)=>{let n=B(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function af(e,t={}){let n=nf(e,`[data-persona-composer-form]`),r=nf(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:nf(e,`[data-persona-composer-header]`),body:nf(e,`[data-persona-composer-body]`),actionsStart:nf(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:nf(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:nf(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:nf(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:nf(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=rf(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=rf(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=nf(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:nf(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:nf(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:nf(e,`[data-persona-composer-submit]`)??void 0,micButton:nf(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}Hs(),H(),W(),fs();const of=[`--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`],sf=`data-persona-menu-focus`,cf=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function lf(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const uf=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function df(e){let t=e.label,n=!1,r=B(`div`,`persona-send-button-wrapper`),i=V(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ns} ${rs}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=V(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=U(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&lf(t)===e;t.toggleAttribute(sf,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(lf).filter(e=>!uf(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=Rs({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(sf);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,is(i,a,of),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},O=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},k=e=>{switch(cf.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,O),a.addEventListener(`keydown`,k),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(sf);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,O),a.removeEventListener(`keydown`,k),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}H(),W(),Wo(),fs();const ff={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},pf=`data-persona-composer-action`,mf=`data-persona-composer-disable-when-streaming`,hf=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function gf(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 r=B(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function _f(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const vf=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},yf=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function bf(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?vf(t,`[Persona] composer action "${e.id}" is already contributed by ${xf(i)}; the ${xf(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?yf(r,e.id):e.id,s=e.order??ff.custom;e.placement===`end`&&s>=ff.send&&(vf(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${ff.send-1}.`),s=ff.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const xf=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Sf=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Cf=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function wf(e,t){if(!e||e===`always`)return!0;let n=Cf(t);return e===`when-text`?n:!n}const Tf=e=>e.kind===`custom`,Ef=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,Df=e=>{let t=Ef(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Of(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const kf=e=>Of(e).length===0;function Af(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=B(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=U(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=B(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(mf,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=Me(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,ns,rs,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=U(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=B(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=Do({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=V(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=B(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(pf,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(pf,t.id),r.element.toggleAttribute(mf,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Tf(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=df({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=_f(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??_f(e);n!==g&&(g=n,T())}),h.observe(e)))},b=(e,t)=>{let n=gf(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||_f(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=hf(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},S=e=>{let t=e.menuSlot;if(!t)return;if(!kf(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=Df(e.element);n?(e.menuLabel||=B(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},C=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Tf(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=V(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[Ro]:``}});t.appendChild(e.element),Eo(Ef(e.element)),e.menuSlot=t;let n=t=>{let n=Ef(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,S(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},w=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},T=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Sf(r.visible,a,!0)&&wf(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=C(n,x(n,s,c)),r){let e=Sf(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Tf(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(S(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();w(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:ff.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=bf(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Tf(r)!==Tf(i)||r&&i&&Tf(r)&&Tf(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Tf(i)?o(n,i):i&&n.element.toggleAttribute(mf,i.disableWhenStreaming===!0)}n=i,T()},sync:T,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}Hs(),H(),W(),fs();const jf=[`--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`],Mf=()=>({wrapper:V(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:V(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Nf(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=V(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=V(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=Mf();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=V(`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`}}),a=B(`span`,`persona-composer-model-picker-label`),o=B(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=V(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Rs({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),is(n,s,jf),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=V(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=U(e.icon,16,`currentColor`,1.5);if(n){let e=B(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=B(`span`,`persona-composer-model-option-body`),r=B(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=B(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=B(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=U(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=Mf();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}H(),W(),ws();function Pf(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=V(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=B(`span`,`persona-mention-chip-icon`),r=U(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=B(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=V(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=U(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),xs(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}xs(t)},destroy:()=>{r=!0,c(),xs(t)}}}const Ff=e=>`core:mode:${e}`,If=e=>Math.min(300+e,499),Lf=e=>`core:mode-group:${e}`;function Rf(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function zf(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function Bf(e,t){return e?.length?e.filter(e=>!Rf(e.groupId,t)&&!zf(e.groupId,t)):[]}const Vf=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function Hf(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(Vf(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function Uf(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function Wf(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Gf(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}H(),W();function Kf(e){let t=null;return{action:{id:Lf(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=V(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=V(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=U(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=B(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}H(),W();function qf(e){let t=V(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=B(`span`,`persona-composer-quote-bar`),i=B(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=B(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=V(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=zl(n.text),i.appendChild(a);let o=V(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=U(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}H(),W();function Jf(e){let t=V(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=V(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=U(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=zl(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=B(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=V(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}H();function Yf(e){let t=V(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=V(`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 r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=B(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=V(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Xf(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 Zf(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function Qf(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function $f(e){return e.wrapped||e.text.includes(`
|
|
195
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function ep(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function tp(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function np(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 rp(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const ip=e=>typeof e?.then==`function`;function ap(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function op(e,t,n){let r;try{r=e(np(t),{signal:n})}catch(e){return{status:`error`,error:e}}return ip(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:ap(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):ap(t,r)}const sp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),cp={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`};Ae();const lp=`16px`,up=`transparent`,dp={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:(()=>{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})(),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`}},fp={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`}},pp={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:be,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:lp,canvasBackground:up,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`}}},mp=dp.colors.gray,hp={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},gp={...dp,colors:{...dp.colors,gray:mp}},_p={...dp,colors:{...dp.colors,gray:hp},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},vp=fp,yp={...fp,colors:{...fp.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...fp.typography,fontSize:`14px`,lineHeight:`1.5`}},bp=pp,xp={...pp,launcher:cp,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:{...pp.input,borderRadius:`palette.radius.full`},introCard:{...pp.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...pp.suggestion.chip,fontWeight:`400`},card:{...pp.suggestion.card,fontWeight:`400`},list:{...pp.suggestion.list,fontWeight:`400`}},panel:{...pp.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...pp.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:{...pp.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...pp.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:{...pp.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...pp.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)`}},Sp=e=>L({future:e}),Cp=e=>Sp(e)===`v5`?{palette:_p,semantic:yp,components:xp}:{palette:gp,semantic:vp,components:bp};function wp(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?wp(e,r):r}function Tp(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=wp(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Ep(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 Dp(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Dp(t,r):r}return n}function Op(e,t){return t?Dp(e,t):e}function kp(e,t={}){let n=Cp(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:Op(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Ep(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const Ap=e=>e.trim()===`0`?`0px`:e,jp=`--persona-`,Mp=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Np=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[jp+n],t!==void 0)break;t!==void 0&&(e[jp+n]=t)}};function Pp(e){let t=Tp(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}Np(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 r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],Np(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`]]),Np(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`]}`,Np(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`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,Np(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`]]),Np(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],Np(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`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],Np(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),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 e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}Np(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,Np(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`]]),Np(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 _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),Np(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`]]),Np(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),Np(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),Np(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),Np(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`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}Np(n,[[`message-border`,`components-message-border`,`border`]]),Np(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 S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.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 T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=Ap(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=Ap(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=wp(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=Ap(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=wp(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=wp(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=wp(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=wp(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=wp(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=wp(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=wp(e,D.background)??D.background));let O=n[`--persona-surface`],k=n[`--persona-container`],A=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,j=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,ee=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,M=!k||k===O,N=Mp(O??n[`--persona-background`]),P=M&&N!==void 0&&N<.179,te=P?`rgba(255, 255, 255, 0.08)`:A,ne=P?`rgba(255, 255, 255, 0.12)`:j,re=P?`rgba(255, 255, 255, 0.16)`:ee,F=M?te:k,ie=M?ne:k;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??F,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??ie,M&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??re),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??F,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??F,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??F,n}Ae(),P();const Fp=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),Ip=(e,t)=>{if(!t||!Fp(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(qp(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:L(t)===`v5`?`400px`:`420px`}}}:e},Lp={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`}}},Rp={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)`}}}},zp=Lp,Bp={...zp,colors:{...zp.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`}}},Vp=Rp,Hp={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:{...Rp.components,button:{...Rp.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:{...Rp.components?.eventStream,badge:{...Rp.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`}}}}},Up=e=>L({future:e})===`v5`?{palette:Bp,components:Hp}:{palette:zp,components:Vp},Wp=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},Gp=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Kp=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:Gp()},qp=e=>Kp(e),Jp=(e,t={})=>kp(e,t),Yp=(e,t={})=>{let n=Up(t.future),r=M(n.components,e??{})??{};return kp({...r,palette:{...r.palette,colors:L(t)===`v5`?M(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Xp=e=>{let t=qp(e),n=Wp(e?.theme),r=M({components:{launcher:sp(e)===`circle`?cp:{...bp.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}}}},n),i=Wp(e?.darkTheme);return Ip(t===`dark`?Yp(M(r??{},i??{}),{future:e?.future}):Jp(r,{future:e?.future}),e)},Zp=e=>Pp(e),Qp=(e,t)=>{let n=Xp(t),r=Zp(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,qp(t)),e.setAttribute(`data-persona-defaults`,L(t))},$p=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(Gp())});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)`),r=()=>e(Gp());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},em=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),tm=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,nm=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},rm=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm=o((()=>{im=null,am=()=>{if(im!==null)return im;if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},om=`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`,sm=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},cm=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return sm(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(sm(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},lm=e=>om.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),um=(e,t)=>{let n=cm(e);if(!n)return``;let r=am(),i=lm(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},dm=e=>um(e,!1),fm=e=>um(e,!0),pm=(e,t)=>t.key?.toLowerCase()===e.key&&(am()?t.metaKey:t.ctrlKey)===e.mod&&!(am()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,mm=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},hm=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(pm(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!mm(n))){e.preventDefault();try{i.run(e)}catch(e){sm(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=cm(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(sm(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,fm(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}}}));gm();const _m=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;m.Idiomorph.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},vm=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),ym={index:-1,draft:``};function bm(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function xm(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 Sm(){return/* @__PURE__ */ new Map}function Cm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function wm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Tm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Em(e){return e.role!==`assistant`||e.variant===`tool`||e.variant===`reasoning`?!1:e.variant===`approval`||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Dm(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function Om(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function km(e,t){return Om(e)-e.scrollTop<=t}function Am(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function jm(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function Mm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Nm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function Pm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Fm=o((()=>{})),Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh=o((()=>{Im={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},Lm=[`pre`,`code`,`a`,`script`,`style`],Rm=e=>({type:e?.type??Im.type,placeholder:e?.placeholder??Im.placeholder,speed:e?.speed??Im.speed,duration:e?.duration??Im.duration,buffer:e?.buffer??Im.buffer}),zm=[{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`}],Bm=/* @__PURE__ */ new Map;for(let e of zm)Bm.set(e.name,e);Vm=[`wipe`,`glyph-cycle`],Hm=e=>{Bm.set(e.name,e)},Um=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Bm.get(e)??null,Wm=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
|
|
196
|
+
`);return t<0?``:e.slice(0,t)}return e},Gm=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-char`,i.id=`stream-c-${n}-${r}`,i.style.setProperty(`--char-index`,String(r)),i.textContent=t,i},Km=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-word`,i.id=`stream-w-${n}-${r}`,i.style.setProperty(`--word-index`,String(r)),i.textContent=t,i},qm=/\s/,Jm=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let e=n;if(t.has(e.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Ym=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=0;for(;s<a.length;)if(qm.test(a[s])){let e=s;for(;e<a.length&&qm.test(a[e]);)e+=1;o.appendChild(r.createTextNode(a.slice(s,e))),s=e}else{let e=r.createElement(`span`);e.className=`persona-stream-word-group`;let i=s;for(;i<a.length&&!qm.test(a[i]);)e.appendChild(Gm(r,a[i],t,n.value)),n.value+=1,i+=1;o.appendChild(e),s=i}i.replaceChild(o,e)},Xm=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=a.split(/(\s+)/);for(let e of s)e&&(/^\s+$/.test(e)?o.appendChild(r.createTextNode(e)):(o.appendChild(Km(r,e,t,n.value)),n.value+=1));i.replaceChild(o,e)},Zm=(e,t,n,r)=>{if(!e||typeof document>`u`)return e;let i=document.createElement(`div`);i.innerHTML=e;let a=new Set((r?.skipTags??Lm).map(e=>e.toLowerCase())),o=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null),s=[],c=o.nextNode();for(;c;)Jm(c,a)||s.push(c),c=o.nextNode();let l={value:r?.startIndex??0},u=t===`char`?Ym:Xm;for(let e of s)u(e,n,l);return i.innerHTML},Qm=(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},$m=(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},eh=/* @__PURE__ */ new WeakMap,th=(e,t)=>{if(!e.styles)return;let n=eh.get(t);if(n||(n=/* @__PURE__ */ new Set,eh.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,`\\$&`);if(t.querySelector(`style[data-persona-animation="${r}"]`))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)},nh=/* @__PURE__ */ new WeakMap,rh=(e,t)=>{if(!e.onAttach)return;let n=nh.get(t);if(n||(n=/* @__PURE__ */ new Map,nh.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},ih=e=>{let t=nh.get(e);if(t){for(let e of t.values())typeof e==`function`&&e();t.clear()}},ah=(e,t)=>{th(e,t),rh(e,t)}})),sh,ch,lh=o((()=>{oh(),sh=`@keyframes persona-stream-wipe {
|
|
197
197
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
198
198
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
199
199
|
}
|
|
@@ -227,7 +227,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
227
227
|
-webkit-mask-image: none !important;
|
|
228
228
|
mask-image: none !important;
|
|
229
229
|
}
|
|
230
|
-
}`,
|
|
230
|
+
}`,ch={name:`wipe`,containerClass:`persona-stream-wipe`,wrap:`word`,styles:sh},Hm(ch)})),uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh=o((()=>{oh(),uh=`[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
231
231
|
animation: persona-stream-glyph-cycle-fade
|
|
232
232
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
233
233
|
}
|
|
@@ -243,7 +243,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
243
243
|
animation: none !important;
|
|
244
244
|
opacity: 1 !important;
|
|
245
245
|
}
|
|
246
|
-
}`,th=`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@`,nh=10,rh=120,ih=120,ah=.4,oh=50,sh=e=>{if(!e)return ih;let t=(e.style.getPropertyValue(`--persona-stream-step`)?.trim()).match(/([\d.]+)\s*ms/);return t?parseFloat(t[1]):ih},ch=e=>{let t=e.closest(`.persona-stream-glyph-cycle`),n=sh(t);return rh*n/ih},lh=e=>{let t=th[Math.floor(Math.random()*41)];return e&&t===e&&(t=th[(th.indexOf(t)+1)%41]),t},uh=e=>{let t=e.closest(`.persona-stream-glyph-cycle`);if(!t)return;let n=t.querySelectorAll(`.persona-stream-char[data-glyph-cycle-final]`),r=!1;for(let t of Array.from(n))t===e?r=!0:r&&Math.random()<ah&&(t.textContent=lh())},dh=/* @__PURE__ */ new WeakMap,fh=25,ph=.5,mh=6,hh=.25,gh=/* @__PURE__ */ new WeakMap,_h=/* @__PURE__ */ new WeakMap,vh=(e,t)=>{if(!e)return fh*ph;let n=gh.get(e);gh.set(e,t);let r=_h.get(e)??fh;if(n!==void 0){let i=t-n;i>1&&(r=r*.75+i*hh,_h.set(e,r))}return Math.max(mh,r*ph)},yh=/* @__PURE__ */ new Map,bh=e=>e.closest(`[data-message-id]`)?.dataset.messageId??null,xh=e=>{e&&yh.set(e,(yh.get(e)??0)+1)},Sh=e=>{if(!e)return;let t=yh.get(e)??0;t<=1?yh.delete(e):yh.set(e,t-1)},Ch=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=lh();let n=bh(e);n&&(e.dataset.glyphCycleMessageId=n),xh(n);let r=e.closest(`.persona-stream-glyph-cycle`),i=Date.now(),a=vh(r,i),o=ch(e),s=i+nh*o;if(r){let e=dh.get(r);e!==void 0&&(s=Math.max(s,e)),dh.set(r,s+a)}wh(e,t,s)},wh=(e,t,n)=>{if(e.dataset.glyphCycleStarted===`true`)return;e.dataset.glyphCycleStarted=`true`;let r=ch(e),i=e.textContent??void 0,a=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute(`data-preserve-runtime`),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,Sh(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let o=lh(i);e.textContent=o,i=o,uh(e),setTimeout(a,r)};setTimeout(a,r)},Th=e=>{let t=e.querySelectorAll?.(`.persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])`);if(t)for(let e of Array.from(t))Ch(e)},Eh=e=>e.nodeType===1,Dh={name:`glyph-cycle`,containerClass:`persona-stream-glyph-cycle`,wrap:`char`,skipTags:[`a`,`script`,`style`],styles:eh,bufferContent(e){if(e.length<oh)return``;let t=0,n=-1,r=0;for(;r<e.length;)e[r]===`*`&&e[r+1]===`*`?(t+=1,r+=2):(/\s/.test(e[r])&&t%2==0&&(n=r),r+=1);return n<0?``:e.slice(0,n)},isAnimating(e){return(yh.get(e.id)??0)>0},onAttach(e){Th(e);let t=new MutationObserver(e=>{for(let t of e)for(let e of Array.from(t.addedNodes))Eh(e)&&(e.classList.contains(`persona-stream-char`)&&e.closest(`.persona-stream-glyph-cycle`)?Ch(e):Th(e))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}},Mm(Dh)})),kh=/* @__PURE__ */ s({glyphCycle:()=>Dh,wipe:()=>Qm}),Ah=o((()=>{$m(),Oh()}));Tm(),ve();const{setLoader:jh,load:Mh}=_e({fallbackImport:()=>Promise.resolve().then(()=>(Ah(),kh))}),Nh=Mh;Br();function Ph(e,t=Rr){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let Fh=0,Ih=null;function Lh(e=document){if(Fh++,Fh===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ih={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,Fh=Math.max(0,Fh-1),Fh===0&&Ih)){let t=e.body,n=e.defaultView??window;t.style.overflow=Ih.originalOverflow,t.style.position=Ih.originalPosition,t.style.top=Ih.originalTop,t.style.width=Ih.originalWidth,n.scrollTo(0,Ih.scrollY),Ih=null}}}ne();const Rh={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},zh=e=>(e?.launcher?.mountMode??`floating`)===`docked`,Bh=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Vh=e=>{let t=e?.launcher?.dock,n=N(e).dockWidth?t?.width:mp(Bp(e),`components.panel.width`);return{side:t?.side??Rh.side,width:n??Rh.width,animate:t?.animate??Rh.animate,reveal:t?.reveal??Rh.reveal,maxHeight:t?.maxHeight??Rh.maxHeight}};H(),ze(),g();const Hh=e=>e===`followUp`?`follow-up`:e,Uh=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Wh=/* @__PURE__ */ new WeakSet,Gh=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Kh=e=>{Gh()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},qh=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:s,plugins:c,chipsConfig:l,session:d,getTextarea:f,eventTarget:p,submitPrompt:m}=e,g=r===`followUp`,_=t.behavior,v=()=>{if(d.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:_},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(g&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of c)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:s})===!1)return;let o=f();_===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,d.sendMessage(t.prompt))},y=()=>{let e=z(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=_,a===`chip`&&(l?.fontWeight&&(e.style.fontWeight=l.fontWeight),l?.paddingX&&(e.style.paddingLeft=l.paddingX,e.style.paddingRight=l.paddingX),l?.paddingY&&(e.style.paddingTop=l.paddingY,e.style.paddingBottom=l.paddingY)),t.icon){let n=U(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=z(`span`,`persona-suggestion__copy`);if(n.appendChild(B(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(B(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=h(u.ArrowRight,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,v),e},b=null;for(let e of c)if(e.renderSuggestion&&(b=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:s,defaultRenderer:y,select:v}),b))break;return b??=y(),b.dataset.suggestionId||=t.id,b.dataset.behavior||=_,b.dataset.emphasis||=t.emphasis,b instanceof HTMLButtonElement||b.setAttribute(`aria-disabled`,o?`true`:`false`),b},Jh=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Wh.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Wh.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(Uh).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Hh(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=qh({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,Kh(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Yh={"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`};H(),ze(),Io();const Xh={x:[1.4,1.05]},Zh=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,Qh=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Xh[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=U(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},$h=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Zh,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=z(`div`,o),b=!!(d||f),x=B(`button`,{className:V(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||ng.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?Qh(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),yo({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},eg=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Zh,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=$h({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},tg=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=$h({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}};H(),ze(),he();const ng={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)`},rg={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)`},ig={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)`},ag=e=>{let{config:t,showClose:n=!0}=e,r=B(`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:ng.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)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=B(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=U(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=z(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=z(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=B(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:ng.titleColor,...rg}}),f=B(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:ng.subtitleColor,...ig}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=tg(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=eg(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`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`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},og=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};function sg(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=z(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(zr)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=U(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}var cg=o((()=>{H(),ze(),Br()}));function lg(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=z(`button`,V(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=U(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function ug(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=z(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=U(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=z(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function dg(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=z(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=lg({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=z(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function fg(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=z(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?lg({...g,icon:n,size:r??14}):ug({...g,icon:n,iconSize:r??14}),v=lg({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=sg({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function pg(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=z(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=z(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=U(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=sg({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var mg=o((()=>{H(),ze(),cg()}));H(),cg(),mg();const hg=e=>{let t=ag({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function gg(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=$h({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?tm(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=nm(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=sg({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const _g={default:hg,minimal:e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=z(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=ng.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=pg({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=ng.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=z(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=z(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=ng.titleColor,Object.assign(u.style,rg),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=eg(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=z(`div`,`persona-flex persona-items-center persona-gap-1`);c||gg(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=tg(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=z(`div`);v.style.display=`none`;let y=z(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}}},vg=e=>_g[e]??_g.default,yg=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=z(`div`);i.style.display=`none`;let a=z(`span`),o=z(`span`),s=z(`button`);s.style.display=`none`;let c=z(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=vg(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};H(),is();const bg=e=>{let{config:t}=e,n=B(`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`}}),r=rs(),i=B(`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:a,attachAutoResize:o}=Zo(t);o();let s=$o(t),c=es(t),l=ts(t),u=ns(t),d=B(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=B(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=B(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=B(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};H(),g(),is(),qo();const xg=()=>{let e=B(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=z(`span`,`persona-pill-peek__icon`),n=h(u.MessageSquare,16,`currentColor`,1.5);n&&t.appendChild(n);let r=z(`span`,`persona-pill-peek__text`),i=z(`span`,`persona-pill-peek__caret`),a=h(u.ChevronUp,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},Sg=e=>{let{config:t}=e,n=B(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=rs(),i=ns(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=Zo(t,{defaultMaxLines:5});o();let s=$o(t),c=es(t),l=ts(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=B(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=B(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=B(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=B(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};H(),Yc(),mg(),ze(),La(),Xm();const Cg=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}},wg=(e,t)=>{if(!e)return null;let n=Cg(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},Tg=(e,t)=>{let n=z(`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},Eg=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},Dg=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(`:`))},Og=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),kg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),Ag=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),jg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),Mg=e=>{if(!e||e.length===0)return null;let t=B(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=B(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=z(`span`,`persona-mention-chip-icon`),i=U(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(B(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Ng=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Jc(r.ref,{readonly:!0,render:t}));return n},Pg=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Ng(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Jc(i.ref,{readonly:!0,render:r}),a),n=a}}},Fg=(e,t,n)=>{if(e.length===0)return null;try{let r=z(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=z(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),Eg(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},Ig=e=>{if(e.length===0)return null;try{let t=z(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!Dg(e.audio))return;let r=z(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Lg=e=>{if(e.length===0)return null;try{let t=z(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!Dg(e.video))return;let r=z(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,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}},Rg=e=>{if(e.length===0)return null;try{let t=z(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!Dg(e.data))return;let r=z(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.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}},zg=()=>{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 r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},Bg=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:zg};if(t){let e=t(r);if(e!==null)return e}return zg()},Vg=(e,t)=>{let n=z(`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`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=z(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,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},Hg=(e,t,n=`div`)=>{let r=z(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},Ug=(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`)}return n},Wg={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`}},Gg=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=Wg[n??`bubble`]??Wg.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},Kg=e=>`custom:${e}`,qg=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),Jg=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=qg(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=z(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=z(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=lg({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,Kg(e.id)));return _},Yg=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=Ug(e.role,s),h=z(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=pp(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;Gg(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=Og(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Om(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Nm(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?Pm(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?Vm(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?Vm(n,`word`,e.id,{skipTags:C.skipTags}):n},k=null;if(b?(k=document.createElement(`div`),k.innerHTML=O(),k.style.display=`none`,E.appendChild(k)):e.contentSegments?.length?Pg(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=Hm(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=Hg(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=Fg(v,!b&&!!y,()=>{b&&k&&(k.style.display=``)});e?h.appendChild(e):b&&k&&(k.style.display=``)}let A=kg(e);if(A.length>0){let e=Ig(A);e&&h.appendChild(e)}let j=Ag(e);if(j.length>0){let e=Lg(j);e&&h.appendChild(e)}let M=jg(e);if(M.length>0){let e=Rg(M);e&&h.appendChild(e)}let ee=e.contentSegments?.length?null:Mg(e.contextMentions);if(ee&&h.appendChild(ee),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=Hg(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let N=e.role===`assistant`?wg(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(Um());else if(t)h.appendChild(Um());else{let e=Bg(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}N&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(Tg(e.stopReason,N)));let P=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,F=a?.actionEligibility,te=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&F?.canEdit===!0||r?.showQuote===!0&&F?.canQuote===!0||qg(r,`user`).length>0);if((P||te)&&r){let t=Jg(e,te?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,F);h.appendChild(t)}if(!u||e.role===`system`)return h;let ne=z(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),I=Vg(c,e.role);return f===`right`||f===`left`&&e.role===`user`?ne.append(h,I):ne.append(I,h),ne};H(),ze();const Xg=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=U(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(B(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(B(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Zg=(e,t,n={})=>{let r=B(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=z(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=z(`h2`,`persona-welcome-title`),o=z(`p`,`persona-welcome-subtitle`),s=B(`div`,{className:`persona-welcome-head-text`},i,a),c=B(`div`,{className:`persona-welcome-title-row`},r,s);return{host:B(`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,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},Qg=(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)},$g=(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===``,Xg(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`)},e_=`data-persona-welcome-overlay`,t_=`persona-welcome-overlay-active`,n_=/* @__PURE__ */ new WeakMap,r_=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(e_,``),e.classList.contains(t_)||(n_.set(e,e.scrollTop),e.classList.add(t_),e.scrollTop=0)},i_=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(e_),e.classList.contains(t_)&&(e.classList.remove(t_),e.scrollTop=n_.get(e)??e.scrollTop,n_.delete(e))},a_=()=>{let e=B(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},o_=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=B(`div`,{className:Ug(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`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(B(`div`,{className:`persona-flex`},i)),e.hidden=!1},s_=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,c_=(e,t)=>{if(s_()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},l_=(e,t,n,r=260)=>{if(t<=1||s_()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},u_=/* @__PURE__ */ new WeakSet,d_=(e,t)=>!!e&&e[t]!==void 0,f_=(e,t)=>{e&&e.debug===!0&&t.length&&(u_.has(e)||(u_.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},p_=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=d_(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:d_(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];d_(n,`title`)&&d_(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),d_(n,`subtitle`)&&d_(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),d_(n,`variant`)&&d_(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&d_(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&d_(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=Kp(n?.anchorComposerTop)!==null;return d_(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(d_(n,`anchorComposerTop`)||d_(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),f_(e,c),{title:d_(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:d_(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},m_=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,h_=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`);H(),Br(),ne();const g_=`var(--persona-components-panel-height)`,__=e=>{let t=N(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${g_})`:`max(200px, calc(${g_} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},v_=`16px`,y_=`10px`,b_=`14px`,x_=e=>{let t=e?.launcher?.enabled??!0,n=zh(e);if(Bh(e)){let t=e?.launcher?.composerBar??{},n=z(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=z(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=z(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=z(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=z(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=z(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=z(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=N(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?__(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&Yh[r.position]?Yh[r.position]:Yh[`bottom-right`],a=z(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=z(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=__(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},S_=e=>{let t=B(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Hh(e)}});return t.hidden=!0,t},C_=(e,t)=>{let n=S_(`starter`),r=Zg(e,n,{flatShadow:zh(e)}),i=p_(e);$g(r,i),Qg(t,r.host,h_(i,e?.initialMessages));let a=a_();return o_(a,i.message,e),{welcome:r,greetingHost:a}},w_=(e,t)=>{let n=z(`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:r,wrapper:i}=eg(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:v_,iconSize:y_});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=tg(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:v_,iconSize:b_});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=B(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=B(`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`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=C_(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=z(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=S_(`followUp`),v=Wp(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=B(`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`}}),b=Sg({config:e}),{root:x,textNode:S}=xg();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:z(`span`),headerTitle:z(`span`),headerSubtitle:z(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},T_=(e,t=!0)=>{if(Bh(e))return w_(e,t);let n=B(`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`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?yg(e,r,{showClose:t}):ag({config:e,showClose:t}),o=B(`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`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=C_(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=z(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=S_(`followUp`),h=Wp(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=bg({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),og(n,a,e),n.append(o);let v=B(`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 _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};H(),ze(),Br();const E_=(e,t)=>{let n=z(`button`);n.type=`button`,n.innerHTML=`
|
|
246
|
+
}`,dh=`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@`,fh=10,ph=120,mh=120,hh=.4,gh=50,_h=e=>{if(!e)return mh;let t=(e.style.getPropertyValue(`--persona-stream-step`)?.trim()).match(/([\d.]+)\s*ms/);return t?parseFloat(t[1]):mh},vh=e=>{let t=e.closest(`.persona-stream-glyph-cycle`),n=_h(t);return ph*n/mh},yh=e=>{let t=dh[Math.floor(Math.random()*41)];return e&&t===e&&(t=dh[(dh.indexOf(t)+1)%41]),t},bh=e=>{let t=e.closest(`.persona-stream-glyph-cycle`);if(!t)return;let n=t.querySelectorAll(`.persona-stream-char[data-glyph-cycle-final]`),r=!1;for(let t of Array.from(n))t===e?r=!0:r&&Math.random()<hh&&(t.textContent=yh())},xh=/* @__PURE__ */ new WeakMap,Sh=25,Ch=.5,wh=6,Th=.25,Eh=/* @__PURE__ */ new WeakMap,Dh=/* @__PURE__ */ new WeakMap,Oh=(e,t)=>{if(!e)return Sh*Ch;let n=Eh.get(e);Eh.set(e,t);let r=Dh.get(e)??Sh;if(n!==void 0){let i=t-n;i>1&&(r=r*.75+i*Th,Dh.set(e,r))}return Math.max(wh,r*Ch)},kh=/* @__PURE__ */ new Map,Ah=e=>e.closest(`[data-message-id]`)?.dataset.messageId??null,jh=e=>{e&&kh.set(e,(kh.get(e)??0)+1)},Mh=e=>{if(!e)return;let t=kh.get(e)??0;t<=1?kh.delete(e):kh.set(e,t-1)},Nh=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=yh();let n=Ah(e);n&&(e.dataset.glyphCycleMessageId=n),jh(n);let r=e.closest(`.persona-stream-glyph-cycle`),i=Date.now(),a=Oh(r,i),o=vh(e),s=i+fh*o;if(r){let e=xh.get(r);e!==void 0&&(s=Math.max(s,e)),xh.set(r,s+a)}Ph(e,t,s)},Ph=(e,t,n)=>{if(e.dataset.glyphCycleStarted===`true`)return;e.dataset.glyphCycleStarted=`true`;let r=vh(e),i=e.textContent??void 0,a=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute(`data-preserve-runtime`),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,Mh(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let o=yh(i);e.textContent=o,i=o,bh(e),setTimeout(a,r)};setTimeout(a,r)},Fh=e=>{let t=e.querySelectorAll?.(`.persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])`);if(t)for(let e of Array.from(t))Nh(e)},Ih=e=>e.nodeType===1,Lh={name:`glyph-cycle`,containerClass:`persona-stream-glyph-cycle`,wrap:`char`,skipTags:[`a`,`script`,`style`],styles:uh,bufferContent(e){if(e.length<gh)return``;let t=0,n=-1,r=0;for(;r<e.length;)e[r]===`*`&&e[r+1]===`*`?(t+=1,r+=2):(/\s/.test(e[r])&&t%2==0&&(n=r),r+=1);return n<0?``:e.slice(0,n)},isAnimating(e){return(kh.get(e.id)??0)>0},onAttach(e){Fh(e);let t=new MutationObserver(e=>{for(let t of e)for(let e of Array.from(t.addedNodes))Ih(e)&&(e.classList.contains(`persona-stream-char`)&&e.closest(`.persona-stream-glyph-cycle`)?Nh(e):Fh(e))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}},Hm(Lh)})),zh=/* @__PURE__ */ s({glyphCycle:()=>Lh,wipe:()=>ch}),Bh=o((()=>{lh(),Rh()}));Fm(),Pe();const{setLoader:Vh,load:Hh}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Bh(),zh))}),Uh=Hh;Wr();function Wh(e,t=Hr){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let Gh=0,Kh=null;function qh(e=document){if(Gh++,Gh===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Kh={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,Gh=Math.max(0,Gh-1),Gh===0&&Kh)){let t=e.body,n=e.defaultView??window;t.style.overflow=Kh.originalOverflow,t.style.position=Kh.originalPosition,t.style.top=Kh.originalTop,t.style.width=Kh.originalWidth,n.scrollTo(0,Kh.scrollY),Kh=null}}}_e();const Jh={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},Yh=e=>(e?.launcher?.mountMode??`floating`)===`docked`,Xh=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Zh=e=>{let t=e?.launcher?.dock,n=pe(e).dockWidth?t?.width:wp(Xp(e),`components.panel.width`);return{side:t?.side??Jh.side,width:n??Jh.width,animate:t?.animate??Jh.animate,reveal:t?.reveal??Jh.reveal,maxHeight:t?.maxHeight??Jh.maxHeight}};H(),W(),ee();const Qh=e=>e===`followUp`?`follow-up`:e,$h=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},eg=/* @__PURE__ */ new WeakSet,tg=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,ng=e=>{tg()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},rg=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:s,plugins:c,chipsConfig:l,session:d,getTextarea:f,eventTarget:p,submitPrompt:m}=e,h=r===`followUp`,g=t.behavior,_=()=>{if(d.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:g},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of c)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:s})===!1)return;let o=f();g===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,d.sendMessage(t.prompt))},v=()=>{let e=B(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=g,a===`chip`&&(l?.fontWeight&&(e.style.fontWeight=l.fontWeight),l?.paddingX&&(e.style.paddingLeft=l.paddingX,e.style.paddingRight=l.paddingX),l?.paddingY&&(e.style.paddingTop=l.paddingY,e.style.paddingBottom=l.paddingY)),t.icon){let n=U(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=B(`span`,`persona-suggestion__copy`);if(n.appendChild(V(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(V(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=j(u.ArrowRight,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,_),e},y=null;for(let e of c)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:s,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,o?`true`:`false`),y},ig=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!eg.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(eg.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map($h).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Qh(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=rg({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,ng(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},ag={"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`};H(),W(),Wo();const og={x:[1.4,1.05]},sg=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,cg=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=og[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=U(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},lg=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=sg,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=B(`div`,o),b=!!(d||f),x=V(`button`,{className:Me(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||fg.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?cg(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),Do({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},ug=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=sg,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=lg({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},dg=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=lg({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}};H(),W(),Ae();const fg={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)`},pg={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)`},mg={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)`},hg=e=>{let{config:t,showClose:n=!0}=e,r=V(`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:fg.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)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=V(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=U(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=B(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=B(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=V(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:fg.titleColor,...pg}}),f=V(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:fg.subtitleColor,...mg}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=dg(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=ug(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`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`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},gg=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};function _g(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=B(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(Ur)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=U(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}var vg=o((()=>{H(),W(),Wr()}));function yg(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=B(`button`,Me(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=U(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function bg(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=B(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=U(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=B(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function xg(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=B(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=yg({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=B(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function Sg(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=B(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?yg({...g,icon:n,size:r??14}):bg({...g,icon:n,iconSize:r??14}),v=yg({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=_g({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function Cg(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=B(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=B(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=U(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=_g({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var wg=o((()=>{H(),W(),vg()}));H(),vg(),wg();const Tg=e=>{let t=hg({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function Eg(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=lg({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?dm(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=fm(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=_g({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const Dg={default:Tg,minimal:e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=B(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=fg.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=Cg({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=fg.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=B(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=B(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=fg.titleColor,Object.assign(u.style,pg),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=ug(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=B(`div`,`persona-flex persona-items-center persona-gap-1`);c||Eg(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=dg(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=B(`div`);v.style.display=`none`;let y=B(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}}},Og=e=>Dg[e]??Dg.default,kg=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=B(`div`);i.style.display=`none`;let a=B(`span`),o=B(`span`),s=B(`button`);s.style.display=`none`;let c=B(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=Og(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};H(),fs();const Ag=e=>{let{config:t}=e,n=V(`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`}}),r=ds(),i=V(`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:a,attachAutoResize:o}=as(t);o();let s=ss(t),c=cs(t),l=ls(t),u=us(t),d=V(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=V(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=V(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=V(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};H(),ee(),fs(),ts();const jg=()=>{let e=V(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=B(`span`,`persona-pill-peek__icon`),n=j(u.MessageSquare,16,`currentColor`,1.5);n&&t.appendChild(n);let r=B(`span`,`persona-pill-peek__text`),i=B(`span`,`persona-pill-peek__caret`),a=j(u.ChevronUp,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},Mg=e=>{let{config:t}=e,n=V(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=ds(),i=us(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=as(t,{defaultMaxLines:5});o();let s=ss(t),c=cs(t),l=ls(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=V(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=V(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=V(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=V(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};H(),rl(),wg(),W(),Ha(),oh();const Ng=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}},Pg=(e,t)=>{if(!e)return null;let n=Ng(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},Fg=(e,t)=>{let n=B(`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},Ig=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},Lg=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(`:`))},Rg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),zg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),Bg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),Vg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),Hg=e=>{if(!e||e.length===0)return null;let t=V(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=V(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=B(`span`,`persona-mention-chip-icon`),i=U(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(V(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Ug=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(nl(r.ref,{readonly:!0,render:t}));return n},Wg=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Ug(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(nl(i.ref,{readonly:!0,render:r}),a),n=a}}},Gg=(e,t,n)=>{if(e.length===0)return null;try{let r=B(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=B(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),Ig(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},Kg=e=>{if(e.length===0)return null;try{let t=B(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!Lg(e.audio))return;let r=B(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},qg=e=>{if(e.length===0)return null;try{let t=B(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!Lg(e.video))return;let r=B(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,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}},Jg=e=>{if(e.length===0)return null;try{let t=B(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!Lg(e.data))return;let r=B(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.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}},Yg=()=>{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 r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},Xg=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:Yg};if(t){let e=t(r);if(e!==null)return e}return Yg()},Zg=(e,t)=>{let n=B(`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`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=B(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,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},Qg=(e,t,n=`div`)=>{let r=B(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},$g=(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`)}return n},e_={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`}},t_=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=e_[n??`bubble`]??e_.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},n_=e=>`custom:${e}`,r_=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),i_=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=r_(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=B(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=B(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=yg({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,n_(e.id)));return _},a_=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=$g(e.role,s),h=B(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Cp(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;t_(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=Rg(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Rm(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Um(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?Wm(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?Zm(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?Zm(n,`word`,e.id,{skipTags:C.skipTags}):n},k=null;if(b?(k=document.createElement(`div`),k.innerHTML=O(),k.style.display=`none`,E.appendChild(k)):e.contentSegments?.length?Wg(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=Qm(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=Qg(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=Gg(v,!b&&!!y,()=>{b&&k&&(k.style.display=``)});e?h.appendChild(e):b&&k&&(k.style.display=``)}let A=zg(e);if(A.length>0){let e=Kg(A);e&&h.appendChild(e)}let j=Bg(e);if(j.length>0){let e=qg(j);e&&h.appendChild(e)}let ee=Vg(e);if(ee.length>0){let e=Jg(ee);e&&h.appendChild(e)}let M=e.contentSegments?.length?null:Hg(e.contextMentions);if(M&&h.appendChild(M),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=Qg(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let N=e.role===`assistant`?Pg(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild($m());else if(t)h.appendChild($m());else{let e=Xg(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}N&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(Fg(e.stopReason,N)));let P=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,te=a?.actionEligibility,ne=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&te?.canEdit===!0||r?.showQuote===!0&&te?.canQuote===!0||r_(r,`user`).length>0);if((P||ne)&&r){let t=i_(e,ne?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,te);h.appendChild(t)}if(!u||e.role===`system`)return h;let re=B(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),F=Zg(c,e.role);return f===`right`||f===`left`&&e.role===`user`?re.append(h,F):re.append(F,h),re};H(),W();const o_=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=U(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(V(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(V(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},s_=(e,t,n={})=>{let r=V(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=B(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=B(`h2`,`persona-welcome-title`),o=B(`p`,`persona-welcome-subtitle`),s=V(`div`,{className:`persona-welcome-head-text`},i,a),c=V(`div`,{className:`persona-welcome-title-row`},r,s);return{host:V(`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,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},c_=(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)},l_=(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===``,o_(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`)},u_=`data-persona-welcome-overlay`,d_=`persona-welcome-overlay-active`,f_=/* @__PURE__ */ new WeakMap,p_=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(u_,``),e.classList.contains(d_)||(f_.set(e,e.scrollTop),e.classList.add(d_),e.scrollTop=0)},m_=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(u_),e.classList.contains(d_)&&(e.classList.remove(d_),e.scrollTop=f_.get(e)??e.scrollTop,f_.delete(e))},h_=()=>{let e=V(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},g_=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=V(`div`,{className:$g(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`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(V(`div`,{className:`persona-flex`},i)),e.hidden=!1},__=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,v_=(e,t)=>{if(__()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},y_=(e,t,n,r=260)=>{if(t<=1||__()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},b_=/* @__PURE__ */ new WeakSet,x_=(e,t)=>!!e&&e[t]!==void 0,S_=(e,t)=>{e&&e.debug===!0&&t.length&&(b_.has(e)||(b_.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},C_=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=x_(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:x_(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];x_(n,`title`)&&x_(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),x_(n,`subtitle`)&&x_(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),x_(n,`variant`)&&x_(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&x_(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&x_(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=nm(n?.anchorComposerTop)!==null;return x_(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(x_(n,`anchorComposerTop`)||x_(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),S_(e,c),{title:x_(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:x_(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},w_=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,T_=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`);H(),Wr(),_e();const E_=`var(--persona-components-panel-height)`,D_=e=>{let t=pe(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${E_})`:`max(200px, calc(${E_} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},O_=`16px`,k_=`10px`,A_=`14px`,j_=e=>{let t=e?.launcher?.enabled??!0,n=Yh(e);if(Xh(e)){let t=e?.launcher?.composerBar??{},n=B(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=B(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=B(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=B(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=B(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=B(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=B(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=pe(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?D_(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&ag[r.position]?ag[r.position]:ag[`bottom-right`],a=B(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=B(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=D_(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},M_=e=>{let t=V(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Qh(e)}});return t.hidden=!0,t},N_=(e,t)=>{let n=M_(`starter`),r=s_(e,n,{flatShadow:Yh(e)}),i=C_(e);l_(r,i),c_(t,r.host,T_(i,e?.initialMessages));let a=h_();return g_(a,i.message,e),{welcome:r,greetingHost:a}},P_=(e,t)=>{let n=B(`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:r,wrapper:i}=ug(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:O_,iconSize:k_});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=dg(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:O_,iconSize:A_});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=V(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=V(`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`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=N_(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=B(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=M_(`followUp`),v=em(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=V(`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`}}),b=Mg({config:e}),{root:x,textNode:S}=jg();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:B(`span`),headerTitle:B(`span`),headerSubtitle:B(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},F_=(e,t=!0)=>{if(Xh(e))return P_(e,t);let n=V(`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`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?kg(e,r,{showClose:t}):hg({config:e,showClose:t}),o=V(`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`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=N_(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=B(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=M_(`followUp`),h=em(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=Ag({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),gg(n,a,e),n.append(o);let v=V(`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 _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};H(),W(),Wr();const I_=(e,t)=>{let n=B(`button`);n.type=`button`,n.innerHTML=`
|
|
247
247
|
<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">💬</span>
|
|
248
248
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
249
249
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -251,17 +251,17 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
251
251
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
252
252
|
</span>
|
|
253
253
|
<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">↗</span>
|
|
254
|
-
`,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=
|
|
255
|
-
`):``},
|
|
256
|
-
`).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:i.codeBlockTextColor??i.contentTextColor}}),c=
|
|
257
|
-
`);let i=
|
|
258
|
-
`):``},Z_=(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)`},Q_=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??L.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:X_(e,r?.previewMaxLines??L.previewMaxLines),o=n?Xe(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:ln(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,c=t?.toolCall??{},l=o;return i===`tool-name`?l=n.name?.trim()||o:i===`tool-preview`&&a&&(l=a),s&&c.activeTextTemplate?l=pn(n,c.activeTextTemplate,l):!s&&c.completeTextTemplate&&(l=pn(n,c.completeTextTemplate,l)),n.success===!1?l+=` · Failed`:n.superseded&&(l+=` · Approved, ran again below`),{summary:l,previewText:a,isActive:s}},$_=(e,t,n,r)=>{Je(e,t,{stateSet:n,previewKind:`tool`,iconColor:Y_(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},ev=(e,t,n=/* @__PURE__ */ new Set)=>{t=Ye(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=He(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return Qe(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??L.expandable,c=s&&n.has(e.id),{summary:l,previewText:u,isActive:d}=Q_(e,t),f=Ue({expandable:s,expanded:c,bubbleType:`tool`});i.headerBackgroundColor&&(f.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(f.style.paddingLeft=i.headerPaddingX,f.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(f.style.paddingTop=i.headerPaddingY,f.style.paddingBottom=i.headerPaddingY);let p=z(`div`,`persona-flex persona-flex-col persona-text-left`),m=z(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(m.style.color=i.headerTextColor);let h=String(r.startedAt??Date.now()),g=()=>{let e=z(`span`,``);return e.setAttribute(`data-tool-elapsed`,h),e.textContent=dn(r),e},_=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:l,previewText:u,collapsedMode:o.collapsedMode??L.collapsedMode,isActive:d,config:t??{},elapsed:dn(r),createElapsedElement:g});typeof _==`string`&&_.trim()?(m.textContent=_,p.appendChild(m)):_ instanceof HTMLElement?p.appendChild(_):(m.textContent=l,p.appendChild(m));let v=o.loadingAnimation??L.loadingAnimation,y=i.activeTextTemplate,b=i.completeTextTemplate,x=d?y:b,S=_ instanceof HTMLElement,C=(e,t)=>{m.textContent=``;let n=r.name?.trim()||`tool`,i=mn(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=z(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return m.appendChild(t),t})():m;if(e.isDuration&&d)n.appendChild(g());else{let i=e.isDuration?dn(r):e.text;t?a=z_(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!S){if(d&&v!==`none`){let e=i.loadingAnimationDuration??2e3;if(m.setAttribute(`data-preserve-animation`,`true`),v===`pulse`)m.classList.add(`persona-tool-loading-pulse`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${v}`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),v===`shimmer-color`&&(i.loadingAnimationColor&&m.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&m.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||l;m.textContent=``,z_(m,e,0)}}else x&&C(x,!1)}let w=Y_(i,Xe(t,`tool`)===`row`),T=Ge(f,p,{expandable:s,expanded:c,iconColor:w,metaGap:!0}),E=Ke({bubble:a,previewKind:`tool`,expanded:c,isActive:d,previewText:u,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:u,isActive:d,config:t??{}})});if(!s)return a.append(f,E),Qe(a,e,t,`tool`);let D=z(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(D.style.display=c?``:`none`,i.contentBackgroundColor&&(D.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(D.style.color=i.contentTextColor),i.contentPaddingX&&(D.style.paddingLeft=i.contentPaddingX,D.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(D.style.paddingTop=i.contentPaddingY,D.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)K_(D,e,t);else{if(r.name){let e=z(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,D.appendChild(e)}if(r.args!==void 0){let e=z(`div`,`persona-space-y-1`),t=z(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=z(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Z_(n,i),n.textContent=rn(r.args),e.append(t,n),D.appendChild(e)}if(r.chunks&&r.chunks.length){let e=z(`div`,`persona-space-y-1`),t=z(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=z(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Z_(n,i),n.textContent=r.chunks.join(``),e.append(t,n),D.appendChild(e)}if(r.success===!1&&D.appendChild(B(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=z(`div`,`persona-space-y-1`),t=z(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=z(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Z_(n,i),n.textContent=rn(r.result),e.append(t,n),D.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=z(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,D.appendChild(e)}}return qe({expanded:c,header:f,toggleIcon:T,content:D,collapsedPreview:E,iconColor:w}),a.append(f,E,D),Qe(a,e,t,`tool`)};var tv,nv,rv,iv=o((()=>{tv=()=>void 0,nv=e=>{tv=e.webMcpToolTitle},rv=e=>tv(e)})),av,ov,sv,cv,lv,uv,dv=o((()=>{H(),Sn(),iv(),g(),Jt(),av=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(Bt.length):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},ov=e=>e?.approval===!1?void 0:e?.approval,sv=(e,t,n)=>{let r=ov(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},cv=(e,t,n)=>{let r=ov(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=h(t?u.ChevronUp:u.ChevronDown,14,`currentColor`,2);e&&a.appendChild(e)}},lv=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=sv(e,r,n);cv(i,o,n),a.style.display=o?``:`none`},uv=(e,t,n=/* @__PURE__ */ new Map)=>{let r=e.approval,i=t?.approval===!1?void 0:t?.approval,a=r?.status===`pending`,o=z(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(o.id=`bubble-${e.id}`,o.setAttribute(`data-message-id`,e.id),o.style.backgroundColor=i?.backgroundColor??`var(--persona-approval-bg)`,o.style.borderColor=i?.borderColor??`var(--persona-approval-border)`,o.style.boxShadow=i?.shadow===void 0?`var(--persona-approval-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return o;let s=z(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),c=z(`div`,`persona-flex-shrink-0 persona-mt-0.5`);c.setAttribute(`data-approval-icon`,`true`);let l=r.status===`denied`?u.ShieldX:r.status===`timeout`?u.ShieldAlert:u.ShieldCheck,d=r.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:r.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:r.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:i?.titleColor??`currentColor`,f=h(l,20,d,2);f&&c.appendChild(f);let p=z(`div`,`persona-flex-1 persona-min-w-0`),m=z(`div`,`persona-flex persona-items-center persona-gap-2`),g=z(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(i?.titleColor&&(g.style.color=i.titleColor),g.textContent=i?.title??`Approval Required`,m.appendChild(g),!a){let e=z(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,r.status),r.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):r.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):r.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=`Timeout`),m.appendChild(e)}p.appendChild(m);let _=r.toolType===`webmcp`||r.toolName.startsWith(`webmcp:`)?rv(r.toolName):void 0,v=i?.formatDescription?.({toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,..._?{displayTitle:_}:{},...r.reason?{reason:r.reason}:{}}),y=!r.toolName,b=v||(y?r.description:`The assistant wants to use “${_??av(r.toolName)}”.`),x=z(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(x.setAttribute(`data-approval-summary`,`true`),i?.descriptionColor&&(x.style.color=i.descriptionColor),x.textContent=b,p.appendChild(x),r.reason){let e=z(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),i?.reasonColor?e.style.color=i.reasonColor:i?.descriptionColor&&(e.style.color=i.descriptionColor);let t=z(`span`,`persona-font-medium`);t.textContent=`${i?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(r.reason)),p.appendChild(e)}let S=i?.detailsDisplay??`collapsed`,C=!!r.description&&!y,w=C||!!r.parameters;if(S!==`hidden`&&w){let a=sv(e.id,n,t),o=z(`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`);o.type=`button`,o.setAttribute(`data-expand-header`,`true`),o.setAttribute(`data-bubble-type`,`approval`),i?.descriptionColor&&(o.style.color=i.descriptionColor);let s=z(`span`);s.setAttribute(`data-approval-details-label`,`true`);let c=z(`span`,`persona-inline-flex persona-items-center`);c.setAttribute(`data-approval-details-chevron`,`true`),o.append(s,c),cv(o,a,t),p.appendChild(o);let l=z(`div`);if(l.setAttribute(`data-approval-details`,`true`),l.style.display=a?``:`none`,C){let e=z(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);i?.descriptionColor&&(e.style.color=i.descriptionColor),e.textContent=r.description,l.appendChild(e)}if(r.parameters){let e=z(`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`);i?.parameterBackgroundColor&&(e.style.backgroundColor=i.parameterBackgroundColor),i?.parameterTextColor&&(e.style.color=i.parameterTextColor),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=rn(r.parameters),l.appendChild(e)}p.appendChild(l)}if(a){let e=z(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let t=z(`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`);t.type=`button`,t.style.backgroundColor=i?.approveButtonColor??`var(--persona-approval-approve-bg)`,t.style.color=i?.approveButtonTextColor??`var(--persona-button-primary-fg)`,t.setAttribute(`data-approval-action`,`approve`);let n=h(u.ShieldCheck,14,i?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);n&&(n.style.marginRight=`4px`,t.appendChild(n));let r=document.createTextNode(i?.approveLabel??`Approve`);t.appendChild(r);let a=z(`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`);a.type=`button`,a.style.backgroundColor=i?.denyButtonColor??`transparent`,a.style.color=i?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,a.style.border=`1px solid ${i?.denyButtonTextColor?i.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,a.setAttribute(`data-approval-action`,`deny`);let o=h(u.ShieldX,14,i?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);o&&(o.style.marginRight=`4px`,a.appendChild(o));let s=document.createTextNode(i?.denyLabel??`Deny`);a.appendChild(s),e.append(t,a),p.appendChild(e)}return s.append(c,p),o.appendChild(s),o}})),fv,pv,mv,hv,gv,_v,vv,yv,bv,xv,Sv=o((()=>{H(),iv(),g(),Sn(),Jt(),Ps(),dv(),fv=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),pv=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},mv=(e,t)=>{pv(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)},hv=e=>e?.approval===!1?void 0:e?.approval,gv=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},_v=e=>{let t=z(`span`,`persona-approval-kbd`);return t.textContent=e,t},vv=(e,t)=>{let n=z(`span`,`persona-approval-title`);t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?rv(e.toolName):void 0,i=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(i)return n.textContent=i,n;let a=r??av(e.toolName),o=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;n.append(`The assistant wants to use `);let s=document.createElement(`strong`);if(s.textContent=a,n.appendChild(s),o){n.append(` from `);let e=document.createElement(`strong`);e.textContent=o,n.appendChild(e)}return n},yv=e=>{let t=z(`div`,`persona-approval-resolved`),n=h(u.Ban,15,`currentColor`,2);n&&t.appendChild(n);let r=z(`span`,`persona-approval-resolved-name`);return r.textContent=e.toolName?av(e.toolName):`Tool`,t.append(r,document.createTextNode(e.status===`timeout`?` timed out`:` denied`)),t},bv=(e,t,n,r,i,a,o,s,c=!1)=>{let l=z(`div`,`persona-approval-card persona-shadow-sm`);l.id=`bubble-${n.id}`,l.setAttribute(`data-message-id`,n.id),l.setAttribute(`data-bubble-type`,`approval`),i?.backgroundColor&&(l.style.background=i.backgroundColor),i?.borderColor&&(l.style.borderColor=i.borderColor),i?.shadow!==void 0&&(l.style.boxShadow=i.shadow.trim()===``?`none`:i.shadow);let d=i?.detailsDisplay??`collapsed`,f=!!r.description&&d!==`hidden`,p=r.parameters!=null&&d!==`hidden`&&!c,m=f||p,g=m&&gv(n.id,t,i),_=i?.showDetailsLabel??`Show details`,v=i?.hideDetailsLabel??`Hide details`,y=z(`button`,`persona-approval-head`);y.type=`button`,m?(y.setAttribute(`data-action`,`toggle-params`),y.setAttribute(`aria-expanded`,g?`true`:`false`),y.setAttribute(`aria-label`,g?v:_)):y.setAttribute(`data-static`,`true`);let b=z(`span`,`persona-approval-logo`),x=h(u.ShieldCheck,16,`currentColor`,2);x&&b.appendChild(x),y.appendChild(b);let S=vv(r,i);if(m){let e=z(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=h(u.ChevronDown,14,`currentColor`,2);t&&e.appendChild(t),S.append(` `),S.appendChild(e)}y.appendChild(S),l.appendChild(y);let C=z(`div`,`persona-approval-body`);if(m){let e=z(`div`,`persona-approval-details`);if(e.setAttribute(`data-role`,`params`),e.hidden=!g,f){let t=z(`p`,`persona-approval-desc`);i?.descriptionColor&&(t.style.color=i.descriptionColor),t.textContent=r.description,e.appendChild(t)}if(p){let t=z(`pre`,`persona-approval-params`);i?.parameterBackgroundColor&&(t.style.background=i.parameterBackgroundColor),i?.parameterTextColor&&(t.style.color=i.parameterTextColor),t.textContent=rn(r.parameters),e.appendChild(t)}C.appendChild(e)}if(c){let e=z(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let t=z(`code`,`persona-approval-tool-name`);if(t.textContent=r.toolName,e.appendChild(t),r.parameters!=null){let t=z(`pre`,`persona-approval-params`);i?.parameterBackgroundColor&&(t.style.background=i.parameterBackgroundColor),i?.parameterTextColor&&(t.style.color=i.parameterTextColor),t.textContent=rn(r.parameters),e.appendChild(t)}C.appendChild(e)}if(r.reason){let e=z(`p`,`persona-approval-reason`);i?.reasonColor?e.style.color=i.reasonColor:i?.descriptionColor&&(e.style.color=i.descriptionColor);let t=z(`span`,`persona-approval-reason-label`);t.textContent=`${i?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(r.reason)),C.appendChild(e)}let w=z(`div`,`persona-approval-actions`),T=null,E=e=>{i?.approveButtonColor&&(e.style.background=i.approveButtonColor),i?.approveButtonTextColor&&(e.style.color=i.approveButtonTextColor)},D=z(`button`,`persona-approval-deny`);if(D.type=`button`,D.setAttribute(`data-action`,`deny`),i?.denyButtonColor&&(D.style.background=i.denyButtonColor),i?.denyButtonTextColor&&(D.style.color=i.denyButtonTextColor),D.append(i?.denyLabel??`Deny`),s){let t=z(`div`,`persona-approval-split`),r=z(`button`,`persona-approval-primary`);r.type=`button`,r.setAttribute(`data-action`,`always`),E(r),r.append(i?.approveLabel??`Always allow`,_v(`⏎`));let o=z(`button`,`persona-approval-caret`);o.type=`button`,o.setAttribute(`data-action`,`toggle-menu`),o.setAttribute(`aria-label`,`More options`),E(o);let s=h(u.ChevronDown,15,`currentColor`,2);s&&o.appendChild(s),t.append(r,o),w.append(t,D),D.append(_v(`Esc`));let c=z(`div`,`persona-approval-menu`),l=z(`button`,`persona-approval-menu-item`);l.type=`button`,l.append(`Allow once`,_v(`⌘⏎`)),c.appendChild(l),T=As({anchor:t,content:c,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(n.id,T),l.addEventListener(`click`,()=>{mv(e,n.id),a()})}else{let e=z(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),E(e),e.append(i?.approveLabel??`Allow`),w.append(e,D)}return C.appendChild(w),l.appendChild(C),l.addEventListener(`click`,r=>{let i=r.target instanceof Element?r.target.closest(`[data-action]`):null;if(!i)return;let s=i.getAttribute(`data-action`);if(s===`toggle-params`){let e=l.querySelector(`[data-role="params"]`);if(e){let r=!!e.hidden;e.hidden=!r,y.setAttribute(`aria-expanded`,r?`true`:`false`),y.setAttribute(`aria-label`,r?v:_),t.set(n.id,r)}}else s===`toggle-menu`?T?.toggle():s===`always`?(mv(e,n.id),a({remember:!0})):s===`allow`?(mv(e,n.id),a()):s===`deny`&&(mv(e,n.id),o())}),l},xv=(e=/* @__PURE__ */ new Map)=>{let t=fv();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let o=n?.approval;if(!o)return null;let s=hv(a);if(o.status!==`pending`){if(mv(t,n.id),o.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return yv(o)}pv(t,n.id);let c=!!a?.clientToken,l=s?.enableAlwaysAllow===!0,u=bv(t,e,n,o,s,r,i,l,c);if(l){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{js(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),mv(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return u}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])mv(t,e);t.latestPendingApprovalId=null}}}})),Cv=o((()=>{dv(),Sv(),iv()})),wv=/* @__PURE__ */ s({createApprovalBubble:()=>uv,createBuiltInApprovalPlugin:()=>xv,humanizeToolName:()=>av,initApprovalUi:()=>nv,updateApprovalDetailsUI:()=>lv}),Tv=o((()=>{Cv()}));ve();const{setLoader:Ev,load:Dv,provide:Ov,getSync:kv}=_e({fallbackImport:()=>Promise.resolve().then(()=>(Tv(),wv))}),Av=Dv,jv=kv;function Mv(e,t){t&&t.split(/\s+/).forEach(t=>t&&e.classList.add(t))}function Nv(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 Pv(e,t){return(t&&Nv(e,t))??Nv(e,Kv)??qv}function Fv(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function Iv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Lv(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}.${String(t.getMilliseconds()).padStart(3,`0`)}`}function Rv(e,t){try{let n=JSON.parse(e);if(typeof n!=`object`||!n)return null;for(let e of t){let t=e.split(`.`),r=n;for(let e of t)if(r&&typeof r==`object`&&r)r=r[e];else{r=void 0;break}if(typeof r==`string`&&r.trim())return r.trim()}}catch{}return null}function zv(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 Bv(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 Vv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?`-- tok/s`:`${e.tokensPerSecond.toFixed(1)} tok/s`}function Hv(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(` · `)}function Uv(e,t,n){let r,i;try{i=JSON.parse(e.payload),r=JSON.stringify(i,null,2)}catch{i=e.payload,r=e.payload}let a=t.find(e=>e.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let t=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>o(),parsedPayload:i});if(t)return t}return o();function o(){let e=z(`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]`),t=z(`pre`,`persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono`);return t.textContent=r,e.appendChild(t),e}}function Wv(e,t,n,r,i,a,o,s){let c=i.has(e.id),l=z(`div`,`persona-border-b persona-border-persona-divider persona-text-xs`);Mv(l,r.classNames?.eventRow);let d=o.find(e=>e.renderEventStreamRow);if(d?.renderEventStreamRow&&s){let n=d.renderEventStreamRow({event:e,index:t,config:s,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(n)return l.appendChild(n),l}return l.appendChild(f()),l;function f(){let i=z(`div`,``),a=z(`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`);a.setAttribute(`data-event-id`,e.id);let l=z(`span`,`persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center`),d=h(c?u.ChevronDown:u.ChevronRight,`14px`,`currentColor`,2);d&&l.appendChild(d);let f=z(`span`,`persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]`);f.textContent=(r.timestampFormat??`relative`)===`relative`?Iv(e.timestamp,n):Lv(e.timestamp);let p=null;r.showSequenceNumbers!==!1&&(p=z(`span`,`persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right`),p.textContent=String(t+1));let m=Pv(e.type,r.badgeColors),g=z(`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`);g.style.backgroundColor=m.bg,g.style.color=m.text,g.style.borderColor=Fv(m.text),g.textContent=e.type;let _=r.descriptionFields??Jv,v=Rv(e.payload,_),y=null;v&&(y=z(`span`,`persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0`),y.textContent=v);let b=z(`div`,`persona-flex-1 persona-min-w-0`),x=z(`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`),S=h(u.Clipboard,`12px`,`currentColor`,1.5);return S&&x.appendChild(S),x.addEventListener(`click`,async t=>{t.stopPropagation(),await zv(Bv(e)),x.innerHTML=``;let n=h(u.Check,`12px`,`currentColor`,1.5);n&&x.appendChild(n),setTimeout(()=>{x.innerHTML=``;let e=h(u.Clipboard,`12px`,`currentColor`,1.5);e&&x.appendChild(e)},1500)}),a.appendChild(l),a.appendChild(f),p&&a.appendChild(p),a.appendChild(g),y&&a.appendChild(y),a.appendChild(b),a.appendChild(x),i.appendChild(a),c&&i.appendChild(Uv(e,o,s)),i}}function Gv(e){let{buffer:t,getFullHistory:n,onClose:r,config:i,plugins:a=[],getThroughput:o}=e,s=e.renderIconByName??(()=>null),c=i?.features?.scrollToBottom,l=c?.enabled!==!1,d=c?.iconName??`arrow-down`,f=c?.label??``,p=i?.features?.eventStream??{},m=a.find(e=>e.renderEventStreamView);if(m?.renderEventStreamView&&i){let e=m.renderEventStreamView({config:i,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(e)return{element:e,update:()=>{},destroy:()=>{}}}return g();function g(){let e=p.classNames,c=z(`div`,`persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0`);Mv(c,e?.panel);let m=[],g=``,_=``,v=null,y=[],b={},x=0,S=_m(),C=0,w=0,T=!1,E=null,D=!1,O=0,k=/* @__PURE__ */ new Set,A=/* @__PURE__ */ new Map,j=``,M=``,ee=null,N,P,F,te,ne=null,I=null,re=null;function ie(){let t=z(`div`,`persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0`),n=z(`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(Mv(n,e?.headerBar),o){I=z(`div`,`persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap`),I.style.cursor=`help`,ne=z(`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`),ne.textContent=`-- tok/s`,re=z(`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`),re.style.display=`none`,re.style.pointerEvents=`none`;let e=I,n=re;I.addEventListener(`mouseenter`,()=>{if(!n.textContent)return;let r=e.getBoundingClientRect(),i=t.getBoundingClientRect();n.style.left=`${r.left-i.left}px`,n.style.top=`${r.bottom-i.top+4}px`,n.style.display=`block`}),I.addEventListener(`mouseleave`,()=>{n.style.display=`none`}),I.appendChild(ne)}let r=z(`div`,`persona-flex-1`);N=z(`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 i=z(`option`,``);i.value=``,i.textContent=`All events (0)`,N.appendChild(i),P=z(`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`),P.type=`button`,P.title=`Copy All`;let a=h(u.ClipboardCopy,`12px`,`currentColor`,1.5);a&&P.appendChild(a);let s=z(`span`,`persona-event-copy-all persona-text-xs`);s.textContent=`Copy All`,P.appendChild(s),I&&n.appendChild(I),n.appendChild(r),n.appendChild(N),n.appendChild(P);let c=z(`div`,`persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface`);Mv(c,e?.searchBar);let l=h(u.Search,`14px`,`var(--persona-muted, #9ca3af)`,1.5),d=z(`span`,`persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center`);l&&d.appendChild(l),F=z(`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`),Mv(F,e?.searchInput),F.type=`text`,F.placeholder=`Search event payloads...`,te=z(`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`),te.type=`button`,te.style.display=`none`;let f=h(u.X,`12px`,`currentColor`,2);return f&&te.appendChild(f),c.appendChild(d),c.appendChild(F),c.appendChild(te),t.appendChild(n),t.appendChild(c),re&&t.appendChild(re),t}let ae,oe=a.find(e=>e.renderEventStreamToolbar);ae=oe?.renderEventStreamToolbar&&i?oe.renderEventStreamToolbar({config:i,defaultRenderer:()=>ie(),eventCount:t.getSize(),filteredCount:0,onFilterChange:e=>{g=e,ge(),H()},onSearchChange:e=>{_=e,ge(),H()}})??ie():ie();let se=z(`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`);se.style.display=`none`;function ce(){if(!o||!ne||!I)return;let e=o(),t=Vv(e);ne.textContent=t;let n=Hv(e);re&&(re.textContent=n,n||(re.style.display=`none`)),I.setAttribute(`aria-label`,n?`Throughput: ${t}, ${n}`:`Throughput: ${t}`)}let le=z(`div`,`persona-flex-1 persona-min-h-0 persona-relative`),L=z(`div`,`persona-event-stream-list persona-overflow-y-auto persona-min-h-0`);L.style.height=`100%`;let R=z(`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`);Mv(R,e?.scrollIndicator),R.style.display=`none`,R.setAttribute(`data-persona-scroll-to-bottom-has-label`,f?`true`:`false`);let ue=s(d,`14px`,`currentColor`,2);ue&&R.appendChild(ue);let de=z(`span`,``);de.textContent=f,R.appendChild(de);let fe=z(`div`,`persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted`);fe.style.display=`none`,le.appendChild(L),le.appendChild(fe),le.appendChild(R),c.setAttribute(`tabindex`,`0`),c.appendChild(ae),c.appendChild(se),c.appendChild(le);function pe(){let e=t.getAll(),n={};for(let t of e)n[t.type]=(n[t.type]||0)+1;let r=Object.keys(n).sort(),i=r.length!==y.length||!r.every((e,t)=>e===y[t]),a=!i&&r.some(e=>n[e]!==b[e]),o=e.length!==Object.values(b).reduce((e,t)=>e+t,0);if(!i&&!a&&!o||(y=r,b=n,!N))return;let s=N.value;if(N.options[0].textContent=`All events (${e.length})`,i){for(;N.options.length>1;)N.remove(1);for(let e of r){let t=z(`option`,``);t.value=e,t.textContent=`${e} (${n[e]||0})`,N.appendChild(t)}s&&r.includes(s)?N.value=s:s&&(N.value=``,g=``)}else for(let e=1;e<N.options.length;e++){let t=N.options[e];t.textContent=`${t.value} (${n[t.value]||0})`}}function me(){let e=t.getAll();if(g&&(e=e.filter(e=>e.type===g)),_){let t=_.toLowerCase();e=e.filter(e=>e.type.toLowerCase().includes(t)||e.payload.toLowerCase().includes(t))}return e}function he(){return g!==``||_!==``}function ge(){x=0,C=0,S.resume(),R.style.display=`none`}function B(e){k.has(e)?k.delete(e):k.add(e),ee=e;let t=L.scrollTop,n=S.isFollowing();D=!0,S.pause(),H(),L.scrollTop=t,n&&S.resume(),D=!1}function V(){return ym(L,50)}function H(){w=Date.now(),T=!1,ce(),pe();let e=t.getEvictedCount();e>0?(se.textContent=`${e.toLocaleString()} older events truncated`,se.style.display=``):se.style.display=`none`,m=me();let n=m.length,r=t.getSize()>0;n===0&&r&&he()?(fe.textContent=_?`No events matching '${_}'`:`No events matching filter`,fe.style.display=``,L.style.display=`none`):(fe.style.display=`none`,L.style.display=``),P&&(P.title=he()?`Copy Filtered (${n})`:`Copy All`),l&&!S.isFollowing()&&n>x&&(C+=n-x,de.textContent=f?`${f}${C>0?` (${C})`:``}`:``,R.style.display=``),x=n;let o=t.getAll(),s=o.length>0?o[0].timestamp:0,c=new Set(m.map(e=>e.id));for(let e of k)c.has(e)||k.delete(e);let u=g!==j||_!==M,d=A.size===0&&m.length>0;if(u||d||m.length===0){L.innerHTML=``,A.clear();let e=document.createDocumentFragment();for(let t=0;t<m.length;t++){let n=Wv(m[t],t,s,p,k,B,a,i);A.set(m[t].id,n),e.appendChild(n)}L.appendChild(e),j=g,M=_,ee=null}else{if(ee!==null){let e=A.get(ee);if(e&&e.parentNode===L){let t=m.findIndex(e=>e.id===ee);if(t>=0){let n=Wv(m[t],t,s,p,k,B,a,i);L.insertBefore(n,e),e.remove(),A.set(ee,n)}}ee=null}let e=new Set(m.map(e=>e.id));for(let[t,n]of A)e.has(t)||(n.remove(),A.delete(t));for(let e=0;e<m.length;e++){let t=m[e];if(!A.has(t.id)){let n=Wv(t,e,s,p,k,B,a,i);A.set(t.id,n),L.appendChild(n)}}}S.isFollowing()&&(L.scrollTop=L.scrollHeight)}function _e(){Date.now()-w>=Yv?(E!==null&&(cancelAnimationFrame(E),E=null),H()):T||(T=!0,E=requestAnimationFrame(()=>{E=null,H()}))}let ve=(e,t)=>{if(!P)return;P.innerHTML=``;let n=h(e,`12px`,`currentColor`,1.5);n&&P.appendChild(n);let r=z(`span`,`persona-text-xs`);r.textContent=`Copy All`,P.appendChild(r),setTimeout(()=>{P.innerHTML=``;let e=h(u.ClipboardCopy,`12px`,`currentColor`,1.5);e&&P.appendChild(e);let t=z(`span`,`persona-text-xs`);t.textContent=`Copy All`,P.appendChild(t),P.disabled=!1},t)},ye=async()=>{if(P){P.disabled=!0;try{let e;he()?e=m:n?(e=await n(),e.length===0&&(e=t.getAll())):e=t.getAll();let r=e.map(e=>{try{return JSON.parse(e.payload)}catch{return e.payload}});await navigator.clipboard.writeText(JSON.stringify(r,null,2)),ve(u.Check,1500)}catch{ve(u.X,1500)}}},be=()=>{N&&(g=N.value,ge(),H())},xe=()=>{F&&te&&(te.style.display=F.value?``:`none`,v&&clearTimeout(v),v=setTimeout(()=>{_=F.value,ge(),H()},150))},Se=()=>{F&&te&&(F.value=``,_=``,te.style.display=`none`,v&&clearTimeout(v),ge(),H())},Ce=()=>{if(D)return;let e=L.scrollTop,{action:t,nextLastScrollTop:n}=bm({following:S.isFollowing(),currentScrollTop:e,lastScrollTop:O,nearBottom:V(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});O=n,t===`resume`?(S.resume(),C=0,R.style.display=`none`):t===`pause`&&(S.pause(),l&&(de.textContent=f,R.style.display=``))},we=e=>{let t=xm({following:S.isFollowing(),deltaY:e.deltaY,nearBottom:V(),resumeWhenNearBottom:!0});t===`pause`?(S.pause(),l&&(de.textContent=f,R.style.display=``)):t===`resume`&&(S.resume(),C=0,R.style.display=`none`)},Te=()=>{l&&(L.scrollTop=L.scrollHeight,S.resume(),C=0,R.style.display=`none`)},Ee=e=>{let t=e.target;if(!t||t.closest(`button`))return;let n=t.closest(`[data-event-id]`);if(!n)return;let r=n.getAttribute(`data-event-id`);r&&B(r)},De=e=>{(e.metaKey||e.ctrlKey)&&e.key===`f`?(e.preventDefault(),F?.focus(),F?.select()):e.key===`Escape`&&(F&&document.activeElement===F?(Se(),F.blur(),c.focus()):r&&r())};P&&P.addEventListener(`click`,ye),N&&N.addEventListener(`change`,be),F&&F.addEventListener(`input`,xe),te&&te.addEventListener(`click`,Se),L.addEventListener(`scroll`,Ce),L.addEventListener(`wheel`,we,{passive:!0}),L.addEventListener(`click`,Ee),R.addEventListener(`click`,Te),c.addEventListener(`keydown`,De);function Oe(){v&&clearTimeout(v),E!==null&&(cancelAnimationFrame(E),E=null),T=!1,A.clear(),P&&P.removeEventListener(`click`,ye),N&&N.removeEventListener(`change`,be),F&&F.removeEventListener(`input`,xe),te&&te.removeEventListener(`click`,Se),L.removeEventListener(`scroll`,Ce),L.removeEventListener(`wheel`,we),L.removeEventListener(`click`,Ee),R.removeEventListener(`click`,Te),c.removeEventListener(`keydown`,De)}return{element:c,update:_e,destroy:Oe}}}var Kv,qv,Jv,Yv,Xv=o((()=>{H(),g(),Kv={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)`}},Kv.execution_error=Kv.error,Kv.execution_=Kv.flow_,Kv.turn_=Kv.agent_,Kv.text_=Kv.agent_,qv={bg:`var(--persona-event-badge-default-bg, #f3f4f6)`,text:`var(--persona-event-badge-default-fg, #4b5563)`},Jv=[`flowName`,`stepName`,`reasoningText`,`text`,`name`,`tool`,`toolName`],Yv=100})),Zv,Qv=o((()=>{Zv=class{#e;#t=0;#n=0;#r=0;#i=/* @__PURE__ */ new Set;#a;#o;constructor(e=2e3,t=null){this.#a=e,this.#e=Array(e),this.#o=t}push(e){this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#r++,this.#i.add(e.type),this.#o?.put(e)}getAll(){return this.#n===0?[]:this.#n<this.#a?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#a),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#o)return 0;let e=await this.#o.getAll();if(e.length===0)return 0;let t=e.length>this.#a?e.slice(e.length-this.#a):e;for(let e of t)this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#i.add(e.type);return this.#r=e.length,t.length}getAllFromStore(){return this.#o?this.#o.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.#n}getTotalCaptured(){return this.#r}getEvictedCount(){return this.#r-this.#n}clear(){this.#e=Array(this.#a),this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.destroy()}getEventTypes(){return Array.from(this.#i)}}})),$v,ey=o((()=>{$v=class{#e=null;#t=[];#n=!1;#r=!1;#i;#a;constructor(e=`persona-event-stream`,t=`events`){this.#i=e,this.#a=t}open(){return new Promise((e,t)=>{try{let n=indexedDB.open(this.#i,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#a)||e.createObjectStore(this.#a,{keyPath:`id`}).createIndex(`timestamp`,`timestamp`,{unique:!1})},n.onsuccess=()=>{this.#e=n.result,e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}put(e){!this.#e||this.#r||(this.#t.push(e),this.#n||(this.#n=!0,queueMicrotask(()=>this.#o())))}putBatch(e){if(!(!this.#e||this.#r||e.length===0))try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.#e)e([]);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).index(`timestamp`).getAll();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}getCount(){return new Promise((e,t)=>{if(!this.#e)e(0);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).count();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}clear(){return new Promise((e,t)=>{if(!this.#e)e();else{this.#t=[];try{let n=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a).clear();n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}}})}close(){this.#e&&=(this.#e.close(),null)}destroy(){return this.#r=!0,this.#t=[],this.close(),new Promise((e,t)=>{try{let n=indexedDB.deleteDatabase(this.#i);n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}#o(){if(this.#n=!1,!this.#e||this.#r||this.#t.length===0)return;let e=this.#t;this.#t=[];try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}}}));function ty(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ny(e,t){if(!(e<=0||t===void 0||t<sy))return e/(t/1e3)}function ry(e,t){return typeof t.type==`string`?t.type:e}function iy(e){let t=fy(e,`tokens`)??fy(e,`totalTokens`);return t?dy(t.output):void 0}function ay(e){return dy(e.durationMs)}function oy(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}var sy,cy,ly,uy,dy,fy,py,my=o((()=>{sy=250,cy=/* @__PURE__ */ new Set([`step_start`,`turn_start`]),ly=/* @__PURE__ */ new Set([`step_complete`,`turn_complete`]),uy=e=>typeof e==`object`&&!!e&&!Array.isArray(e),dy=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,fy=(e,t)=>{let n=e[t];return uy(n)?n:void 0},py=class{#e={status:`idle`};#t=null;constructor(e=oy){this.now=e}getMetric(){let e=this.#t;if(e&&this.#e.status===`running`&&e.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.#e,durationMs:t,tokensPerSecond:ny(this.#e.outputTokens,t)}}return this.#e}reset(){this.#t=null,this.#e={status:`idle`}}#n(e){this.#t={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.#e={status:`running`}}processEvent(e,t){if(!uy(t)){e===`execution_error`&&this.#t&&(this.#t=null,this.#e={status:`error`});return}let n=ry(e,t),r=this.now();if(n===`execution_start`)this.#n(r);else if(cy.has(n))this.#t||this.#n(r);else if(n===`text_delta`){let e=typeof t.delta==`string`?t.delta:``;if(!e)return;this.#t||this.#n(r);let n=this.#t;n.firstDeltaAt??=r,n.visibleCharCount+=e.length;let i=n.exactOutputTokens+ty(n.visibleCharCount),a=r-n.firstDeltaAt;this.#e={status:`running`,tokensPerSecond:ny(i,a),outputTokens:i,durationMs:a,source:n.exactOutputTokens>0?`usage`:`estimate`}}else if(ly.has(n)){if(!this.#t)return;let e=this.#t,n=iy(t);n!==void 0&&(e.exactOutputTokens+=n,e.visibleCharCount=0);let i=e.exactOutputTokens>0,a=e.exactOutputTokens+ty(e.visibleCharCount),o=this.#r(e,t,r);this.#e={status:`running`,tokensPerSecond:ny(a,o),outputTokens:a,durationMs:o,source:i?`usage`:`estimate`}}else if(n===`execution_complete`){if(!this.#t)return;let e=this.#t,n=iy(t),i=n??e.exactOutputTokens+ty(e.visibleCharCount),a=n!==void 0||e.exactOutputTokens>0?`usage`:`estimate`,o=this.#r(e,t,r);this.#e={status:`complete`,tokensPerSecond:ny(i,o),outputTokens:i,durationMs:o,source:a},this.#t=null}else if(n===`execution_error`||n===`error`&&t.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:`error`}}}#r(e,t,n){let r=e.firstDeltaAt===void 0?void 0:n-e.firstDeltaAt;return r!==void 0&&r>=sy?r:ay(t)??n-e.startedAt}}})),hy=o((()=>{Xv(),Qv(),ey(),my()})),gy=/* @__PURE__ */ s({EventStreamBuffer:()=>Zv,EventStreamStore:()=>$v,ThroughputTracker:()=>py,createEventStreamView:()=>Gv}),_y=o((()=>{hy()}));ve();const{setLoader:vy,load:yy}=_e({fallbackImport:()=>Promise.resolve().then(()=>(_y(),gy))}),by=yy;var xy,Sy,Cy=o((()=>{xy=class{constructor(){this.components=/* @__PURE__ */ new Map,this.#e=/* @__PURE__ */ new Map}#e;register(e,t,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),n?this.#e.set(e,n):this.#e.delete(e)}unregister(e){this.components.delete(e),this.#e.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#e.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}},Sy=new xy}));function wy(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??``}function Ty(e){let t=wy(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n+1).toLowerCase()}function Ey(e){if(typeof e!=`string`)return``;let t=e.indexOf(`
|
|
254
|
+
`,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=Yh(e),i=sp(e)===`circle`;i?(n.dataset.personaLauncherVariant=`circle`,n.setAttribute(`aria-label`,t.title??`Open chat`)):(n.removeAttribute(`data-persona-launcher-variant`),n.removeAttribute(`aria-label`));let a=n.querySelector(`[data-role='launcher-title']`);if(a){let e=t.title??`Chat Assistant`;a.textContent=e,a.setAttribute(`title`,e)}let o=n.querySelector(`[data-role='launcher-subtitle']`);if(o){let e=t.subtitle??`Here to help you get answers fast`;o.textContent=e,o.setAttribute(`title`,e)}let s=n.querySelector(`.persona-flex-col`);s&&(t.textHidden||r||i?s.style.display=`none`:s.style.display=``);let c=n.querySelector(`[data-role='launcher-icon']`);if(c){if(t.agentIconHidden)c.style.display=`none`;else{let e=t.agentIconSize??`40px`;if(c.style.height=e,c.style.width=e,t.agentIconBackgroundColor?(c.style.backgroundColor=t.agentIconBackgroundColor,c.classList.remove(`persona-bg-persona-primary`)):(c.style.backgroundColor=``,c.classList.add(`persona-bg-persona-primary`)),c.innerHTML=``,t.agentIconName){let n=parseFloat(e)||24,r=U(t.agentIconName,n*.6,`var(--persona-text-inverse, #ffffff)`,1.5);r?(c.appendChild(r),c.style.display=``):(c.textContent=t.agentIconText??`💬`,c.style.display=``)}else t.iconUrl?c.style.display=`none`:(c.textContent=t.agentIconText??`💬`,c.style.display=``)}}let l=n.querySelector(`[data-role='launcher-image']`);if(l){let e=t.agentIconSize??`40px`;l.style.height=e,l.style.width=e,t.iconUrl&&!t.agentIconName&&!t.agentIconHidden?(l.src=t.iconUrl,l.style.display=`block`):l.style.display=`none`}let u=n.querySelector(`[data-role='launcher-call-to-action-icon']`);if(u){let e=t.callToActionIconSize??`32px`;u.style.height=e,u.style.width=e,t.callToActionIconBackgroundColor?(u.style.backgroundColor=t.callToActionIconBackgroundColor,u.classList.remove(`persona-bg-persona-primary`)):(u.style.backgroundColor=``,u.classList.add(`persona-bg-persona-primary`)),t.callToActionIconColor?(u.style.color=t.callToActionIconColor,u.classList.remove(`persona-text-persona-call-to-action`)):(u.style.color=``,u.classList.add(`persona-text-persona-call-to-action`));let n=0;if(t.callToActionIconPadding?(u.style.boxSizing=`border-box`,u.style.padding=t.callToActionIconPadding,n=(parseFloat(t.callToActionIconPadding)||0)*2):(u.style.boxSizing=``,u.style.padding=``),t.callToActionIconHidden||i)u.style.display=`none`;else if(u.style.display=r?`none`:``,u.innerHTML=``,t.callToActionIconName){let r=Math.max((parseFloat(e)||24)-n,8),i=U(t.callToActionIconName,r,`currentColor`,1.5);i?u.appendChild(i):u.textContent=t.callToActionIconText??`↗`}else u.textContent=t.callToActionIconText??`↗`}let d=t.position&&ag[t.position]?ag[t.position]:ag[`bottom-right`];n.className=r?`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`:`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 ${d}`,r||(n.style.zIndex=String(t.zIndex??1e5)),n.style.border=t.border??`1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))`,n.style.boxShadow=t.shadow===void 0?`var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))`:t.shadow.trim()===``?`none`:t.shadow,r?(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=t.collapsedMaxWidth??``,n.style.justifyContent=``,n.style.padding=``,n.style.overflow=``)};return e&&r(e),{element:n,update:r,destroy:()=>{n.removeEventListener(`click`,t),n.remove()}}},L_=/* @__PURE__ */ new Set,R_=e=>{let t=e?.persistState;return`${(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`}teaser-dismissed`},z_=(e,t)=>{if(L_.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)===`1`}catch{return!1}},B_=(e,t)=>{if(L_.add(e),t)try{window.localStorage.setItem(e,`1`)}catch{}},V_=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,H_=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Yh(e??{})?null:t},U_=(e,t)=>{let n=B(`div`,`persona-launcher-surface`);n.setAttribute(`data-persona-launcher-surface`,`true`);let r=e??{},i=null,a=null,o=null,s=null,c=null,l=!1,u=!1,d=!1,f=!1,p=()=>(i?.frequency??`once`)===`once`&&r.persistState!==!1,m=()=>{c!==null&&(clearTimeout(c),c=null)},h=()=>{a&&l&&(l=!1,a.hidden=!0)},g=e=>{m(),d=!0,h(),B_(R_(r),e&&p())},_=e=>{i&&!d&&g(e===`user`&&l)},v=()=>{c=null,!(!a||d||f)&&(u=!0,l=!0,a.hidden=!1,!(V_()||typeof a.animate!=`function`)&&a.animate([{opacity:`0`,transform:`translateY(6px)`},{opacity:`1`,transform:`none`}],{duration:220,easing:`ease-out`,fill:`backwards`}))},y=()=>{i&&a&&(d||u||f||z_(R_(r),p())||(m(),c=setTimeout(v,Math.max(0,i.delayMs??0))))},b=()=>{g(p()),t()},x=e=>{e.stopPropagation(),g(p())},S=I_(e,()=>{_(`user`),t()}),C=()=>{m(),s?.removeEventListener(`click`,b),o?.removeEventListener(`click`,x),a?.remove(),a=null,s=null,o=null,l=!1},w=()=>{s=V(`button`,{className:`persona-launcher-teaser-text`,attrs:{type:`button`}}),s.addEventListener(`click`,b),o=V(`button`,{className:`persona-launcher-teaser-dismiss`,attrs:{type:`button`},text:`×`}),o.addEventListener(`click`,x),a=V(`div`,{className:`persona-launcher-teaser`,attrs:{"data-persona-launcher-teaser":`true`,role:`status`,"aria-live":`polite`,hidden:``}},s,o),n.insertBefore(a,S.element)},T=()=>{let e=r.launcher?.position??`bottom-right`,t=ag[e]??ag[`bottom-right`];a?(n.className=Me(`persona-launcher-surface`,t),n.setAttribute(`data-teaser`,e),n.style.zIndex=String(r.launcher?.zIndex??1e5),S.element.style.position=`static`):(n.className=`persona-launcher-surface`,n.removeAttribute(`data-teaser`),n.style.zIndex=``,S.element.style.position=``)},E=e=>{let t=H_(e);i=t,t?(a||w(),s.textContent=t.text,o.hidden=t.dismissible===!1,o.setAttribute(`aria-label`,t.dismissLabel??`Dismiss message`),y()):C()};return n.appendChild(S.element),e&&(E(e),T()),{element:n,launcher:S,get teaser(){return a?{element:a,show:v,dismiss:g}:null},setPanelOpen:(e,t=`user`)=>{f=e,e&&_(t)},update:e=>{r=e,S.update(e),E(e),T()},destroy:()=>{C(),S.destroy(),n.remove()}}},W_=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:i}=j_(e),a=F_(e,t),o={wrapper:n,panel:r,pillRoot:i},s={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:o,panelElements:a,transcript:s,header:c,composer:l,replaceHeader:e=>(c.element.replaceWith(e.header),c.element=e.header,c.iconHolder=e.iconHolder,c.headerTitle=e.headerTitle,c.headerSubtitle=e.headerSubtitle,c.closeButton=e.closeButton,c.closeButtonWrapper=e.closeButtonWrapper,c.clearChatButton=e.clearChatButton,c.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{l.footer.replaceWith(e),l.footer=e}}},G_=({config:e,plugins:t,onToggle:n})=>{let r=t.find(e=>e.renderLauncher);if(r?.renderLauncher){let t=r.renderLauncher({config:e,defaultRenderer:()=>I_(e,n).element,onToggle:n});if(t)return{instance:null,element:t}}let i=U_(e,n);return{instance:i,element:i.element}},K_=e=>{let t=e?.persistState;return(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`},q_=(e,t,n)=>`${K_(e)}plugin:${t}:${n}`,J_=e=>{let t=/* @__PURE__ */ new Map,n=!1,r=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return i=>{let a=t=>q_(e(),i,t);return{get:e=>{let i=a(e),o=r();if(o)try{return o.getItem(i)}catch{n=!0}return t.get(i)??null},set:(e,i)=>{let o=a(e),s=r();if(s)try{s.setItem(o,i);return}catch{n=!0}t.set(o,i)},remove:e=>{let i=a(e);t.delete(i);let o=r();if(o)try{o.removeItem(i)}catch{n=!0}}}}};var Y_,X_=o((()=>{H(),Y_=(e,t,n)=>{let r=n;for(let n of t){let t=B(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(r)),t.textContent=n===` `?`\xA0`:n,e.appendChild(t),r++}return r}}));H(),W(),Ae(),Tn(),X_();const Z_=(e,t)=>{let n=e.reasoning?.chunks.join(``).trim()??``;return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
255
|
+
`):``},Q_=(e,t,n)=>{at(e,t,{stateSet:n,previewKind:`reasoning`,iconColor:`currentColor`})},$_=(e,t,n=/* @__PURE__ */ new Set)=>{t=Y(t,`reasoning`);let r=e.reasoning,i=nt(`persona-reasoning-bubble`,e.id);if(!r)return X(i,e,t,`reasoning`);let a=t?.features?.reasoningDisplay??{},o=a.expandable??we.expandable,s=o&&n.has(e.id),c=r.status!==`complete`,l=Z_(e,a.previewMaxLines??we.previewMaxLines),u=K({expandable:o,expanded:s,bubbleType:`reasoning`}),d=B(`div`,`persona-flex persona-flex-col persona-text-left`),f=B(`span`,`persona-text-xs persona-text-persona-primary`),p=ot(t,`reasoning`)===`row`,m=p&&!c?`Thought for ${st(r.durationMs??(r.completedAt!==void 0&&r.startedAt!==void 0?r.completedAt-r.startedAt:void 0))}`:`Thinking...`,h=t?.reasoning??{},g=String(r.startedAt??Date.now()),_=()=>{let e=B(`span`,``);return e.setAttribute(`data-tool-elapsed`,g),e.textContent=hn(r),e},v=h.renderCollapsedSummary?.({message:e,reasoning:r,defaultSummary:m,previewText:l,isActive:c,config:t??{},elapsed:hn(r),createElapsedElement:_});typeof v==`string`&&v.trim()?(f.textContent=v,d.appendChild(f)):v instanceof HTMLElement?d.appendChild(v):(f.textContent=m,d.appendChild(f));let y=B(`span`,`persona-text-xs persona-text-persona-primary`);y.textContent=ln(r),p||d.appendChild(y);let b=a.loadingAnimation??we.loadingAnimation,x=h.activeTextTemplate,S=h.completeTextTemplate,C=c?x:S,w=v instanceof HTMLElement,T=(e,t)=>{f.textContent=``;let n=_n(e,``),i=0;for(let e of n){let n=e.styles.length>0?(()=>{let t=B(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return f.appendChild(t),t})():f;if(e.isDuration&&c)n.appendChild(_());else{let a=e.isDuration?hn(r):e.text;t?i=Y_(n,a,i):n.appendChild(document.createTextNode(a))}}};if(!w&&C){if(y.style.display=`none`,f.style.display=``,c&&b!==`none`){let e=h.loadingAnimationDuration??2e3;f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`?(f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),T(C,!1)):(f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor)),T(C,!0))}else T(C,!1)}else if(!w&&c&&b!==`none`){f.style.display=``;let e=h.loadingAnimationDuration??2e3;if(f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`)f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`);else{f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor));let t=f.textContent||m;f.textContent=``,Y_(f,t,0)}r.status===`complete`&&!p&&(f.style.display=`none`)}else w||(r.status===`complete`&&!p?f.style.display=`none`:f.style.display=``);if(a.iconName&&!w){let e=B(`span`,`persona-reasoning-header-icon`),t=U(a.iconName,16,`currentColor`,2);t&&(e.appendChild(t),u.appendChild(e))}let E=`currentColor`,D=J(u,d,{expandable:o,expanded:s,iconColor:E,metaGap:!1}),O=rt({bubble:i,previewKind:`reasoning`,expanded:s,isActive:c,previewText:l,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:r,defaultPreview:l,isActive:c,config:t??{}})});if(!o)return i.append(u,O),X(i,e,t,`reasoning`);let k=B(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`);k.style.display=s?``:`none`;let A=r.chunks.join(``),j=B(`div`,`persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted`);return j.textContent=A||(r.status===`complete`?`No additional context was shared.`:`Waiting for details…`),k.appendChild(j),it({expanded:s,header:u,toggleIcon:D,content:k,collapsedPreview:O,iconColor:E}),i.append(u,O,k),X(i,e,t,`reasoning`)};H(),Tn(),W();const ev=e=>{if(e==null)return!0;if(typeof e==`string`){if(!e.trim())return!0;try{return ev(JSON.parse(e))}catch{return!1}}return typeof e==`object`&&Object.keys(e).length===0},tv=e=>{if(typeof e==`object`&&e)return!0;if(typeof e!=`string`)return!1;try{let t=JSON.parse(e);return typeof t==`object`&&!!t}catch{return!1}};function nv(e,t,n){let r=t.toolCall;if(!r)return;let i=n.toolCall??{},a=(t,n)=>{let r=V(`section`,{className:`persona-tool-detail`,attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:i.codeBlockBackgroundColor,borderColor:i.codeBlockBorderColor,borderWidth:i.codeBlockBorderColor?`1px`:void 0}}),a=V(`div`,{className:`persona-tool-detail-label`,text:t,style:{color:i.labelTextColor}}),o=sn(n),s=V(`pre`,{className:`persona-tool-detail-value${tv(n)?` persona-tool-detail-code`:``}`,text:o,attrs:o.length>420||o.split(`
|
|
256
|
+
`).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:i.codeBlockTextColor??i.contentTextColor}}),c=V(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),l=U(`copy`,14,`currentColor`,1.7);l&&c.appendChild(l),r.append(a,s,c),e.appendChild(r)};ev(r.args)||a(`Request`,r.args);let o=r.status===`complete`&&r.result!==void 0?r.result:r.chunks?.join(``);o!==void 0&&(typeof o!=`string`||o.trim())&&a(`Response`,o),r.success===!1&&e.appendChild(V(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``,role:`status`}}))}const rv=/* @__PURE__ */ new WeakMap;async function iv(e){let t=e.closest(`[data-persona-tool-detail]`),n=t?.querySelector(`pre`);if(!n)return;let r=`Copy ${t?.getAttribute(`data-persona-tool-detail`)}`;clearTimeout(rv.get(e));try{await navigator.clipboard.writeText(n.textContent??``),e.dataset.copied=`true`,e.setAttribute(`aria-label`,`Copied`),e.title=`Copied`;let t=U(`check`,14,`currentColor`,2);t&&e.replaceChildren(t)}catch{e.setAttribute(`aria-label`,`Copy failed — try again`),e.title=`Copy failed — try again`}rv.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute(`aria-label`,r),e.title=r;let t=U(`copy`,14,`currentColor`,1.7);t&&e.replaceChildren(t),rv.delete(e)},1800))}H(),Ae(),Tn(),X_();const av=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),ov=(e,t)=>{let n=e.toolCall;if(!n)return``;let r=(n.chunks??[]).join(``).trim();if(r)return r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join(`
|
|
257
|
+
`);let i=sn(n.args).trim();return i?i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
258
|
+
`):``},sv=(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)`},cv=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??Ce.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:ov(e,r?.previewMaxLines??Ce.previewMaxLines),o=n?.interrupted?`${n.name?.trim()||`Tool`} · Interrupted`:n?ot(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:fn(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,c=t?.toolCall??{},l=o;return i===`tool-name`?l=n.name?.trim()||o:i===`tool-preview`&&a&&(l=a),s&&c.activeTextTemplate?l=gn(n,c.activeTextTemplate,l):!s&&!n.interrupted&&c.completeTextTemplate&&(l=gn(n,c.completeTextTemplate,l)),n.interrupted?l.includes(` · Interrupted`)||(l+=` · Interrupted`):n.success===!1?l+=` · Failed`:n.superseded&&(l+=` · Approved, ran again below`),{summary:l,previewText:a,isActive:s}},lv=(e,t,n,r)=>{at(e,t,{stateSet:n,previewKind:`tool`,iconColor:av(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},uv=(e,t,n=/* @__PURE__ */ new Set)=>{t=Y(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=nt(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return X(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??Ce.expandable,c=s&&n.has(e.id),{summary:l,previewText:u,isActive:d}=cv(e,t),f=K({expandable:s,expanded:c,bubbleType:`tool`});i.headerBackgroundColor&&(f.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(f.style.paddingLeft=i.headerPaddingX,f.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(f.style.paddingTop=i.headerPaddingY,f.style.paddingBottom=i.headerPaddingY);let p=B(`div`,`persona-flex persona-flex-col persona-text-left`),m=B(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(m.style.color=i.headerTextColor);let h=String(r.startedAt??Date.now()),g=()=>{let e=B(`span`,``);return d&&e.setAttribute(`data-tool-elapsed`,h),e.textContent=mn(r),e},_=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:l,previewText:u,collapsedMode:o.collapsedMode??Ce.collapsedMode,isActive:d,config:t??{},elapsed:mn(r),createElapsedElement:g});typeof _==`string`&&_.trim()?(m.textContent=_,p.appendChild(m)):_ instanceof HTMLElement?p.appendChild(_):(m.textContent=l,p.appendChild(m));let v=o.loadingAnimation??Ce.loadingAnimation,y=i.activeTextTemplate,b=r.interrupted?void 0:i.completeTextTemplate,x=d?y:b,S=_ instanceof HTMLElement,C=(e,t)=>{m.textContent=``;let n=r.name?.trim()||`tool`,i=_n(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=B(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return m.appendChild(t),t})():m;if(e.isDuration&&d)n.appendChild(g());else{let i=e.isDuration?mn(r):e.text;t?a=Y_(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!S){if(d&&v!==`none`){let e=i.loadingAnimationDuration??2e3;if(m.setAttribute(`data-preserve-animation`,`true`),v===`pulse`)m.classList.add(`persona-tool-loading-pulse`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${v}`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),v===`shimmer-color`&&(i.loadingAnimationColor&&m.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&m.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||l;m.textContent=``,Y_(m,e,0)}}else x&&C(x,!1)}let w=av(i,ot(t,`tool`)===`row`),T=J(f,p,{expandable:s,expanded:c,iconColor:w,metaGap:!0}),E=rt({bubble:a,previewKind:`tool`,expanded:c,isActive:d,previewText:u,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:u,isActive:d,config:t??{}})});if(!s)return a.append(f,E),X(a,e,t,`tool`);let D=B(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(D.style.display=c?``:`none`,i.contentBackgroundColor&&(D.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(D.style.color=i.contentTextColor),i.contentPaddingX&&(D.style.paddingLeft=i.contentPaddingX,D.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(D.style.paddingTop=i.contentPaddingY,D.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)nv(D,e,t);else{if(r.name){let e=B(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,D.appendChild(e)}if(r.args!==void 0){let e=B(`div`,`persona-space-y-1`),t=B(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=B(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,sv(n,i),n.textContent=sn(r.args),e.append(t,n),D.appendChild(e)}if(r.chunks&&r.chunks.length){let e=B(`div`,`persona-space-y-1`),t=B(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=B(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,sv(n,i),n.textContent=r.chunks.join(``),e.append(t,n),D.appendChild(e)}if(r.success===!1&&D.appendChild(V(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=B(`div`,`persona-space-y-1`),t=B(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=B(`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`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,sv(n,i),n.textContent=sn(r.result),e.append(t,n),D.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=B(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,D.appendChild(e)}}return it({expanded:c,header:f,toggleIcon:T,content:D,collapsedPreview:E,iconColor:w}),a.append(f,E,D),X(a,e,t,`tool`)};var dv,fv,pv,mv=o((()=>{dv=()=>void 0,fv=e=>{dv=e.webMcpToolTitle},pv=e=>dv(e)})),hv,gv,_v,vv,yv,bv,xv=o((()=>{A(),H(),Tn(),mv(),ee(),E(),hv=e=>{let t=(e.startsWith(`webmcp:`)?e.slice(v.length):e).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return e;let n=t.join(` `).toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)},gv=e=>e?.approval===!1?void 0:e?.approval,_v=(e,t,n)=>{let r=gv(n)?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},vv=(e,t,n)=>{let r=gv(n);e.setAttribute(`aria-expanded`,t?`true`:`false`);let i=e.querySelector(`[data-approval-details-label]`);i&&(i.textContent=t?r?.hideDetailsLabel??`Hide details`:r?.showDetailsLabel??`Show details`);let a=e.querySelector(`[data-approval-details-chevron]`);if(a){a.innerHTML=``;let e=j(t?u.ChevronUp:u.ChevronDown,14,`currentColor`,2);e&&a.appendChild(e)}},yv=(e,t,n,r=/* @__PURE__ */ new Map)=>{let i=t.querySelector(`button[data-bubble-type="approval"]`),a=t.querySelector(`[data-approval-details]`);if(!i||!a)return;let o=_v(e,r,n);vv(i,o,n),a.style.display=o?``:`none`},bv=(e,t,n=/* @__PURE__ */ new Map)=>{let r=e.approval,i=t?.approval===!1?void 0:t?.approval,a=r?.status===`pending`,o=B(`div`,[`persona-approval-bubble`,`persona-w-full`,`persona-rounded-2xl`,`persona-border`,`persona-shadow-sm`,`persona-overflow-hidden`].join(` `));if(o.id=`bubble-${e.id}`,o.setAttribute(`data-message-id`,e.id),o.style.backgroundColor=i?.backgroundColor??`var(--persona-approval-bg)`,o.style.borderColor=i?.borderColor??`var(--persona-approval-border)`,o.style.boxShadow=i?.shadow===void 0?`var(--persona-approval-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return o;let s=B(`div`,`persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3`),c=B(`div`,`persona-flex-shrink-0 persona-mt-0.5`);c.setAttribute(`data-approval-icon`,`true`);let l=r.status===`denied`?u.ShieldX:r.status===`timeout`?u.ShieldAlert:u.ShieldCheck,d=r.status===`approved`?`var(--persona-feedback-success, var(--persona-palette-colors-success-600))`:r.status===`denied`?`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`:r.status===`timeout`?`var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))`:i?.titleColor??`currentColor`,f=j(l,20,d,2);f&&c.appendChild(f);let p=B(`div`,`persona-flex-1 persona-min-w-0`),m=B(`div`,`persona-flex persona-items-center persona-gap-2`),h=B(`span`,`persona-text-sm persona-font-medium persona-text-persona-primary`);if(i?.titleColor&&(h.style.color=i.titleColor),h.textContent=i?.title??`Approval Required`,m.appendChild(h),!a){let e=B(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium`);e.setAttribute(`data-approval-status`,r.status),r.status===`approved`?(e.style.backgroundColor=`var(--persona-palette-colors-success-100)`,e.style.color=`var(--persona-palette-colors-success-700)`,e.textContent=`Approved`):r.status===`denied`?(e.style.backgroundColor=`var(--persona-palette-colors-error-100)`,e.style.color=`var(--persona-palette-colors-error-700)`,e.textContent=`Denied`):r.status===`timeout`&&(e.style.backgroundColor=`var(--persona-palette-colors-warning-100)`,e.style.color=`var(--persona-palette-colors-warning-700)`,e.textContent=r.status===`timeout`&&r.interrupted?`Interrupted`:`Timeout`),m.appendChild(e)}if(p.appendChild(m),r.status===`timeout`&&r.interrupted){let e=B(`p`,`persona-text-sm`);e.textContent=k,p.appendChild(e)}let g=r.toolType===`webmcp`||r.toolName.startsWith(`webmcp:`)?pv(r.toolName):void 0,_=i?.formatDescription?.({toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...g?{displayTitle:g}:{},...r.reason?{reason:r.reason}:{}}),v=!r.toolName,y=_||(v?r.description:`The assistant wants to use “${g??hv(r.toolName)}”.`),b=B(`p`,`persona-text-sm persona-mt-0.5 persona-text-persona-muted`);if(b.setAttribute(`data-approval-summary`,`true`),i?.descriptionColor&&(b.style.color=i.descriptionColor),b.textContent=y,p.appendChild(b),r.reason){let e=B(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);e.setAttribute(`data-approval-reason`,`true`),i?.reasonColor?e.style.color=i.reasonColor:i?.descriptionColor&&(e.style.color=i.descriptionColor);let t=B(`span`,`persona-font-medium`);t.textContent=`${i?.reasonLabel??`Agent's stated reason:`} `,e.appendChild(t),e.appendChild(document.createTextNode(r.reason)),p.appendChild(e)}let x=i?.detailsDisplay??`collapsed`,S=!!r.description&&!v,C=S||!!r.parameters;if(x!==`hidden`&&C){let a=_v(e.id,n,t),o=B(`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`);o.type=`button`,o.setAttribute(`data-expand-header`,`true`),o.setAttribute(`data-bubble-type`,`approval`),i?.descriptionColor&&(o.style.color=i.descriptionColor);let s=B(`span`);s.setAttribute(`data-approval-details-label`,`true`);let c=B(`span`,`persona-inline-flex persona-items-center`);c.setAttribute(`data-approval-details-chevron`,`true`),o.append(s,c),vv(o,a,t),p.appendChild(o);let l=B(`div`);if(l.setAttribute(`data-approval-details`,`true`),l.style.display=a?``:`none`,S){let e=B(`p`,`persona-text-sm persona-mt-1 persona-text-persona-muted`);i?.descriptionColor&&(e.style.color=i.descriptionColor),e.textContent=r.description,l.appendChild(e)}if(r.parameters){let e=B(`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`);i?.parameterBackgroundColor&&(e.style.backgroundColor=i.parameterBackgroundColor),i?.parameterTextColor&&(e.style.color=i.parameterTextColor),e.style.fontSize=`0.75rem`,e.style.lineHeight=`1rem`,e.textContent=sn(r.parameters),l.appendChild(e)}p.appendChild(l)}if(a){let e=B(`div`,`persona-flex persona-gap-2 persona-mt-2`);e.setAttribute(`data-approval-buttons`,`true`);let t=B(`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`);t.type=`button`,t.style.backgroundColor=i?.approveButtonColor??`var(--persona-approval-approve-bg)`,t.style.color=i?.approveButtonTextColor??`var(--persona-button-primary-fg)`,t.setAttribute(`data-approval-action`,`approve`);let n=j(u.ShieldCheck,14,i?.approveButtonTextColor??`var(--persona-button-primary-fg)`,2);n&&(n.style.marginRight=`4px`,t.appendChild(n));let r=document.createTextNode(i?.approveLabel??`Approve`);t.appendChild(r);let a=B(`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`);a.type=`button`,a.style.backgroundColor=i?.denyButtonColor??`transparent`,a.style.color=i?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,a.style.border=`1px solid ${i?.denyButtonTextColor?i.denyButtonTextColor:`var(--persona-palette-colors-error-200)`}`,a.setAttribute(`data-approval-action`,`deny`);let o=j(u.ShieldX,14,i?.denyButtonTextColor??`var(--persona-feedback-error, var(--persona-palette-colors-error-600))`,2);o&&(o.style.marginRight=`4px`,a.appendChild(o));let s=document.createTextNode(i?.denyLabel??`Deny`);a.appendChild(s),e.append(t,a),p.appendChild(e)}return s.append(c,p),o.appendChild(s),o}})),Sv,Cv,wv,Tv,Ev,Dv,Ov,kv,Av,jv,Mv=o((()=>{H(),A(),mv(),ee(),Tn(),E(),Hs(),xv(),Sv=()=>({keyHandlers:/* @__PURE__ */ new Map,popovers:/* @__PURE__ */ new Map,pendingOrder:[],latestPendingApprovalId:null}),Cv=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener(`keydown`,n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},wv=(e,t)=>{Cv(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)},Tv=e=>e?.approval===!1?void 0:e?.approval,Ev=(e,t,n)=>{let r=n?.detailsDisplay??`collapsed`;return t.get(e)??r===`expanded`},Dv=e=>{let t=B(`span`,`persona-approval-kbd`);return t.textContent=e,t},Ov=(e,t)=>{let n=B(`span`,`persona-approval-title`);t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType===`webmcp`||e.toolName.startsWith(`webmcp:`)?pv(e.toolName):void 0,i=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??``,parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(i)return n.textContent=i,n;let a=r??hv(e.toolName),o=e.toolType&&e.toolType!==`webmcp`?e.toolType:null;n.append(`The assistant wants to use `);let s=document.createElement(`strong`);if(s.textContent=a,n.appendChild(s),o){n.append(` from `);let e=document.createElement(`strong`);e.textContent=o,n.appendChild(e)}return n},kv=e=>{let t=B(`div`,`persona-approval-resolved`),n=j(u.Ban,15,`currentColor`,2);n&&t.appendChild(n);let r=B(`span`,`persona-approval-resolved-name`);r.textContent=e.toolName?hv(e.toolName):`Tool`;let i=e.status===`timeout`&&e.interrupted?` approval expired. ${k}`:e.status===`timeout`?` timed out`:` denied`;return t.appendChild(V(`span`,{className:`persona-approval-resolved-text`},r,i)),t},Av=(e,t,n,r,i,a,o,s,c=!1)=>{let l=B(`div`,`persona-approval-card persona-shadow-sm`);l.id=`bubble-${n.id}`,l.setAttribute(`data-message-id`,n.id),l.setAttribute(`data-bubble-type`,`approval`),i?.backgroundColor&&(l.style.background=i.backgroundColor),i?.borderColor&&(l.style.borderColor=i.borderColor),i?.shadow!==void 0&&(l.style.boxShadow=i.shadow.trim()===``?`none`:i.shadow);let d=i?.detailsDisplay??`collapsed`,f=!!r.description&&d!==`hidden`,p=r.parameters!=null&&d!==`hidden`&&!c,m=f||p,h=m&&Ev(n.id,t,i),g=i?.showDetailsLabel??`Show details`,_=i?.hideDetailsLabel??`Hide details`,v=B(`button`,`persona-approval-head`);v.type=`button`,m?(v.setAttribute(`data-action`,`toggle-params`),v.setAttribute(`aria-expanded`,h?`true`:`false`),v.setAttribute(`aria-label`,h?_:g)):v.setAttribute(`data-static`,`true`);let y=B(`span`,`persona-approval-logo`),b=j(u.ShieldCheck,16,`currentColor`,2);b&&y.appendChild(b),v.appendChild(y);let x=Ov(r,i);if(m){let e=B(`span`,`persona-approval-toggle`);e.setAttribute(`aria-hidden`,`true`);let t=j(u.ChevronDown,14,`currentColor`,2);t&&e.appendChild(t),x.append(` `),x.appendChild(e)}v.appendChild(x),l.appendChild(v);let S=B(`div`,`persona-approval-body`);if(m){let e=B(`div`,`persona-approval-details`);if(e.setAttribute(`data-role`,`params`),e.hidden=!h,f){let t=B(`p`,`persona-approval-desc`);i?.descriptionColor&&(t.style.color=i.descriptionColor),t.textContent=r.description,e.appendChild(t)}if(p){let t=B(`pre`,`persona-approval-params`);i?.parameterBackgroundColor&&(t.style.background=i.parameterBackgroundColor),i?.parameterTextColor&&(t.style.color=i.parameterTextColor),t.textContent=sn(r.parameters),e.appendChild(t)}S.appendChild(e)}if(c){let e=B(`div`,`persona-approval-call`);e.setAttribute(`data-role`,`raw-call`);let t=B(`code`,`persona-approval-tool-name`);if(t.textContent=r.toolName,e.appendChild(t),r.parameters!=null){let t=B(`pre`,`persona-approval-params`);i?.parameterBackgroundColor&&(t.style.background=i.parameterBackgroundColor),i?.parameterTextColor&&(t.style.color=i.parameterTextColor),t.textContent=sn(r.parameters),e.appendChild(t)}S.appendChild(e)}if(r.reason){let e=B(`p`,`persona-approval-reason`);i?.reasonColor?e.style.color=i.reasonColor:i?.descriptionColor&&(e.style.color=i.descriptionColor);let t=B(`span`,`persona-approval-reason-label`);t.textContent=`${i?.reasonLabel??`Agent's stated reason:`} `,e.append(t,document.createTextNode(r.reason)),S.appendChild(e)}let C=B(`div`,`persona-approval-actions`),w=null,T=e=>{i?.approveButtonColor&&(e.style.background=i.approveButtonColor),i?.approveButtonTextColor&&(e.style.color=i.approveButtonTextColor)},E=B(`button`,`persona-approval-deny`);if(E.type=`button`,E.setAttribute(`data-action`,`deny`),i?.denyButtonColor&&(E.style.background=i.denyButtonColor),i?.denyButtonTextColor&&(E.style.color=i.denyButtonTextColor),E.append(i?.denyLabel??`Deny`),s){let t=B(`div`,`persona-approval-split`),r=B(`button`,`persona-approval-primary`);r.type=`button`,r.setAttribute(`data-action`,`always`),T(r),r.append(i?.approveLabel??`Always allow`,Dv(`⏎`));let o=B(`button`,`persona-approval-caret`);o.type=`button`,o.setAttribute(`data-action`,`toggle-menu`),o.setAttribute(`aria-label`,`More options`),T(o);let s=j(u.ChevronDown,15,`currentColor`,2);s&&o.appendChild(s),t.append(r,o),C.append(t,E),E.append(Dv(`Esc`));let c=B(`div`,`persona-approval-menu`),l=B(`button`,`persona-approval-menu-item`);l.type=`button`,l.append(`Allow once`,Dv(`⌘⏎`)),c.appendChild(l),w=Rs({anchor:t,content:c,placement:`bottom-start`,matchAnchorWidth:!0}),e.popovers.set(n.id,w),l.addEventListener(`click`,()=>{wv(e,n.id),a()})}else{let e=B(`button`,`persona-approval-primary persona-approval-primary--solo`);e.type=`button`,e.setAttribute(`data-action`,`allow`),T(e),e.append(i?.approveLabel??`Allow`),C.append(e,E)}return S.appendChild(C),l.appendChild(S),l.addEventListener(`click`,r=>{let i=r.target instanceof Element?r.target.closest(`[data-action]`):null;if(!i)return;let s=i.getAttribute(`data-action`);if(s===`toggle-params`){let e=l.querySelector(`[data-role="params"]`);if(e){let r=!!e.hidden;e.hidden=!r,v.setAttribute(`aria-expanded`,r?`true`:`false`),v.setAttribute(`aria-label`,r?_:g),t.set(n.id,r)}}else s===`toggle-menu`?w?.toggle():s===`always`?(wv(e,n.id),a({remember:!0})):s===`allow`?(wv(e,n.id),a()):s===`deny`&&(wv(e,n.id),o())}),l},jv=(e=/* @__PURE__ */ new Map)=>{let t=Sv();return{plugin:{id:`persona-built-in-approval`,renderApproval:({message:n,approve:r,deny:i,config:a})=>{let o=n?.approval;if(!o)return null;let s=Tv(a);if(o.status!==`pending`){if(wv(t,n.id),o.status===`approved`){let e=document.createElement(`div`);return e.style.display=`none`,e}return kv(o)}Cv(t,n.id);let c=!!a?.clientToken,l=s?.enableAlwaysAllow===!0,u=Av(t,e,n,o,s,r,i,l,c);if(l){t.pendingOrder.includes(n.id)||t.pendingOrder.push(n.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let e=e=>{zs(e)||n.id===t.latestPendingApprovalId&&(e.key===`Escape`||e.key===`Enter`)&&(e.preventDefault(),e.stopImmediatePropagation(),wv(t,n.id),e.key===`Escape`?i():e.metaKey||e.ctrlKey?r():r({remember:!0}))};t.keyHandlers.set(n.id,e),document.addEventListener(`keydown`,e)}return u}},teardown:()=>{for(let e of[...t.keyHandlers.keys(),...t.popovers.keys()])wv(t,e);t.latestPendingApprovalId=null}}}})),Nv=o((()=>{xv(),Mv(),mv()})),Pv=/* @__PURE__ */ s({createApprovalBubble:()=>bv,createBuiltInApprovalPlugin:()=>jv,humanizeToolName:()=>hv,initApprovalUi:()=>fv,updateApprovalDetailsUI:()=>yv}),Fv=o((()=>{Nv()}));Pe();const{setLoader:Iv,load:Lv,provide:Rv,getSync:zv}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Fv(),Pv))}),Bv=Lv,Vv=zv;function Hv(e,t){t&&t.split(/\s+/).forEach(t=>t&&e.classList.add(t))}function Uv(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 Wv(e,t){return(t&&Uv(e,t))??Uv(e,ny)??ry}function Gv(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function Kv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function qv(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}.${String(t.getMilliseconds()).padStart(3,`0`)}`}function Jv(e,t){try{let n=JSON.parse(e);if(typeof n!=`object`||!n)return null;for(let e of t){let t=e.split(`.`),r=n;for(let e of t)if(r&&typeof r==`object`&&r)r=r[e];else{r=void 0;break}if(typeof r==`string`&&r.trim())return r.trim()}}catch{}return null}function Yv(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 Xv(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 Zv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?`-- tok/s`:`${e.tokensPerSecond.toFixed(1)} tok/s`}function Qv(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(` · `)}function $v(e,t,n){let r,i;try{i=JSON.parse(e.payload),r=JSON.stringify(i,null,2)}catch{i=e.payload,r=e.payload}let a=t.find(e=>e.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let t=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>o(),parsedPayload:i});if(t)return t}return o();function o(){let e=B(`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]`),t=B(`pre`,`persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono`);return t.textContent=r,e.appendChild(t),e}}function ey(e,t,n,r,i,a,o,s){let c=i.has(e.id),l=B(`div`,`persona-border-b persona-border-persona-divider persona-text-xs`);Hv(l,r.classNames?.eventRow);let d=o.find(e=>e.renderEventStreamRow);if(d?.renderEventStreamRow&&s){let n=d.renderEventStreamRow({event:e,index:t,config:s,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(n)return l.appendChild(n),l}return l.appendChild(f()),l;function f(){let i=B(`div`,``),a=B(`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`);a.setAttribute(`data-event-id`,e.id);let l=B(`span`,`persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center`),d=j(c?u.ChevronDown:u.ChevronRight,`14px`,`currentColor`,2);d&&l.appendChild(d);let f=B(`span`,`persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]`);f.textContent=(r.timestampFormat??`relative`)===`relative`?Kv(e.timestamp,n):qv(e.timestamp);let p=null;r.showSequenceNumbers!==!1&&(p=B(`span`,`persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right`),p.textContent=String(t+1));let m=Wv(e.type,r.badgeColors),h=B(`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`);h.style.backgroundColor=m.bg,h.style.color=m.text,h.style.borderColor=Gv(m.text),h.textContent=e.type;let g=r.descriptionFields??iy,_=Jv(e.payload,g),v=null;_&&(v=B(`span`,`persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0`),v.textContent=_);let y=B(`div`,`persona-flex-1 persona-min-w-0`),b=B(`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`),x=j(u.Clipboard,`12px`,`currentColor`,1.5);return x&&b.appendChild(x),b.addEventListener(`click`,async t=>{t.stopPropagation(),await Yv(Xv(e)),b.innerHTML=``;let n=j(u.Check,`12px`,`currentColor`,1.5);n&&b.appendChild(n),setTimeout(()=>{b.innerHTML=``;let e=j(u.Clipboard,`12px`,`currentColor`,1.5);e&&b.appendChild(e)},1500)}),a.appendChild(l),a.appendChild(f),p&&a.appendChild(p),a.appendChild(h),v&&a.appendChild(v),a.appendChild(y),a.appendChild(b),i.appendChild(a),c&&i.appendChild($v(e,o,s)),i}}function ty(e){let{buffer:t,getFullHistory:n,onClose:r,config:i,plugins:a=[],getThroughput:o}=e,s=e.renderIconByName??(()=>null),c=i?.features?.scrollToBottom,l=c?.enabled!==!1,d=c?.iconName??`arrow-down`,f=c?.label??``,p=i?.features?.eventStream??{},m=a.find(e=>e.renderEventStreamView);if(m?.renderEventStreamView&&i){let e=m.renderEventStreamView({config:i,events:t.getAll(),defaultRenderer:()=>h().element,onClose:r});if(e)return{element:e,update:()=>{},destroy:()=>{}}}return h();function h(){let e=p.classNames,c=B(`div`,`persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0`);Hv(c,e?.panel);let m=[],h=``,g=``,_=null,v=[],y={},b=0,x=Dm(),S=0,C=0,w=!1,T=null,E=!1,D=0,O=/* @__PURE__ */ new Set,k=/* @__PURE__ */ new Map,A=``,ee=``,M=null,N,P,te,ne,re=null,F=null,ie=null;function ae(){let t=B(`div`,`persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0`),n=B(`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(Hv(n,e?.headerBar),o){F=B(`div`,`persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap`),F.style.cursor=`help`,re=B(`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`),re.textContent=`-- tok/s`,ie=B(`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`),ie.style.display=`none`,ie.style.pointerEvents=`none`;let e=F,n=ie;F.addEventListener(`mouseenter`,()=>{if(!n.textContent)return;let r=e.getBoundingClientRect(),i=t.getBoundingClientRect();n.style.left=`${r.left-i.left}px`,n.style.top=`${r.bottom-i.top+4}px`,n.style.display=`block`}),F.addEventListener(`mouseleave`,()=>{n.style.display=`none`}),F.appendChild(re)}let r=B(`div`,`persona-flex-1`);N=B(`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 i=B(`option`,``);i.value=``,i.textContent=`All events (0)`,N.appendChild(i),P=B(`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`),P.type=`button`,P.title=`Copy All`;let a=j(u.ClipboardCopy,`12px`,`currentColor`,1.5);a&&P.appendChild(a);let s=B(`span`,`persona-event-copy-all persona-text-xs`);s.textContent=`Copy All`,P.appendChild(s),F&&n.appendChild(F),n.appendChild(r),n.appendChild(N),n.appendChild(P);let c=B(`div`,`persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface`);Hv(c,e?.searchBar);let l=j(u.Search,`14px`,`var(--persona-muted, #9ca3af)`,1.5),d=B(`span`,`persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center`);l&&d.appendChild(l),te=B(`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`),Hv(te,e?.searchInput),te.type=`text`,te.placeholder=`Search event payloads...`,ne=B(`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`),ne.type=`button`,ne.style.display=`none`;let f=j(u.X,`12px`,`currentColor`,2);return f&&ne.appendChild(f),c.appendChild(d),c.appendChild(te),c.appendChild(ne),t.appendChild(n),t.appendChild(c),ie&&t.appendChild(ie),t}let oe,se=a.find(e=>e.renderEventStreamToolbar);oe=se?.renderEventStreamToolbar&&i?se.renderEventStreamToolbar({config:i,defaultRenderer:()=>ae(),eventCount:t.getSize(),filteredCount:0,onFilterChange:e=>{h=e,ve(),z()},onSearchChange:e=>{g=e,ve(),z()}})??ae():ae();let ce=B(`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`);ce.style.display=`none`;function le(){if(!o||!re||!F)return;let e=o(),t=Zv(e);re.textContent=t;let n=Qv(e);ie&&(ie.textContent=n,n||(ie.style.display=`none`)),F.setAttribute(`aria-label`,n?`Throughput: ${t}, ${n}`:`Throughput: ${t}`)}let ue=B(`div`,`persona-flex-1 persona-min-h-0 persona-relative`),de=B(`div`,`persona-event-stream-list persona-overflow-y-auto persona-min-h-0`);de.style.height=`100%`;let I=B(`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`);Hv(I,e?.scrollIndicator),I.style.display=`none`,I.setAttribute(`data-persona-scroll-to-bottom-has-label`,f?`true`:`false`);let fe=s(d,`14px`,`currentColor`,2);fe&&I.appendChild(fe);let pe=B(`span`,``);pe.textContent=f,I.appendChild(pe);let me=B(`div`,`persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted`);me.style.display=`none`,ue.appendChild(de),ue.appendChild(me),ue.appendChild(I),c.setAttribute(`tabindex`,`0`),c.appendChild(oe),c.appendChild(ce),c.appendChild(ue);function he(){let e=t.getAll(),n={};for(let t of e)n[t.type]=(n[t.type]||0)+1;let r=Object.keys(n).sort(),i=r.length!==v.length||!r.every((e,t)=>e===v[t]),a=!i&&r.some(e=>n[e]!==y[e]),o=e.length!==Object.values(y).reduce((e,t)=>e+t,0);if(!i&&!a&&!o||(v=r,y=n,!N))return;let s=N.value;if(N.options[0].textContent=`All events (${e.length})`,i){for(;N.options.length>1;)N.remove(1);for(let e of r){let t=B(`option`,``);t.value=e,t.textContent=`${e} (${n[e]||0})`,N.appendChild(t)}s&&r.includes(s)?N.value=s:s&&(N.value=``,h=``)}else for(let e=1;e<N.options.length;e++){let t=N.options[e];t.textContent=`${t.value} (${n[t.value]||0})`}}function ge(){let e=t.getAll();if(h&&(e=e.filter(e=>e.type===h)),g){let t=g.toLowerCase();e=e.filter(e=>e.type.toLowerCase().includes(t)||e.payload.toLowerCase().includes(t))}return e}function _e(){return h!==``||g!==``}function ve(){b=0,S=0,x.resume(),I.style.display=`none`}function L(e){O.has(e)?O.delete(e):O.add(e),M=e;let t=de.scrollTop,n=x.isFollowing();E=!0,x.pause(),z(),de.scrollTop=t,n&&x.resume(),E=!1}function R(){return km(de,50)}function z(){C=Date.now(),w=!1,le(),he();let e=t.getEvictedCount();e>0?(ce.textContent=`${e.toLocaleString()} older events truncated`,ce.style.display=``):ce.style.display=`none`,m=ge();let n=m.length,r=t.getSize()>0;n===0&&r&&_e()?(me.textContent=g?`No events matching '${g}'`:`No events matching filter`,me.style.display=``,de.style.display=`none`):(me.style.display=`none`,de.style.display=``),P&&(P.title=_e()?`Copy Filtered (${n})`:`Copy All`),l&&!x.isFollowing()&&n>b&&(S+=n-b,pe.textContent=f?`${f}${S>0?` (${S})`:``}`:``,I.style.display=``),b=n;let o=t.getAll(),s=o.length>0?o[0].timestamp:0,c=new Set(m.map(e=>e.id));for(let e of O)c.has(e)||O.delete(e);let u=h!==A||g!==ee,d=k.size===0&&m.length>0;if(u||d||m.length===0){de.innerHTML=``,k.clear();let e=document.createDocumentFragment();for(let t=0;t<m.length;t++){let n=ey(m[t],t,s,p,O,L,a,i);k.set(m[t].id,n),e.appendChild(n)}de.appendChild(e),A=h,ee=g,M=null}else{if(M!==null){let e=k.get(M);if(e&&e.parentNode===de){let t=m.findIndex(e=>e.id===M);if(t>=0){let n=ey(m[t],t,s,p,O,L,a,i);de.insertBefore(n,e),e.remove(),k.set(M,n)}}M=null}let e=new Set(m.map(e=>e.id));for(let[t,n]of k)e.has(t)||(n.remove(),k.delete(t));for(let e=0;e<m.length;e++){let t=m[e];if(!k.has(t.id)){let n=ey(t,e,s,p,O,L,a,i);k.set(t.id,n),de.appendChild(n)}}}x.isFollowing()&&(de.scrollTop=de.scrollHeight)}function ye(){Date.now()-C>=ay?(T!==null&&(cancelAnimationFrame(T),T=null),z()):w||(w=!0,T=requestAnimationFrame(()=>{T=null,z()}))}let be=(e,t)=>{if(!P)return;P.innerHTML=``;let n=j(e,`12px`,`currentColor`,1.5);n&&P.appendChild(n);let r=B(`span`,`persona-text-xs`);r.textContent=`Copy All`,P.appendChild(r),setTimeout(()=>{P.innerHTML=``;let e=j(u.ClipboardCopy,`12px`,`currentColor`,1.5);e&&P.appendChild(e);let t=B(`span`,`persona-text-xs`);t.textContent=`Copy All`,P.appendChild(t),P.disabled=!1},t)},xe=async()=>{if(P){P.disabled=!0;try{let e;_e()?e=m:n?(e=await n(),e.length===0&&(e=t.getAll())):e=t.getAll();let r=e.map(e=>{try{return JSON.parse(e.payload)}catch{return e.payload}});await navigator.clipboard.writeText(JSON.stringify(r,null,2)),be(u.Check,1500)}catch{be(u.X,1500)}}},Se=()=>{N&&(h=N.value,ve(),z())},Ce=()=>{te&&ne&&(ne.style.display=te.value?``:`none`,_&&clearTimeout(_),_=setTimeout(()=>{g=te.value,ve(),z()},150))},we=()=>{te&&ne&&(te.value=``,g=``,ne.style.display=`none`,_&&clearTimeout(_),ve(),z())},Te=()=>{if(E)return;let e=de.scrollTop,{action:t,nextLastScrollTop:n}=Am({following:x.isFollowing(),currentScrollTop:e,lastScrollTop:D,nearBottom:R(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});D=n,t===`resume`?(x.resume(),S=0,I.style.display=`none`):t===`pause`&&(x.pause(),l&&(pe.textContent=f,I.style.display=``))},Ee=e=>{let t=jm({following:x.isFollowing(),deltaY:e.deltaY,nearBottom:R(),resumeWhenNearBottom:!0});t===`pause`?(x.pause(),l&&(pe.textContent=f,I.style.display=``)):t===`resume`&&(x.resume(),S=0,I.style.display=`none`)},De=()=>{l&&(de.scrollTop=de.scrollHeight,x.resume(),S=0,I.style.display=`none`)},Oe=e=>{let t=e.target;if(!t||t.closest(`button`))return;let n=t.closest(`[data-event-id]`);if(!n)return;let r=n.getAttribute(`data-event-id`);r&&L(r)},ke=e=>{(e.metaKey||e.ctrlKey)&&e.key===`f`?(e.preventDefault(),te?.focus(),te?.select()):e.key===`Escape`&&(te&&document.activeElement===te?(we(),te.blur(),c.focus()):r&&r())};P&&P.addEventListener(`click`,xe),N&&N.addEventListener(`change`,Se),te&&te.addEventListener(`input`,Ce),ne&&ne.addEventListener(`click`,we),de.addEventListener(`scroll`,Te),de.addEventListener(`wheel`,Ee,{passive:!0}),de.addEventListener(`click`,Oe),I.addEventListener(`click`,De),c.addEventListener(`keydown`,ke);function Ae(){_&&clearTimeout(_),T!==null&&(cancelAnimationFrame(T),T=null),w=!1,k.clear(),P&&P.removeEventListener(`click`,xe),N&&N.removeEventListener(`change`,Se),te&&te.removeEventListener(`input`,Ce),ne&&ne.removeEventListener(`click`,we),de.removeEventListener(`scroll`,Te),de.removeEventListener(`wheel`,Ee),de.removeEventListener(`click`,Oe),I.removeEventListener(`click`,De),c.removeEventListener(`keydown`,ke)}return{element:c,update:ye,destroy:Ae}}}var ny,ry,iy,ay,oy=o((()=>{H(),ee(),ny={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)`}},ny.execution_error=ny.error,ny.execution_=ny.flow_,ny.turn_=ny.agent_,ny.text_=ny.agent_,ry={bg:`var(--persona-event-badge-default-bg, #f3f4f6)`,text:`var(--persona-event-badge-default-fg, #4b5563)`},iy=[`flowName`,`stepName`,`reasoningText`,`text`,`name`,`tool`,`toolName`],ay=100})),sy,cy=o((()=>{sy=class{#e;#t=0;#n=0;#r=0;#i=/* @__PURE__ */ new Set;#a;#o;constructor(e=2e3,t=null){this.#a=e,this.#e=Array(e),this.#o=t}push(e){this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#r++,this.#i.add(e.type),this.#o?.put(e)}getAll(){return this.#n===0?[]:this.#n<this.#a?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#a),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#o)return 0;let e=await this.#o.getAll();if(e.length===0)return 0;let t=e.length>this.#a?e.slice(e.length-this.#a):e;for(let e of t)this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#i.add(e.type);return this.#r=e.length,t.length}getAllFromStore(){return this.#o?this.#o.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.#n}getTotalCaptured(){return this.#r}getEvictedCount(){return this.#r-this.#n}clear(){this.#e=Array(this.#a),this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.destroy()}getEventTypes(){return Array.from(this.#i)}}})),ly,uy=o((()=>{ly=class{#e=null;#t=[];#n=!1;#r=!1;#i;#a;constructor(e=`persona-event-stream`,t=`events`){this.#i=e,this.#a=t}open(){return new Promise((e,t)=>{try{let n=indexedDB.open(this.#i,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#a)||e.createObjectStore(this.#a,{keyPath:`id`}).createIndex(`timestamp`,`timestamp`,{unique:!1})},n.onsuccess=()=>{this.#e=n.result,e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}put(e){!this.#e||this.#r||(this.#t.push(e),this.#n||(this.#n=!0,queueMicrotask(()=>this.#o())))}putBatch(e){if(!(!this.#e||this.#r||e.length===0))try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.#e)e([]);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).index(`timestamp`).getAll();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}getCount(){return new Promise((e,t)=>{if(!this.#e)e(0);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).count();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}clear(){return new Promise((e,t)=>{if(!this.#e)e();else{this.#t=[];try{let n=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a).clear();n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}}})}close(){this.#e&&=(this.#e.close(),null)}destroy(){return this.#r=!0,this.#t=[],this.close(),new Promise((e,t)=>{try{let n=indexedDB.deleteDatabase(this.#i);n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}#o(){if(this.#n=!1,!this.#e||this.#r||this.#t.length===0)return;let e=this.#t;this.#t=[];try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}}}));function dy(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function fy(e,t){if(!(e<=0||t===void 0||t<_y))return e/(t/1e3)}function py(e,t){return typeof t.type==`string`?t.type:e}function my(e){let t=Sy(e,`tokens`)??Sy(e,`totalTokens`);return t?xy(t.output):void 0}function hy(e){return xy(e.durationMs)}function gy(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}var _y,vy,yy,by,xy,Sy,Cy,wy=o((()=>{_y=250,vy=/* @__PURE__ */ new Set([`step_start`,`turn_start`]),yy=/* @__PURE__ */ new Set([`step_complete`,`turn_complete`]),by=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xy=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Sy=(e,t)=>{let n=e[t];return by(n)?n:void 0},Cy=class{#e={status:`idle`};#t=null;constructor(e=gy){this.now=e}getMetric(){let e=this.#t;if(e&&this.#e.status===`running`&&e.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.#e,durationMs:t,tokensPerSecond:fy(this.#e.outputTokens,t)}}return this.#e}reset(){this.#t=null,this.#e={status:`idle`}}#n(e){this.#t={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.#e={status:`running`}}processEvent(e,t){if(!by(t)){e===`execution_error`&&this.#t&&(this.#t=null,this.#e={status:`error`});return}let n=py(e,t),r=this.now();if(n===`execution_start`)this.#n(r);else if(vy.has(n))this.#t||this.#n(r);else if(n===`text_delta`){let e=typeof t.delta==`string`?t.delta:``;if(!e)return;this.#t||this.#n(r);let n=this.#t;n.firstDeltaAt??=r,n.visibleCharCount+=e.length;let i=n.exactOutputTokens+dy(n.visibleCharCount),a=r-n.firstDeltaAt;this.#e={status:`running`,tokensPerSecond:fy(i,a),outputTokens:i,durationMs:a,source:n.exactOutputTokens>0?`usage`:`estimate`}}else if(yy.has(n)){if(!this.#t)return;let e=this.#t,n=my(t);n!==void 0&&(e.exactOutputTokens+=n,e.visibleCharCount=0);let i=e.exactOutputTokens>0,a=e.exactOutputTokens+dy(e.visibleCharCount),o=this.#r(e,t,r);this.#e={status:`running`,tokensPerSecond:fy(a,o),outputTokens:a,durationMs:o,source:i?`usage`:`estimate`}}else if(n===`execution_complete`){if(!this.#t)return;let e=this.#t,n=my(t),i=n??e.exactOutputTokens+dy(e.visibleCharCount),a=n!==void 0||e.exactOutputTokens>0?`usage`:`estimate`,o=this.#r(e,t,r);this.#e={status:`complete`,tokensPerSecond:fy(i,o),outputTokens:i,durationMs:o,source:a},this.#t=null}else if(n===`execution_error`||n===`error`&&t.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:`error`}}}#r(e,t,n){let r=e.firstDeltaAt===void 0?void 0:n-e.firstDeltaAt;return r!==void 0&&r>=_y?r:hy(t)??n-e.startedAt}}})),Ty=o((()=>{oy(),cy(),uy(),wy()})),Ey=/* @__PURE__ */ s({EventStreamBuffer:()=>sy,EventStreamStore:()=>ly,ThroughputTracker:()=>Cy,createEventStreamView:()=>ty}),Dy=o((()=>{Ty()}));Pe();const{setLoader:Oy,load:ky}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Dy(),Ey))}),Ay=ky;var jy,My,Ny=o((()=>{jy=class{constructor(){this.components=/* @__PURE__ */ new Map,this.#e=/* @__PURE__ */ new Map}#e;register(e,t,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),n?this.#e.set(e,n):this.#e.delete(e)}unregister(e){this.components.delete(e),this.#e.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#e.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}},My=new jy}));function Py(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??``}function Fy(e){let t=Py(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n+1).toLowerCase()}function Iy(e){if(typeof e!=`string`)return``;let t=e.indexOf(`
|
|
259
259
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let n=e.slice(t+1),r=n.lastIndexOf(`
|
|
260
|
-
`);return(r===-1?n:n.slice(0,r)).split("```").join("```")}function
|
|
261
|
-
`).length,p=e.artifactType===`markdown`?e.file:void 0,m={artifactId:o,artifactType:e.artifactType,title:e.title,typeLabel:r,file:p,chars:d,lines:f,elapsedMs:c,content:()=>l?``:u,surface:n};try{let e=a(m);return typeof e==`string`?{label:e}:e&&typeof e==`object`&&typeof e.label==`string`?{label:e.label,detail:typeof e.detail==`string`?e.detail:void 0}:{label:i}}catch{return{label:i}}}function
|
|
260
|
+
`);return(r===-1?n:n.slice(0,r)).split("```").join("```")}function Ly(e){let t=Fy(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 Ry(e){switch(Ly(e)){case`html`:return`HTML`;case`svg`:return`SVG`;case`markdown`:return`Markdown`;default:{let t=Fy(e.path);return t?t.toUpperCase():`File`}}}function zy(e){let t=e.markdown??``;return e.file?{filename:Py(e.file.path)||`artifact`,mime:e.file.mimeType||`application/octet-stream`,content:Iy(t)}:{filename:`${e.title||`artifact`}.md`,mime:`text/markdown`,content:t}}function By(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e.filename,r.click(),URL.revokeObjectURL(n)}var Vy=o((()=>{}));function Hy(e,t){let n=t?.documentChrome??!1,r;if(typeof e.icon==`function`){r=e.showLabel?B(`button`,`persona-label-btn persona-label-btn--sm `+Wy+(n?` persona-artifact-doc-copy-btn`:``)):B(`button`,`persona-icon-btn `+Wy+(n?` persona-artifact-doc-icon-btn`:``)),r.type=`button`,r.setAttribute(`aria-label`,e.label),r.title=e.label;try{let t=e.icon();t&&r.appendChild(t)}catch{}if(e.showLabel){let t=B(`span`);t.textContent=e.label,r.appendChild(t)}}else r=e.showLabel||!e.icon?bg({icon:e.icon,label:e.label,className:Wy+(n?` persona-artifact-doc-copy-btn`:``)}):yg({icon:e.icon,label:e.label,className:Wy+(n?` persona-artifact-doc-icon-btn`:``)});return t?.onClick&&r.addEventListener(`click`,t.onClick),r}function Uy(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 Wy,Gy=o((()=>{wg(),H(),Wy=`persona-artifact-custom-action-btn`}));function Ky(e){let t=document.createElementNS(qy,`svg`);t.setAttribute(`class`,Me(`persona-spinner`,e)),t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`focusable`,`false`);let n=document.createElementNS(qy,`circle`);n.setAttribute(`class`,`persona-spinner-track`),n.setAttribute(`cx`,`12`),n.setAttribute(`cy`,`12`),n.setAttribute(`r`,`9`);let r=document.createElementNS(qy,`circle`);return r.setAttribute(`class`,`persona-spinner-arc`),r.setAttribute(`cx`,`12`),r.setAttribute(`cy`,`12`),r.setAttribute(`r`,`9`),t.appendChild(n),t.appendChild(r),t}var qy,Jy=o((()=>{H(),qy=`http://www.w3.org/2000/svg`}));function Yy(e,t,n){let r=n?.loadingAnimation??`shimmer`,i=n?.loadingAnimationDuration??2e3;r===`none`?e.textContent=t:r===`pulse`?(e.setAttribute(`data-preserve-animation`,`true`),e.classList.add(`persona-tool-loading-pulse`),e.style.setProperty(`--persona-tool-anim-duration`,`${i}ms`),e.textContent=t):(e.setAttribute(`data-preserve-animation`,`true`),e.classList.add(`persona-tool-loading-${r}`),e.style.setProperty(`--persona-tool-anim-duration`,`${i}ms`),r===`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)),Y_(e,t,0))}var Xy=o((()=>{X_()}));function Zy(e){e&&ab.delete(e)}function Qy(e){let t=e.artifactType===`markdown`?e.file:void 0;return t?Ry(t):e.artifactType===`component`?`Component`:`Document`}function $y(e,t,n){let r=Qy(e),i=`Generating ${r.toLowerCase()}...`,a=t?.statusLabel;if(typeof a==`string`)return{label:a};if(typeof a!=`function`)return{label:i};let o=e.id,s=ab.get(o);e.status!==`complete`&&s===void 0&&(s=ob(),ab.set(o,s));let c=s===void 0?0:Math.max(0,ob()-s),l=e.artifactType===`component`,u=!l&&typeof e.markdown==`string`?e.markdown:``,d=l?0:u.length,f=l||u===``?0:u.split(`
|
|
261
|
+
`).length,p=e.artifactType===`markdown`?e.file:void 0,m={artifactId:o,artifactType:e.artifactType,title:e.title,typeLabel:r,file:p,chars:d,lines:f,elapsedMs:c,content:()=>l?``:u,surface:n};try{let e=a(m);return typeof e==`string`?{label:e}:e&&typeof e==`object`&&typeof e.label==`string`?{label:e.label,detail:typeof e.detail==`string`?e.detail:void 0}:{label:i}}catch{return{label:i}}}function eb(e){e.className=nb,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 tb(e,t,n){let r=e.querySelector(`:scope > .${nb}`);r||(r=B(`span`,nb),e.appendChild(r)),r.getAttribute(ib)!==t.label&&(eb(r),Yy(r,t.label,n),r.setAttribute(ib,t.label));let i=e.querySelector(`:scope > .${rb}`),a=t.detail;a?(i||(i=B(`span`,rb),e.appendChild(i)),i.textContent!==a&&(i.textContent=a)):i&&i.remove()}var nb,rb,ib,ab,ob,sb=o((()=>{H(),Vy(),Xy(),nb=`persona-artifact-status-label`,rb=`persona-artifact-status-detail`,ib=`data-artifact-status-label`,ab=/* @__PURE__ */ new Map,ob=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}));function cb(e,t){let n=(e||``).trim().toLowerCase();if(n&&vb[n])return vb[n];if(t){let e=t.lastIndexOf(`.`);if(e>=0){let n=t.slice(e+1).toLowerCase();if(vb[n])return vb[n]}}return null}function lb(e,t){let n=[],r=0,i=0,a=t=>{t>i&&n.push({type:`plain`,value:e.slice(i,t)})};for(;r<e.length;){let o=!1;for(let s of t){s.re.lastIndex=r;let t=s.re.exec(e);if(t&&t.index===r&&t[0].length>0){a(r);let e=s.map?s.map(t[0]):s.type;n.push({type:e,value:t[0]}),r+=t[0].length,i=r,o=!0;break}}o||(r+=1)}return a(e.length),n}function ub(e){return lb(e,bb)}function db(e){let t=lb(e,xb);for(let e=0;e<t.length;e+=1){if(t[e].type!==`string`)continue;let n=e+1;for(;n<t.length&&t[n].value.trim()===``;)n+=1;let r=t[n];r&&r.value.replace(/^\s*/,``).startsWith(`:`)&&(t[e].type=`property`)}return t}function fb(e){let t=lb(e,Sb),n=``;for(let e=0;e<t.length;e+=1){let r=t[e];if(r.type===`plain`&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=e+1;for(;i<t.length&&t[i].value.trim()===``;)i+=1;let a=t[i];a&&a.value.replace(/^\s*/,``).startsWith(`:`)&&(n===``||n===`{`||n===`}`||n===`;`||n===`,`)&&(r.type=`property`)}let i=r.value.replace(/\s+$/,``);i&&(n=i[i.length-1])}return t}function pb(e){let t=[],n=(e,n)=>{n&&t.push({type:e,value:n})},r=e.length,i=0;for(;i<r;){if(e.startsWith(`<!--`,i)){let t=e.indexOf(`-->`,i+4),a=t===-1?r:t+3;n(`comment`,e.slice(i,a)),i=a;continue}if(e[i]===`<`&&e[i+1]===`!`){let t=e.indexOf(`>`,i),a=t===-1?r:t+1;n(`tag`,e.slice(i,a)),i=a;continue}if(e[i]===`<`&&/[A-Za-z/]/.test(e[i+1]||``)){let n=e.indexOf(`>`,i),a=n===-1?r:n+1,o=e.slice(i,a);for(let e of lb(o,Cb))t.push(e);i=a;let s=/^<\s*(script|style)\b/i.exec(o);if(s&&!/\/>\s*$/.test(o)){let n=s[1].toLowerCase(),a=RegExp(`</\\s*`+n+`\\s*>`,`i`).exec(e.slice(i)),o=a?i+a.index:r,c=e.slice(i,o),l=n===`script`?ub(c):fb(c);for(let e of l)t.push(e);i=o}continue}let a=e.indexOf(`<`,i);if(a===i)n(`plain`,e[i]),i+=1;else{let t=a===-1?r:a;n(`plain`,e.slice(i,t)),i=t}}return t}function mb(e,t){switch(t){case`html`:return pb(e);case`css`:return fb(e);case`js`:return ub(e);case`json`:return db(e)}}function hb(e){let t=je(),n=B(`span`,`persona-code-line`),r=(e,t)=>{if(!t)return;let r=_b[e];if(r){let e=B(`span`,r);e.textContent=t,n.appendChild(e)}else n.appendChild(document.createTextNode(t))};for(let i of e){let e=i.value.split(`
|
|
262
262
|
`);for(let a=0;a<e.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
263
|
-
`)),n=
|
|
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 Eb(e,t,n){let r=z(`div`,`persona-artifact-frame-loading`);if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return r.appendChild(i),{el:r,revealLabel:()=>{}}}catch{}let i=z(`div`,`persona-artifact-frame-loading-indicator`);i.appendChild(Iy());let a=null;return n.label!==!1&&(a=z(`div`,`persona-artifact-frame-loading-text`),a.textContent=n.label,i.appendChild(a)),r.appendChild(i),{el:r,revealLabel:()=>{a&&a.classList.add(`persona-artifact-frame-loading-text--visible`)}}}function Db(e,t,n,r,i,a){let o=null,s=0,c=!1,l=/* @__PURE__ */ new Set,u=()=>{l.forEach(e=>clearTimeout(e)),l.clear()},d=(e,t)=>{let n=setTimeout(()=>{l.delete(n),typeof document<`u`&&e()},t);l.add(n)},f=()=>{o&&o.parentElement&&o.remove(),o=null},p=()=>{if(o||c)return;let t=Eb(i,a,r);o=t.el,e.appendChild(o),s=Date.now(),r.label!==!1&&d(t.revealLabel,r.labelDelayMs)},m=()=>{o&&(o.classList.add(`persona-artifact-frame-loading--out`),d(f,jb))},h=()=>{n===null?t.removeEventListener(`load`,v):typeof window<`u`&&window.removeEventListener(`message`,_)},g=()=>{if(c||(c=!0,h(),u(),!o))return;let e=Math.max(0,r.minVisibleMs-(Date.now()-s));e>0?d(m,e):m()};function _(e){if(n===null)return;let r=e.data;r&&r.persona===`artifact-preview-ready`&&r.token===n&&e.source===t.contentWindow&&g()}function v(){let e=e=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,0)};e(()=>e(()=>g()))}return d(p,r.delayMs),d(g,r.timeoutMs),n===null?t.addEventListener(`load`,v):typeof window<`u`&&window.addEventListener(`message`,_),()=>{c=!0,u(),h(),f()}}function Ob(e,t){let{config:n}=t,r=t.registry??_b()??Sy,i=t.bodyLayout,a=n.markdown?vt(n.markdown):null,o=wt(n.sanitize),s=e,c=!1,l=e=>{let t=mt()!==null;a&&!t&&!c&&(c=!0,pt(()=>j(s)));let n=a?a(e):yt(e);return a&&t&&o?o(n):n},u=z(`div`,`persona-artifact-preview-body`),d=null,f=null,p=null,m=()=>{p&&=(p(),null),d=null,f=null},h=null,g=null,_=null,v=!1,y=()=>{h=null,g=null,_=null,v=!1},b=null,x=null,S=()=>{b=null,x=null},C=0,w=e=>typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,0),T=e=>e.scrollHeight-e.clientHeight-e.scrollTop<=40,E=e=>{if(!i)return;let t=e.scrollHeight-e.clientHeight>1,n=e.scrollHeight-e.clientHeight-e.scrollTop;e.classList.toggle(`persona-artifact-fade-top`,i.fadeTop&&t&&e.scrollTop>1),e.classList.toggle(`persona-artifact-fade-bottom`,i.fadeBottom&&t&&n>1)},D=e=>{C||=w(()=>{C=0,e.scrollTop=e.scrollHeight,E(e)})},O=(e,t,n,r)=>{let a=!!i,o=n.id+`|`+(a?`w`:`p`);if(!h||_!==o||h.parentElement!==u){m(),S(),u.replaceChildren();let e=z(`pre`,`persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary persona-code-pre`),t=z(`code`,`persona-code`);if(e.appendChild(t),a){let t=z(`div`,`persona-artifact-source-window`);if(t.appendChild(e),u.appendChild(t),i?.overflow!==`clip`&&typeof t.addEventListener==`function`){let e=()=>t.scrollHeight-t.clientHeight>1;t.addEventListener(`scroll`,()=>{T(t)&&(v=!1),E(t)},{passive:!0}),t.addEventListener(`wheel`,t=>{e()&&t.deltaY<0&&(v=!0)},{passive:!0}),t.addEventListener(`touchmove`,()=>{e()&&(v=!0)},{passive:!0})}h=t}else u.appendChild(e),h=e;g=t,_=o}let s=a?h:null;s&&(s.classList.toggle(`persona-artifact-source-window--fixed`,r),s.classList.toggle(`persona-artifact-source-window--clip`,r&&i?.overflow===`clip`));let c=!s||T(s);if(g.replaceChildren(ob(e,t?.language,t?.path)),s){let e=n.status!==`complete`;r&&e&&i?.followOutput&&!v&&c?D(s):e||(v=!1),E(s)}},k=e=>{m(),y(),S(),u.replaceChildren();let t=z(`div`,Ab);t.innerHTML=l(e),u.appendChild(t)},A=e=>{let t=e.id,r=n.features?.artifacts,i=Uy(e,r,`status-body`);if(b&&x===t&&b.parentElement===u){let e=b.querySelector(`.persona-artifact-status-view-text`);e&&Gy(e,i,r);return}m(),y(),u.replaceChildren();let a=z(`div`,`persona-artifact-status-view`),o=z(`div`,`persona-artifact-status-view-text`);Gy(o,i,r),a.appendChild(o),u.appendChild(a),b=a,x=t},j=e=>{s=e;let a=t.resolveViewMode?.(e)??i?.viewMode??`rendered`,o=e.artifactType===`markdown`?e.file:void 0,c=e.status!==`complete`;c||Vy(e.id);let l=c?i?.streamingHeight:i?.completeHeight,h=!!i&&typeof l==`number`;if(i?.streamingView===`status`&&c){A(e);return}if(o){let t=Ey(e.markdown??``),r=Dy(o),i=n.features?.artifacts?.filePreview?.enabled!==!1;if(!c&&a===`rendered`&&i&&(r===`html`||r===`svg`)){let r=e.id+`\0`+t;if(d&&f===r&&d.parentElement===u)return;y(),S(),m(),u.replaceChildren();let i=n.features?.artifacts?.filePreview,a=i?.iframeSandbox??`allow-scripts`;!i?.dangerouslyAllowSameOrigin&&a.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.`),a=a.split(/\s+/).filter(e=>e&&e!==`allow-same-origin`).join(` `));let o=Cb(i?.loading),s=z(`div`,`persona-artifact-frame`),c=z(`iframe`,`persona-artifact-iframe`);c.setAttribute(`sandbox`,a),c.setAttribute(`data-artifact-id`,e.id);let l=null;o.enabled&&o.injectReadySignal?(l=wb(),c.srcdoc=t+Tb(l)):c.srcdoc=t,s.appendChild(c),u.appendChild(s),o.enabled&&(p=Db(s,c,l,o,e.id,n)),d=s,f=r;return}if(m(),!c&&r===`markdown`&&a===`rendered`){k(t);return}O(t,{language:o.language,path:o.path},e,h);return}if(e.artifactType===`markdown`){if(a===`source`){m(),O(e.markdown??``,void 0,e,h);return}k(e.markdown??``);return}m(),y(),S(),u.replaceChildren();let g=e.component?r.get(e.component):void 0;if(g){let t={message:{id:e.id,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString()},config:n,updateProps:()=>{}};try{let n=g(e.props??{},t);if(n){u.appendChild(n);return}}catch{}}u.appendChild(Sb(e))};return j(e),{el:u,update(e){j(e)},destroy(){m()}}}var kb,Ab,jb,Mb=o((()=>{H(),Ry(),jy(),Zy(),mb(),bt(),ht(),Cy(),vb(),kb=!1,Ab=`persona-text-sm persona-leading-relaxed persona-markdown-bubble`,jb=220}));function Nb(e,t){let n=t.orientation??`horizontal`,r=n===`vertical`?`ArrowUp`:`ArrowLeft`,i=n===`vertical`?`ArrowDown`:`ArrowRight`;e.setAttribute(`role`,`tablist`);let a=[],o=!1,s=e=>{typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`,inline:`nearest`})},c=e=>{let t=e;return a.findIndex(e=>e===t||e.contains(t))},l=e=>{let n=c(e.target);if(n<0)return;let o=n;if(e.key===i)o=Math.min(n+1,a.length-1);else if(e.key===r)o=Math.max(n-1,0);else if(e.key===`Home`)o=0;else if(e.key===`End`)o=a.length-1;else return;e.preventDefault(),o!==n&&t.onSelect(o)},u=e=>{let t=c(e.target);t>=0&&s(a[t])};return e.addEventListener(`keydown`,l),e.addEventListener(`focusin`,u),{beforeRender(){o=typeof document<`u`&&e.contains(document.activeElement)},render(e,t){if(a=e,e.forEach((e,n)=>{e.setAttribute(`role`,`tab`);let r=n===t;e.setAttribute(`aria-selected`,r?`true`:`false`),e.tabIndex=r||t<0&&n===0?0:-1}),o){let n=(t>=0?e[t]:void 0)??e[0];n&&typeof n.focus==`function`&&(s(n),n.focus())}},destroy(){e.removeEventListener(`keydown`,l),e.removeEventListener(`focusin`,u)}}}var Pb=o((()=>{}));function Fb(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??`default`)===`document`,i=n?.toolbarTitle??`Artifacts`,a=n?.closeButtonLabel??`Close`,o=n?.panePadding?.trim(),s=n?.tabFadeSize?.trim(),c=e=>({start:e===!1?!1:typeof e==`object`&&e?e.start!==!1:!0,end:e===!1?!1:typeof e==`object`&&e?e.end!==!1:!0}),{start:l,end:d}=c(n?.tabFade),f=typeof document<`u`?z(`div`,`persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden`):null,p=()=>{f?.classList.add(`persona-hidden`),m.classList.remove(`persona-artifact-drawer-open`),O?.closeMenu()};f&&f.addEventListener(`click`,()=>{p(),t.onDismiss?.()});let m=z(`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`);m.setAttribute(`data-persona-theme-zone`,`artifact-pane`),r&&m.classList.add(`persona-artifact-pane-document`);let g=z(`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`);g.setAttribute(`data-persona-theme-zone`,`artifact-toolbar`),r&&g.classList.add(`persona-artifact-toolbar-document`);let _=z(`span`,`persona-text-xs persona-font-medium persona-truncate`);_.textContent=i;let v=lg({icon:`x`,label:a});v.addEventListener(`click`,()=>{p(),t.onDismiss?.()});let y=`rendered`,b=dg({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:e=>{y=e===`source`?`source`:`rendered`,we()}}),x=z(`div`,`persona-flex persona-items-center persona-gap-1 persona-shrink-0`),S=n?.documentToolbarShowCopyLabel===!0,C=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,T=!!(C&&w&&w.length>0),E=null,D,O=null;if(r&&(S||C)&&!T){if(D=S?ug({icon:`copy`,label:`Copy`,iconSize:14,className:`persona-artifact-doc-copy-btn`}):lg({icon:`copy`,label:`Copy`,className:`persona-artifact-doc-copy-btn`}),C){let e=h(u.ChevronDown,14,`currentColor`,2);e&&D.appendChild(e)}}else r&&T?(O=fg({label:`Copy`,icon:`copy`,iconSize:14,iconOnly:!S,primaryClassName:`persona-artifact-doc-copy-btn`,chevronLabel:`More copy options`,chevronClassName:`persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn`,menuItems:(w??[]).map(e=>({id:e.id,label:e.label})),position:`bottom-right`,portal:()=>m.closest(`[data-persona-root]`)??document.body,onSelect:e=>void re(e)}),E=O.element,D=O.primaryButton):r?D=lg({icon:`copy`,label:`Copy`,className:`persona-artifact-doc-icon-btn`}):(D=lg({icon:`copy`,label:`Copy`}),n?.showCopyButton!==!0&&D.classList.add(`persona-hidden`));let k=lg(r?{icon:`refresh-cw`,label:`Refresh`,className:`persona-artifact-doc-icon-btn`}:{icon:`refresh-cw`,label:`Refresh`});n?.onDocumentToolbarRefresh||k.classList.add(`persona-hidden`);let A=lg(r?{icon:`x`,label:a,className:`persona-artifact-doc-icon-btn`}:{icon:`x`,label:a}),j=lg({icon:`maximize`,label:`Expand artifacts panel`,className:`persona-artifact-expand-btn`+(r?` persona-artifact-doc-icon-btn`:``),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&j.classList.add(`persona-hidden`);let M=z(`div`,`persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions`),ee=e.features?.artifacts?.toolbarActions??[],N=()=>{let e=pe.find(e=>e.id===me)??pe[pe.length-1],t=e?.id??null,n=e?.artifactType===`markdown`?e.markdown??``:``,r=e?JSON.stringify({component:e.component,props:e.props},null,2):``,{filename:i,mime:a,content:o}=ky({title:e?.title,markdown:e?.markdown??``,file:e?.file});return{markdown:n,jsonPayload:r,id:t,file:e?.file,suggestedFilename:i,mime:a,content:o}},P=()=>{let{suggestedFilename:e,mime:t,content:n}=N();n&&Ay({filename:e,mime:t,content:n})},F=e=>{let{id:t,...n}=N();return{actionId:e,artifactId:t,...n}},te=async()=>{let e=pe.find(e=>e.id===me)??pe[pe.length-1];try{return await navigator.clipboard.writeText(yb(e)),!0}catch{return!1}},ne=null,I=()=>{ne?.();let e=D.querySelector(`svg`),t=Number(e?.getAttribute(`width`))||16,n=h(u.Check,t,`currentColor`,2);if(!e||!n)return;e.replaceWith(n);let r=D.querySelector(`span`);r&&(r.textContent=`Copied`);let i=setTimeout(()=>ne?.(),2e3);ne=()=>{clearTimeout(i),n.replaceWith(e),r&&(r.textContent=`Copy`),ne=null}};D.addEventListener(`click`,async()=>{let e=n?.onDocumentToolbarCopyMenuSelect;if(e&&T)try{if(await e(F(`primary`))===!1){await te()&&I();return}I()}catch{}else await te()&&I()});async function re(e){let t=n?.onDocumentToolbarCopyMenuSelect;try{if(t&&await t(F(e))!==!1)return;if(e===`download`){P();return}let{markdown:n,jsonPayload:r}=N();e===`markdown`||e===`md`?await navigator.clipboard.writeText(n):e===`json`||e===`source`?await navigator.clipboard.writeText(r):await navigator.clipboard.writeText(n||r),I()}catch{}}k.addEventListener(`click`,async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}we()}),A.addEventListener(`click`,()=>{p(),t.onDismiss?.()});let ie=z(`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)g.replaceChildren(),E?x.append(E,k,A):x.append(D,k,A),x.insertBefore(M,A),x.insertBefore(j,A),g.append(b.element,ie,x);else{let e=z(`div`,`persona-flex persona-items-center persona-gap-1 persona-shrink-0`);e.append(D,M,j,v),g.appendChild(_),g.appendChild(e)}o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let ae=z(`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`);s&&ae.style.setProperty(`--persona-artifact-tab-fade-size`,s);let oe=e.features?.artifacts?.renderTabBar,se=z(`div`,`persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden`),ce=Nb(ae,{onSelect:e=>t.onSelect(pe[e].id)}),le=e=>{let t=e.scrollWidth-e.clientWidth,n=t>1,r=Math.abs(e.scrollLeft);e.classList.toggle(`persona-artifact-tab-fade-start`,l&&n&&r>1),e.classList.toggle(`persona-artifact-tab-fade-end`,d&&n&&r<t-1)},L=0,R=()=>{if(L)return;let e=()=>{L=0,le(ae)};L=typeof requestAnimationFrame==`function`?requestAnimationFrame(e):setTimeout(e,0)};ae.addEventListener(`scroll`,()=>R(),{passive:!0}),typeof ResizeObserver<`u`&&new ResizeObserver(()=>le(ae)).observe(ae);let ue=z(`div`,`persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3`),de=()=>{ue.scrollLeft=0},fe=()=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(de):setTimeout(de,0)};if(o){for(let e of[ae,se])e.style.paddingLeft=o,e.style.paddingRight=o;ue.style.padding=o}m.appendChild(g),m.appendChild(ae),m.appendChild(se),m.appendChild(ue);let pe=[],me=null,he=!1,ge=!1,B=!0,V=!1,H=null,_e=``,ve=null,ye=!1,be=e=>e.artifactType===`markdown`&&e.file||r?y:`rendered`,xe=e=>{r||(e&&!ye?(g.insertBefore(b.element,_),ye=!0):!e&&ye&&(b.element.remove(),ye=!1))},Se=()=>me&&pe.find(e=>e.id===me)||pe[pe.length-1],Ce=()=>{let e=Ny(Se());if(!e){M.replaceChildren();return}let t=ee.filter(t=>t.visible===void 0||t.visible(e)).map(e=>My(e,{documentChrome:r,onClick:()=>{let t=Ny(Se());if(t)try{Promise.resolve(e.onClick(t)).catch(()=>{})}catch{}}}));M.replaceChildren(...t)},we=()=>{Ce();let n=r&&pe.length<=1,a=!!oe;if(ae.classList.toggle(`persona-hidden`,n||a),se.classList.toggle(`persona-hidden`,n||!a),a&&oe){let e=pe.map(e=>e.id).join(`|`)+` `+(me??``);if(e!==_e){_e=e;let n=oe({records:pe,selectedId:me,onSelect:t.onSelect});se.firstElementChild!==n&&se.replaceChildren(n)}}else{ce.beforeRender(),ae.replaceChildren();let e=[],n=-1;for(let[r,i]of pe.entries()){let a=z(`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`);a.type=`button`;let o=i.artifactType===`markdown`?i.file:void 0,s=o?wy(o.path):i.title||i.id.slice(0,8),c=o?.path||i.title||s;a.textContent=s,a.title=c,a.setAttribute(`aria-label`,c),i.id===me&&(a.classList.add(`persona-bg-persona-container`,`persona-border-persona-border`),n=r),a.addEventListener(`click`,()=>t.onSelect(i.id)),ae.appendChild(a),e.push(a)}if(ce.render(e,n),n>=0&&me!==H){H=me;let t=e[n];typeof t.scrollIntoView==`function`&&t.scrollIntoView({block:`nearest`,inline:`nearest`})}le(ae)}let o=me&&pe.find(e=>e.id===me)||pe[pe.length-1];if(!o){ue.replaceChildren(),ve?.destroy(),ve=null,xe(!1);return}let s=o.artifactType===`markdown`?o.file:void 0;if(xe(!!s&&Dy(s)!==`other`),r){let e=s?Oy(s):o.artifactType===`markdown`?`MD`:o.component??`Component`,t=(o.title||`Document`).trim(),n=s?wy(s.path):t.replace(/\s*·\s*MD\s*$/i,``).trim()||`Document`;ie.textContent=`${n} · ${e}`}else _.textContent=s?wy(s.path):i;ve?(ve.el.parentElement!==ue&&ue.replaceChildren(ve.el),ve.update(o)):(ve=Ob(o,{config:e,resolveViewMode:be}),ue.replaceChildren(ve.el)),ue.classList.toggle(`persona-artifact-content-flush`,!!ue.querySelector(`.persona-code-pre`))},Te=()=>{let e=pe.length>0;if(m.classList.toggle(`persona-hidden`,!e),f){let t=((typeof m.closest==`function`?m.closest(`[data-persona-root]`):null)?.classList.contains(`persona-artifact-narrow-host`)??!1)||typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches;e&&t&&he?(f.classList.remove(`persona-hidden`),m.classList.add(`persona-artifact-drawer-open`)):(f.classList.add(`persona-hidden`),m.classList.remove(`persona-artifact-drawer-open`))}},Ee=()=>{V=!1,we(),Te()};return{element:m,backdrop:f,update(e){let t=e.selectedId??e.artifacts[e.artifacts.length-1]?.id??null,n=t!==me;pe=e.artifacts,me=t,pe.length>0&&(he=!0),V=!0,B&&Ee(),n&&de()},setMobileOpen(e){he=e,!e&&f?(f.classList.add(`persona-hidden`),m.classList.remove(`persona-artifact-drawer-open`)):Te()},setExpanded(e){e!==ge&&(ge=e,fe());let t=h(e?u.Minimize:u.Maximize,16,`currentColor`,2);t&&j.replaceChildren(t);let n=e?`Collapse artifacts panel`:`Expand artifacts panel`;j.setAttribute(`aria-label`,n),j.title=n},setExpandToggleVisible(e){j.classList.toggle(`persona-hidden`,!e)},setCopyButtonVisible(e){r||D.classList.toggle(`persona-hidden`,!e)},setRefreshButtonVisible(e){k.classList.toggle(`persona-hidden`,!e)},setCustomActions(e){ee=e,Ce()},setTabFade(e){let t=c(e);(t.start!==l||t.end!==d)&&(l=t.start,d=t.end,le(ae))},setRenderTabBar(e){e!==oe&&(oe=e,_e=``,we())},setVisible(e){e!==B&&(B=e,e&&V&&Ee())},destroy(){ve?.destroy(),ve=null}}}var Ib=o((()=>{H(),jy(),Fy(),Mb(),g(),mg(),Pb()}));function Lb(e,t){let n=e.file&&typeof e.file==`object`&&!Array.isArray(e.file)?e.file:void 0,r=typeof e.title==`string`&&e.title?e.title:`Untitled artifact`,i=n?wy(n.path):r,a=typeof e.artifactId==`string`?e.artifactId:``,o=e.status===`streaming`?`streaming`:`complete`,s=typeof e.artifactType==`string`?e.artifactType:`markdown`,c=e.presentation&&typeof e.presentation==`object`&&!Array.isArray(e.presentation)?e.presentation:void 0,l=n?Oy(n):s===`component`?`Component`:`Document`,u=document.createElement(`div`);u.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`,u.tabIndex=0,u.setAttribute(`role`,`button`),u.setAttribute(`aria-label`,`Open ${i} in artifact panel`),a&&u.setAttribute(`data-open-artifact`,a);let d=document.createElement(`div`);d.className=`persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg`,d.style.border=`1px solid var(--persona-border, #e5e7eb)`,d.style.color=`var(--persona-muted, #9ca3af)`,d.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 f=document.createElement(`div`);f.className=`persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5`;let p=document.createElement(`div`);p.className=`persona-truncate persona-text-sm persona-font-medium`,p.style.color=`var(--persona-text, #1f2937)`,p.textContent=i;let m=document.createElement(`div`);if(m.className=`persona-text-xs persona-flex persona-items-center persona-gap-1.5`,m.style.color=`var(--persona-muted, #9ca3af)`,o===`streaming`){let i=t?.config?.features?.artifacts;Gy(m,Uy({id:a,artifactType:s===`component`?`component`:`markdown`,title:r,status:`streaming`,...typeof e.markdown==`string`?{markdown:e.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},i,`card`),i)}else a&&Vy(a),m.textContent=l;if(f.append(p,m),u.append(d,f),o===`complete`){let r=t?.config?.features?.artifacts?.cardActions;if(r&&r.length>0){let t={artifactId:a||null,title:i,artifactType:s,markdown:typeof e.markdown==`string`?e.markdown:void 0,file:n};for(let e of r)try{if(e.visible===void 0||e.visible(t)){let t=My(e);t.setAttribute(`data-artifact-custom-action`,e.id),t.className=`${t.className} persona-flex-shrink-0`,u.append(t)}}catch{}}let o=ug({label:`Download`,className:`persona-flex-shrink-0`});o.title=`Download ${i}`,o.setAttribute(`data-download-artifact`,a),u.append(o)}return u}var Rb,zb=o((()=>{jy(),Zy(),mg(),Fy(),Rb=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let r=typeof e.title==`string`&&e.title?e.title:`Untitled artifact`,i=typeof e.artifactId==`string`?e.artifactId:``,a=e.status===`streaming`?`streaming`:`complete`,o=n({artifact:{artifactId:i,title:r,artifactType:typeof e.artifactType==`string`?e.artifactType:`markdown`,status:a},config:t.config,defaultRenderer:()=>Lb(e,t)});if(o)return o}return Lb(e,t)}}));function Bb(e,t,n){if(t.length===0)return;let r=new Map(t.map(e=>[e.id,e]));e.querySelectorAll(`[data-artifact-inline]`).forEach(e=>{let t=Yb.get(e);if(!t)return;let i=r.get(e.getAttribute(`data-artifact-inline`)??``);i&&t(i,n)})}function Vb(e){return Yb.has(e)}function Hb(e){let t=typeof e.artifactId==`string`?e.artifactId:``,n=typeof e.title==`string`&&e.title?e.title:void 0,r=e.status===`streaming`?`streaming`:`complete`,i=e.presentation&&typeof e.presentation==`object`&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType===`component`){let a=e.componentProps,o=a&&typeof a==`object`&&!Array.isArray(a)?a:{};return{id:t,artifactType:`component`,title:n,status:r,component:typeof e.component==`string`?e.component:``,props:o,...i?{presentation:i}:{}}}let a=e.file&&typeof e.file==`object`&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:`markdown`,title:n,status:r,markdown:typeof e.markdown==`string`?e.markdown:``,...a?{file:a}:{},...i?{presentation:i}:{}}}function Ub(e){let t=e.artifactType===`markdown`?e.file:void 0;return{title:t?wy(t.path):e.title&&e.title.trim()?e.title:`Untitled artifact`,typeLabel:t?Oy(t):e.artifactType===`component`?`Component`:`Document`}}function Wb(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 Gb(e,t,n){let{swap:r,onSettled:i}=n,a=!1;try{a=typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!=`function`){r(),i();return}e.style.height=`${t}px`,e.style.overflow=`hidden`;let o=[];for(let t of Array.from(e.children))t instanceof HTMLElement&&o.push(t.animate([{opacity:1},{opacity:0}],{duration:Xb,easing:`ease-out`,fill:`forwards`}));window.setTimeout(()=>{for(let e of o)e.cancel();r();let n=()=>{e.style.removeProperty(`height`),e.style.removeProperty(`overflow`)};if(!e.isConnected){n(),i();return}e.style.height=`auto`;let a=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!a||Math.abs(a-t)<1){n(),i();return}let s=Math.abs(t-a),c=Math.round(Math.min(ex,Math.max($b,Zb+s*Qb))),l=Math.round(c*rx),u=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,d=u?u.animate([{opacity:0},{opacity:1}],{duration:nx,delay:l,easing:`ease-out`,fill:`backwards`}):null,f=e.animate([{height:`${t}px`},{height:`${a}px`}],{duration:c,easing:tx});e.style.height=`${a}px`;let p=!1,m=()=>{p||(p=!0,n(),i())};Promise.allSettled([f.finished,d?.finished].filter(Boolean)).then(m),window.setTimeout(m,Math.max(c,l+nx)+120)},Xb)}function Kb(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 qb(e){let t=e?.inlineBody,n=t?.streamingView===`status`?`status`:`source`,r=t?.viewMode===`source`?`source`:`rendered`,i=320,a=320,o=t?.height;typeof o==`number`||o===`auto`?(i=o,a=o):o&&typeof o==`object`&&(i=o.streaming??320,a=o.complete??320);let s=t?.overflow===`clip`?`clip`:`scroll`,c=s!==`clip`&&t?.followOutput!==!1,l,u,d=t?.fadeMask;d===!0?(l=!0,u=!0):d===!1?(l=!1,u=!1):d&&typeof d==`object`?(l=d.top===!0,u=d.bottom===!0):s===`clip`?(l=!1,u=!0):(l=!0,u=!0);let f=t?.transition===`none`?`none`:`auto`,p=t?.completeDisplay===`card`?`card`:`inline`;return{streamingView:n,viewMode:r,streamingHeight:i,completeHeight:a,followOutput:c,overflow:s,fadeTop:l,fadeBottom:u,transition:f,completeDisplay:p}}function Jb(e,t){let n=Hb(e),r=t.config?.features?.artifacts,{chromeEnabled:i,showCopy:a,showExpand:o,showViewToggle:s}=Kb(r),c=r?.inlineActions??[],l=qb(r),d=l.completeDisplay===`card`,f=null,p=n,m=z(`div`,`persona-artifact-inline persona-w-full persona-max-w-full`);m.setAttribute(`data-persona-theme-zone`,`artifact-inline`),n.id&&m.setAttribute(`data-artifact-inline`,n.id);let g=e=>Rb(Wb(e),t),_=null,v=e=>{_?.destroy(),_=null,m.classList.add(`persona-artifact-inline--card`),m.style.removeProperty(ix),m.replaceChildren(g(e)),Yb.set(m,e=>{m.replaceChildren(g(e))})};if(d&&n.status===`complete`)return v(n),m;let y=Ob(n,{config:t.config,bodyLayout:l,resolveViewMode:()=>f??l.viewMode});_=y;let b=z(`div`,`persona-artifact-inline-body`);b.appendChild(y.el);let x=e=>{let t=e.status!==`complete`,n=t?l.streamingHeight:l.completeHeight,r=typeof n==`number`;r?m.style.setProperty(ix,`${n}px`):m.style.removeProperty(ix);let i=!!y.el.querySelector(`.persona-code-pre`),a=!!y.el.querySelector(`iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view`);b.classList.toggle(`persona-artifact-content-flush`,i),b.classList.toggle(`persona-artifact-inline-body--sized`,r&&a),b.classList.toggle(`persona-artifact-inline-body--cap`,!t&&!a&&typeof l.completeHeight==`number`)},S=n.status,C=(e,t)=>{S!==`complete`&&e.status===`complete`?(typeof l.completeHeight==`number`?m.style.setProperty(ix,`${l.completeHeight}px`):m.style.removeProperty(ix),xb(b,t?.suppressTransition?`none`:l.transition,e.id,()=>{y.update(e),x(e)})):y.update(e),x(e),S=e.status};x(n);let w=l.overflow===`clip`&&o&&!!n.id;if(w&&(b.setAttribute(`data-expand-artifact-inline`,n.id),b.setAttribute(`role`,`button`),b.setAttribute(`tabindex`,`0`),b.classList.add(`persona-cursor-pointer`),b.setAttribute(`aria-label`,`Open ${Ub(n).title} in panel`)),!i)return m.appendChild(b),Yb.set(m,C),m;let T=z(`div`,`persona-artifact-inline-chrome`);T.setAttribute(`data-persona-theme-zone`,`artifact-inline-chrome`);let E=z(`div`,`persona-artifact-inline-chrome-lead`),D=z(`span`,`persona-flex persona-items-center persona-flex-shrink-0`),O=h(u.FileText,16,`currentColor`,2);O&&D.appendChild(O);let k=z(`span`,`persona-artifact-inline-title persona-truncate persona-min-w-0`),A=z(`span`,`persona-artifact-inline-type`);E.append(D,k,A);let j=z(`div`,`persona-artifact-inline-chrome-actions`),M=z(`span`,`persona-flex persona-items-center persona-gap-1`),ee=()=>f??l.viewMode,N=s?dg({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:ee(),className:`persona-artifact-toggle-group persona-flex-shrink-0`,onSelect:e=>{let t=e===`source`?`source`:`rendered`;t!==ee()&&(f=t,y.update(p),x(p))}}):null,P=a?lg({icon:`copy`,label:`Copy`,className:`persona-artifact-doc-icon-btn persona-flex-shrink-0`}):null;P&&n.id&&P.setAttribute(`data-copy-artifact`,n.id);let F=o?lg({icon:`maximize`,label:`Open in panel`,className:`persona-artifact-doc-icon-btn persona-flex-shrink-0`}):null;F&&n.id&&F.setAttribute(`data-expand-artifact-inline`,n.id),j.appendChild(M),N&&j.appendChild(N.element),P&&j.appendChild(P),F&&j.appendChild(F),T.append(E,j),m.append(T,b);let te=e=>{let{title:t,typeLabel:n}=Ub(e);k.textContent=t,k.title=t,w&&b.setAttribute(`aria-label`,`Open ${t} in panel`);let i=e.status!==`complete`;if(i){A.classList.contains(`persona-artifact-inline-status`)||(A.className=`persona-artifact-inline-status`,A.removeAttribute(`data-preserve-animation`),A.replaceChildren());let t=Uy(e,r,`inline-chrome`);Gy(A,t,r)}else Vy(e.id),A.className=`persona-artifact-inline-type`,A.removeAttribute(`data-preserve-animation`),A.replaceChildren(),A.textContent=n;if(P&&P.classList.toggle(`persona-hidden`,i),N){let t=e.artifactType===`markdown`?e.file:void 0,n=!1;if(!i&&t&&l.viewMode!==`source`){let e=Dy(t);e===`markdown`?n=!0:(e===`html`||e===`svg`)&&(n=r?.filePreview?.enabled!==!1)}N.element.classList.toggle(`persona-hidden`,!n),N.setSelected(ee())}if(M.replaceChildren(),!i&&c.length>0){let t=Ny(e);if(t)for(let e of c)try{if(e.visible===void 0||e.visible(t)){let t=My(e,{documentChrome:!0});t.setAttribute(`data-artifact-custom-action`,e.id),t.classList.add(`persona-flex-shrink-0`),M.appendChild(t)}}catch{}}};return te(n),Yb.set(m,(e,t)=>{if(d&&S!==`complete`&&e.status===`complete`){let t=m.isConnected?m.getBoundingClientRect().height:0;S=`complete`;let n=e,r=!1,i=e=>{n=e,r=!0};Yb.set(m,i),Gb(m,t,{swap:()=>{v(n),r=!1,Yb.set(m,i)},onSettled:()=>{r?v(n):Yb.set(m,e=>{m.replaceChildren(g(e))})}})}else(e.status!==`complete`||e.id!==p.id)&&(f=null),p=e,C(e,t),te(e)}),m}var Yb,Xb,Zb,Qb,$b,ex,tx,nx,rx,ix,ax,ox=o((()=>{H(),jy(),Zy(),Fy(),mg(),g(),Mb(),zb(),Yb=/* @__PURE__ */ new WeakMap,Xb=180,Zb=240,Qb=.8,$b=300,ex=500,tx=`cubic-bezier(0.2, 0, 0, 1)`,nx=240,rx=.35,ix=`--persona-artifact-inline-body-height`,ax=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let r=typeof e.title==`string`&&e.title?e.title:`Untitled artifact`,i=typeof e.artifactId==`string`?e.artifactId:``,a=e.status===`streaming`?`streaming`:`complete`,o=n({artifact:{artifactId:i,title:r,artifactType:typeof e.artifactType==`string`?e.artifactType:`markdown`,status:a},config:t.config,defaultRenderer:()=>Jb(e,t)});if(o)return o}return Jb(e,t)}})),sx=o((()=>{Ib(),ox(),zb(),Mb(),jy(),vb(),ht(),Ee()})),cx=/* @__PURE__ */ s({PersonaArtifactCard:()=>Rb,PersonaArtifactInline:()=>ax,__provideMarkdownParsers:()=>Y,__setIconsExtraLoader:()=>we,artifactCopyText:()=>yb,createArtifactPane:()=>Fb,downloadInfoFor:()=>ky,hasLiveInlineArtifactBlock:()=>Vb,initArtifactsUi:()=>gb,triggerArtifactDownload:()=>Ay,updateInlineArtifactBlocks:()=>Bb}),lx=o((()=>{sx()}));ve(),Cy(),ht(),Ee();const ux=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:dx,load:fx,provide:px,getSync:mx}=_e({fallbackImport:()=>Promise.resolve().then(()=>(lx(),cx))});let hx=null;const gx=/* @__PURE__ */ new Set,_x=e=>{if(hx)return hx;hx=e,e.initArtifactsUi({componentRegistry:Sy});for(let t of ux)Sy.has(t)||Sy.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=mt();t?e.__provideMarkdownParsers(t):pt(()=>{let t=mt();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Te());let n=[...gx];gx.clear();for(let e of n)try{e()}catch{}return e},vx=()=>fx().then(_x),yx=()=>{if(hx)return hx;let e=mx();return e?_x(e):null},bx=e=>hx?()=>{}:(gx.add(e),()=>{gx.delete(e)});function xx(e){return e?.features?.artifacts?.enabled===!0}function Sx(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`),!xx(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function Cx(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`)}const wx=[`panel`,`seamless`,`detached`];function Tx(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&wx.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Ex(e){return!e||!xx(e)?!1:Tx(e)===`detached`}function Dx(e,t){if(!xx(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`),Cx(e),Sx(e,t);return}let n=t.features?.artifacts?.layout,r=Tx(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),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 i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[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[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}Sx(e,t)}function Ox(e,t){for(let t of wx)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!xx(t))return;let n=t.features?.artifacts?.layout,r=Tx(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function kx(e,t){return!t||!xx(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}tn();const Ax=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),jx=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),Mx=/* @__PURE__ */ new Set([`markdown`,`component`]),Nx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Px=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Fx=e=>!Ax.has(e),Ix=e=>typeof e==`string`&&jx.has(e),Lx=e=>Object.keys(e).length>0;function Rx(e,t,n,r){e.push({path:t,code:n,message:r})}const zx=`Ignored an unsupported value.`,Bx={kind:`mode`,message:zx},Vx={kind:`string`,message:`Expected a CSS length string.`},Hx={kind:`boolean`},Ux={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:Hx,showReasoning:Hx,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:zx},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:zx},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:zx},expandable:Hx,grouped:Hx}},reasoningDisplay:{kind:`object`,children:{expandable:Hx,activePreview:Hx}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:Bx,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:Bx,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:Mx,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:Mx}}},filePreview:{kind:`object`,children:{enabled:Hx}},layout:{kind:`object`,children:{paneWidth:Vx,paneMaxWidth:Vx,paneMinWidth:Vx,expandedPanelWidth:Vx,resizableMinWidth:Vx,resizableMaxWidth:Vx,expandLauncherPanelWhenOpen:Hx,resizable:Hx}}}}}};function Wx(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:Rx(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:Rx(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:Rx(r,n,`invalid_value`,t.message);case`mode`:return Ix(e)?Yt(e):Rx(r,n,`invalid_value`,t.message);case`modeMap`:{if(!Px(e))return Rx(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:Xt(t);Fx(t)&&(i?i.has(t):Nx.test(e))?Ix(o)?a[e]=Yt(o):Rx(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):Rx(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return Lx(a)?a:void 0}case`object`:{if(t.bareMode&&Ix(e))return Yt(e);if(!Px(e))return Rx(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!Fx(t)||!i.includes(t))&&Rx(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=Wx(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&Rx(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=Px(l)&&Px(s)?{...l,...s}:s}return Lx(o)?o:void 0}}}function Gx(e){let t=[];return{preferences:(e===null?void 0:Wx(e,Ux,``,t))??{},issues:t}}function Kx(e){if(Array.isArray(e))return e.map(Kx);if(!Px(e))return e;let t={};for(let[n,r]of Object.entries(e))Fx(n)&&r!==void 0&&(t[n]=Kx(r));return t}function qx(e,t){let n=Kx(e);for(let[e,r]of Object.entries(t)){if(!Fx(e)||r===void 0)continue;let t=n[e];n[e]=Px(t)&&Px(r)?qx(t,r):Kx(r)}return n}function Jx(e){let t={},n;for(let r of e){let e=Gx(r).preferences;n=Xx(n,e.artifacts?.display),t=qx(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function Yx(e,t){if(t===void 0)return e===void 0?void 0:Kx(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...Lx(i)?{byMediaType:i}:{}};return Lx(a)?a:void 0}function Xx(e,t){if(t===void 0)return e===void 0?void 0:Kx(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=Yx(n.files,t.files),o={...r?{default:r}:{},...Lx(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return Lx(o)?o:void 0}function Zx(e={},t){let n=Jx(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=Xx(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function Qx(e){let t=e.preferences;return!t||!Lx(t)?e:{...e,features:Zx(e.features??{},[t])}}function $x(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 eS(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 tS(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function nS(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function rS(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function iS(e,t,n,r,i,a,o=200){let s=$x(i,200),c=nS(t,n,r,o);c=Math.max(s,c);let l=eS(a);return l!==null&&(c=Math.min(c,l)),tS(e,s,c)}var aS,oS,sS=o((()=>{H(),aS={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`}},oS=(e,t,n,r)=>{let i=e.querySelectorAll(`[data-tv-form]`);i.length&&i.forEach(e=>{if(e.dataset.enhanced===`true`)return;let i=e.dataset.tvForm??`init`;e.dataset.enhanced=`true`;let a=aS[i]??aS.init;e.classList.add(`persona-form-card`,`persona-space-y-4`);let o=z(`div`,`persona-space-y-1`),s=z(`h3`,`persona-text-base persona-font-semibold persona-text-persona-primary`);if(s.textContent=a.title,o.appendChild(s),a.description){let e=z(`p`,`persona-text-sm persona-text-persona-muted`);e.textContent=a.description,o.appendChild(e)}let c=document.createElement(`form`);c.className=`persona-form-grid persona-space-y-3`,a.fields.forEach(e=>{let n=z(`label`,`persona-form-field persona-flex persona-flex-col persona-gap-1`);n.htmlFor=`${t.id}-${i}-${e.name}`;let r=z(`span`,`persona-text-xs persona-font-medium persona-text-persona-muted`);r.textContent=e.label,n.appendChild(r);let a=e.type??`text`,o;a===`textarea`?(o=document.createElement(`textarea`),o.rows=3):(o=document.createElement(`input`),o.type=a),o.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`,o.id=`${t.id}-${i}-${e.name}`,o.name=e.name,o.placeholder=e.placeholder??``,e.required&&(o.required=!0),n.appendChild(o),c.appendChild(n)});let l=z(`div`,`persona-flex persona-items-center persona-justify-between persona-gap-2`),u=z(`div`,`persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]`),d=z(`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`);d.type=`submit`,d.textContent=a.submitLabel??`Submit`,l.appendChild(u),l.appendChild(d),c.appendChild(l),e.replaceChildren(o,c),c.addEventListener(`submit`,async e=>{e.preventDefault();let t=n.formEndpoint??`/form`,a=new FormData(c),o={};a.forEach((e,t)=>{o[t]=e}),o.type=i,d.disabled=!0,u.textContent=`Submitting…`;try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!e.ok)throw Error(`Form submission failed (${e.status})`);let n=await e.json();u.textContent=n.message??`Thanks! We'll be in touch soon.`,n.success&&n.nextPrompt&&await r.sendMessage(String(n.nextPrompt))}catch(e){u.textContent=e instanceof Error?e.message:`Something went wrong. Please try again.`}finally{d.disabled=!1}})})}})),cS=/* @__PURE__ */ s({enhanceWithForms:()=>oS,formDefinitions:()=>aS}),lS=o((()=>{sS()}));ve();const{setLoader:uS,load:dS,provide:fS,getSync:pS}=_e({fallbackImport:()=>Promise.resolve().then(()=>(lS(),cS))}),mS=dS,hS=pS,gS=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}};he(),ne(),k();const _S=e=>typeof e==`object`&&!!e&&!Array.isArray(e),vS=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),yS=(e,t,n)=>{if(!_S(e)||!_S(t)||vS.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=yS(e[i],t[i],a)}return r};function bS(e,t){let n=b(me),r=T(e,t,n),i=C(E(yS(e,t,``),n,r),r);return P(oe(i),te(e,t))}const xS=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},SS=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},CS=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},wS=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=SS(e),n=CS(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},TS=e=>typeof e==`string`?e:e==null?``:String(e),ES={message:e=>{if(e.type===`message`)return{handled:!0,displayText:TS(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=TS(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:TS(n.text)}}},DS=e=>Array.isArray(e)?e.map(e=>String(e)):[],OS=e=>{let t=new Set(DS(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(DS(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.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 a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},kS=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},AS=e=>e.map(e=>({...e,streaming:!1})),jS=e=>e.map(e=>({...e,status:`complete`})),MS=(e=`persona-state`)=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?kS(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?AS(n.messages):void 0,artifacts:n.artifacts?jS(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},NS=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`)},PS=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(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return NS(e)},FS=async(e,t)=>{let n=await PS(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await PS(`${e}\0${t}`)}`}},IS=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await FS(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}};function LS(){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 RS=o((()=>{})),zS,BS=o((()=>{zS=`
|
|
263
|
+
`)),n=B(`span`,`persona-code-line`)),r(i.type,e[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function gb(e,t,n){let r=e.length<=15e4?cb(t,n):null;return hb(r?mb(e,r):[{type:`plain`,value:e}])}var _b,vb,yb,bb,xb,Sb,Cb,wb=o((()=>{H(),_b={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`},vb={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`},yb=/* @__PURE__ */ new Set(/* @__PURE__ */ `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`.split(`.`)),bb=[{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=>yb.has(e)?`keyword`:`plain`}],xb=[{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`}],Sb=[{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}],Cb=[{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}]})),Tb,Eb,Db,Ob=o((()=>{Tb=null,Eb=e=>{Tb=e.componentRegistry},Db=()=>Tb}));function kb(e){if(!e)return``;if(e.artifactType===`markdown`){let t=e.markdown??``;return e.file?Iy(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}function Ab(e){return`persona-artifact-vt-`+((e||`artifact`).replace(/[^A-Za-z0-9_-]/g,`-`).replace(/^-+/,``)||`artifact`)}function jb(e,t,n,r){let i=typeof document<`u`?document.startViewTransition:void 0,a=!1;try{a=typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{a=!1}if(t!==`auto`||!e||typeof i!=`function`||zb||a){r();return}zb=!0;let o=Ab(n);e.style.setProperty(`view-transition-name`,o);let s=()=>{zb=!1,e.style.removeProperty(`view-transition-name`)};try{i.call(document,()=>{r()}).finished.then(s,s)}catch{s(),r()}}function Mb(e){let t=B(`div`,`persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary`),n=B(`div`,`persona-font-semibold persona-text-sm persona-mb-2`);n.textContent=e.component?`Component: ${e.component}`:`Component`;let r=B(`pre`,`persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto`);return r.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(r),t}function Nb(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 Pb(){try{if(typeof crypto<`u`&&crypto.getRandomValues){let e=/* @__PURE__ */ 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 Fb(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 Ib(e,t,n){let r=B(`div`,`persona-artifact-frame-loading`);if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return r.appendChild(i),{el:r,revealLabel:()=>{}}}catch{}let i=B(`div`,`persona-artifact-frame-loading-indicator`);i.appendChild(Ky());let a=null;return n.label!==!1&&(a=B(`div`,`persona-artifact-frame-loading-text`),a.textContent=n.label,i.appendChild(a)),r.appendChild(i),{el:r,revealLabel:()=>{a&&a.classList.add(`persona-artifact-frame-loading-text--visible`)}}}function Lb(e,t,n,r,i,a){let o=null,s=0,c=!1,l=/* @__PURE__ */ new Set,u=()=>{l.forEach(e=>clearTimeout(e)),l.clear()},d=(e,t)=>{let n=setTimeout(()=>{l.delete(n),typeof document<`u`&&e()},t);l.add(n)},f=()=>{o&&o.parentElement&&o.remove(),o=null},p=()=>{if(o||c)return;let t=Ib(i,a,r);o=t.el,e.appendChild(o),s=Date.now(),r.label!==!1&&d(t.revealLabel,r.labelDelayMs)},m=()=>{o&&(o.classList.add(`persona-artifact-frame-loading--out`),d(f,Vb))},h=()=>{n===null?t.removeEventListener(`load`,v):typeof window<`u`&&window.removeEventListener(`message`,_)},g=()=>{if(c||(c=!0,h(),u(),!o))return;let e=Math.max(0,r.minVisibleMs-(Date.now()-s));e>0?d(m,e):m()};function _(e){if(n===null)return;let r=e.data;r&&r.persona===`artifact-preview-ready`&&r.token===n&&e.source===t.contentWindow&&g()}function v(){let e=e=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,0)};e(()=>e(()=>g()))}return d(p,r.delayMs),d(g,r.timeoutMs),n===null?t.addEventListener(`load`,v):typeof window<`u`&&window.addEventListener(`message`,_),()=>{c=!0,u(),h(),f()}}function Rb(e,t){let{config:n}=t,r=t.registry??Db()??My,i=t.bodyLayout,a=n.markdown?Nt(n.markdown):null,o=Rt(n.sanitize),s=e,c=!1,l=e=>{let t=kt()!==null;a&&!t&&!c&&(c=!0,Dt(()=>j(s)));let n=a?a(e):Pt(e);return a&&t&&o?o(n):n},u=B(`div`,`persona-artifact-preview-body`),d=null,f=null,p=null,m=()=>{p&&=(p(),null),d=null,f=null},h=null,g=null,_=null,v=!1,y=()=>{h=null,g=null,_=null,v=!1},b=null,x=null,S=()=>{b=null,x=null},C=0,w=e=>typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>e()):setTimeout(e,0),T=e=>e.scrollHeight-e.clientHeight-e.scrollTop<=40,E=e=>{if(!i)return;let t=e.scrollHeight-e.clientHeight>1,n=e.scrollHeight-e.clientHeight-e.scrollTop;e.classList.toggle(`persona-artifact-fade-top`,i.fadeTop&&t&&e.scrollTop>1),e.classList.toggle(`persona-artifact-fade-bottom`,i.fadeBottom&&t&&n>1)},D=e=>{C||=w(()=>{C=0,e.scrollTop=e.scrollHeight,E(e)})},O=(e,t,n,r)=>{let a=!!i,o=n.id+`|`+(a?`w`:`p`);if(!h||_!==o||h.parentElement!==u){m(),S(),u.replaceChildren();let e=B(`pre`,`persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary persona-code-pre`),t=B(`code`,`persona-code`);if(e.appendChild(t),a){let t=B(`div`,`persona-artifact-source-window`);if(t.appendChild(e),u.appendChild(t),i?.overflow!==`clip`&&typeof t.addEventListener==`function`){let e=()=>t.scrollHeight-t.clientHeight>1;t.addEventListener(`scroll`,()=>{T(t)&&(v=!1),E(t)},{passive:!0}),t.addEventListener(`wheel`,t=>{e()&&t.deltaY<0&&(v=!0)},{passive:!0}),t.addEventListener(`touchmove`,()=>{e()&&(v=!0)},{passive:!0})}h=t}else u.appendChild(e),h=e;g=t,_=o}let s=a?h:null;s&&(s.classList.toggle(`persona-artifact-source-window--fixed`,r),s.classList.toggle(`persona-artifact-source-window--clip`,r&&i?.overflow===`clip`));let c=!s||T(s);if(g.replaceChildren(gb(e,t?.language,t?.path)),s){let e=n.status!==`complete`;r&&e&&i?.followOutput&&!v&&c?D(s):e||(v=!1),E(s)}},k=e=>{m(),y(),S(),u.replaceChildren();let t=B(`div`,Bb);t.innerHTML=l(e),u.appendChild(t)},A=e=>{let t=e.id,r=n.features?.artifacts,i=$y(e,r,`status-body`);if(b&&x===t&&b.parentElement===u){let e=b.querySelector(`.persona-artifact-status-view-text`);e&&tb(e,i,r);return}m(),y(),u.replaceChildren();let a=B(`div`,`persona-artifact-status-view`),o=B(`div`,`persona-artifact-status-view-text`);tb(o,i,r),a.appendChild(o),u.appendChild(a),b=a,x=t},j=e=>{s=e;let a=t.resolveViewMode?.(e)??i?.viewMode??`rendered`,o=e.artifactType===`markdown`?e.file:void 0,c=e.status!==`complete`;c||Zy(e.id);let l=c?i?.streamingHeight:i?.completeHeight,h=!!i&&typeof l==`number`;if(i?.streamingView===`status`&&c){A(e);return}if(o){let t=Iy(e.markdown??``),r=Ly(o),i=n.features?.artifacts?.filePreview?.enabled!==!1;if(!c&&a===`rendered`&&i&&(r===`html`||r===`svg`)){let r=e.id+`\0`+t;if(d&&f===r&&d.parentElement===u)return;y(),S(),m(),u.replaceChildren();let i=n.features?.artifacts?.filePreview,a=i?.iframeSandbox??`allow-scripts`;!i?.dangerouslyAllowSameOrigin&&a.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.`),a=a.split(/\s+/).filter(e=>e&&e!==`allow-same-origin`).join(` `));let o=Nb(i?.loading),s=B(`div`,`persona-artifact-frame`),c=B(`iframe`,`persona-artifact-iframe`);c.setAttribute(`sandbox`,a),c.setAttribute(`data-artifact-id`,e.id);let l=null;o.enabled&&o.injectReadySignal?(l=Pb(),c.srcdoc=t+Fb(l)):c.srcdoc=t,s.appendChild(c),u.appendChild(s),o.enabled&&(p=Lb(s,c,l,o,e.id,n)),d=s,f=r;return}if(m(),!c&&r===`markdown`&&a===`rendered`){k(t);return}O(t,{language:o.language,path:o.path},e,h);return}if(e.artifactType===`markdown`){if(a===`source`){m(),O(e.markdown??``,void 0,e,h);return}k(e.markdown??``);return}m(),y(),S(),u.replaceChildren();let g=e.component?r.get(e.component):void 0;if(g){let t={message:{id:e.id,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString()},config:n,updateProps:()=>{}};try{let n=g(e.props??{},t);if(n){u.appendChild(n);return}}catch{}}u.appendChild(Mb(e))};return j(e),{el:u,update(e){j(e)},destroy(){m()}}}var zb,Bb,Vb,Hb=o((()=>{H(),Jy(),Vy(),sb(),wb(),Ft(),At(),Ny(),Ob(),zb=!1,Bb=`persona-text-sm persona-leading-relaxed persona-markdown-bubble`,Vb=220}));function Ub(e,t){let n=t.orientation??`horizontal`,r=n===`vertical`?`ArrowUp`:`ArrowLeft`,i=n===`vertical`?`ArrowDown`:`ArrowRight`;e.setAttribute(`role`,`tablist`);let a=[],o=!1,s=e=>{typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`,inline:`nearest`})},c=e=>{let t=e;return a.findIndex(e=>e===t||e.contains(t))},l=e=>{let n=c(e.target);if(n<0)return;let o=n;if(e.key===i)o=Math.min(n+1,a.length-1);else if(e.key===r)o=Math.max(n-1,0);else if(e.key===`Home`)o=0;else if(e.key===`End`)o=a.length-1;else return;e.preventDefault(),o!==n&&t.onSelect(o)},u=e=>{let t=c(e.target);t>=0&&s(a[t])};return e.addEventListener(`keydown`,l),e.addEventListener(`focusin`,u),{beforeRender(){o=typeof document<`u`&&e.contains(document.activeElement)},render(e,t){if(a=e,e.forEach((e,n)=>{e.setAttribute(`role`,`tab`);let r=n===t;e.setAttribute(`aria-selected`,r?`true`:`false`),e.tabIndex=r||t<0&&n===0?0:-1}),o){let n=(t>=0?e[t]:void 0)??e[0];n&&typeof n.focus==`function`&&(s(n),n.focus())}},destroy(){e.removeEventListener(`keydown`,l),e.removeEventListener(`focusin`,u)}}}var Wb=o((()=>{}));function Gb(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??`default`)===`document`,i=n?.toolbarTitle??`Artifacts`,a=n?.closeButtonLabel??`Close`,o=n?.panePadding?.trim(),s=n?.tabFadeSize?.trim(),c=e=>({start:e===!1?!1:typeof e==`object`&&e?e.start!==!1:!0,end:e===!1?!1:typeof e==`object`&&e?e.end!==!1:!0}),{start:l,end:d}=c(n?.tabFade),f=typeof document<`u`?B(`div`,`persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden`):null,p=()=>{f?.classList.add(`persona-hidden`),m.classList.remove(`persona-artifact-drawer-open`),D?.closeMenu()};f&&f.addEventListener(`click`,()=>{p(),t.onDismiss?.()});let m=B(`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`);m.setAttribute(`data-persona-theme-zone`,`artifact-pane`),r&&m.classList.add(`persona-artifact-pane-document`);let h=B(`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`);h.setAttribute(`data-persona-theme-zone`,`artifact-toolbar`),r&&h.classList.add(`persona-artifact-toolbar-document`);let g=B(`span`,`persona-text-xs persona-font-medium persona-truncate`);g.textContent=i;let _=yg({icon:`x`,label:a});_.addEventListener(`click`,()=>{p(),t.onDismiss?.()});let v=`rendered`,y=xg({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:e=>{v=e===`source`?`source`:`rendered`,Ee()}}),b=B(`div`,`persona-flex persona-items-center persona-gap-1 persona-shrink-0`),x=n?.documentToolbarShowCopyLabel===!0,S=n?.documentToolbarShowCopyChevron===!0,C=n?.documentToolbarCopyMenuItems,w=!!(S&&C&&C.length>0),T=null,E,D=null;if(r&&(x||S)&&!w){if(E=x?bg({icon:`copy`,label:`Copy`,iconSize:14,className:`persona-artifact-doc-copy-btn`}):yg({icon:`copy`,label:`Copy`,className:`persona-artifact-doc-copy-btn`}),S){let e=j(u.ChevronDown,14,`currentColor`,2);e&&E.appendChild(e)}}else r&&w?(D=Sg({label:`Copy`,icon:`copy`,iconSize:14,iconOnly:!x,primaryClassName:`persona-artifact-doc-copy-btn`,chevronLabel:`More copy options`,chevronClassName:`persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn`,menuItems:(C??[]).map(e=>({id:e.id,label:e.label})),position:`bottom-right`,portal:()=>m.closest(`[data-persona-root]`)??document.body,onSelect:e=>void ie(e)}),T=D.element,E=D.primaryButton):r?E=yg({icon:`copy`,label:`Copy`,className:`persona-artifact-doc-icon-btn`}):(E=yg({icon:`copy`,label:`Copy`}),n?.showCopyButton!==!0&&E.classList.add(`persona-hidden`));let O=yg(r?{icon:`refresh-cw`,label:`Refresh`,className:`persona-artifact-doc-icon-btn`}:{icon:`refresh-cw`,label:`Refresh`});n?.onDocumentToolbarRefresh||O.classList.add(`persona-hidden`);let k=yg(r?{icon:`x`,label:a,className:`persona-artifact-doc-icon-btn`}:{icon:`x`,label:a}),A=yg({icon:`maximize`,label:`Expand artifacts panel`,className:`persona-artifact-expand-btn`+(r?` persona-artifact-doc-icon-btn`:``),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&A.classList.add(`persona-hidden`);let ee=B(`div`,`persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions`),M=e.features?.artifacts?.toolbarActions??[],N=()=>{let e=he.find(e=>e.id===ge)??he[he.length-1],t=e?.id??null,n=e?.artifactType===`markdown`?e.markdown??``:``,r=e?JSON.stringify({component:e.component,props:e.props},null,2):``,{filename:i,mime:a,content:o}=zy({title:e?.title,markdown:e?.markdown??``,file:e?.file});return{markdown:n,jsonPayload:r,id:t,file:e?.file,suggestedFilename:i,mime:a,content:o}},P=()=>{let{suggestedFilename:e,mime:t,content:n}=N();n&&By({filename:e,mime:t,content:n})},te=e=>{let{id:t,...n}=N();return{actionId:e,artifactId:t,...n}},ne=async()=>{let e=he.find(e=>e.id===ge)??he[he.length-1];try{return await navigator.clipboard.writeText(kb(e)),!0}catch{return!1}},re=null,F=()=>{re?.();let e=E.querySelector(`svg`),t=Number(e?.getAttribute(`width`))||16,n=j(u.Check,t,`currentColor`,2);if(!e||!n)return;e.replaceWith(n);let r=E.querySelector(`span`);r&&(r.textContent=`Copied`);let i=setTimeout(()=>re?.(),2e3);re=()=>{clearTimeout(i),n.replaceWith(e),r&&(r.textContent=`Copy`),re=null}};E.addEventListener(`click`,async()=>{let e=n?.onDocumentToolbarCopyMenuSelect;if(e&&w)try{if(await e(te(`primary`))===!1){await ne()&&F();return}F()}catch{}else await ne()&&F()});async function ie(e){let t=n?.onDocumentToolbarCopyMenuSelect;try{if(t&&await t(te(e))!==!1)return;if(e===`download`){P();return}let{markdown:n,jsonPayload:r}=N();e===`markdown`||e===`md`?await navigator.clipboard.writeText(n):e===`json`||e===`source`?await navigator.clipboard.writeText(r):await navigator.clipboard.writeText(n||r),F()}catch{}}O.addEventListener(`click`,async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ee()}),k.addEventListener(`click`,()=>{p(),t.onDismiss?.()});let ae=B(`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)h.replaceChildren(),T?b.append(T,O,k):b.append(E,O,k),b.insertBefore(ee,k),b.insertBefore(A,k),h.append(y.element,ae,b);else{let e=B(`div`,`persona-flex persona-items-center persona-gap-1 persona-shrink-0`);e.append(E,ee,A,_),h.appendChild(g),h.appendChild(e)}o&&(h.style.paddingLeft=o,h.style.paddingRight=o);let oe=B(`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`);s&&oe.style.setProperty(`--persona-artifact-tab-fade-size`,s);let se=e.features?.artifacts?.renderTabBar,ce=B(`div`,`persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden`),le=Ub(oe,{onSelect:e=>t.onSelect(he[e].id)}),ue=e=>{let t=e.scrollWidth-e.clientWidth,n=t>1,r=Math.abs(e.scrollLeft);e.classList.toggle(`persona-artifact-tab-fade-start`,l&&n&&r>1),e.classList.toggle(`persona-artifact-tab-fade-end`,d&&n&&r<t-1)},de=0,I=()=>{if(de)return;let e=()=>{de=0,ue(oe)};de=typeof requestAnimationFrame==`function`?requestAnimationFrame(e):setTimeout(e,0)};oe.addEventListener(`scroll`,()=>I(),{passive:!0}),typeof ResizeObserver<`u`&&new ResizeObserver(()=>ue(oe)).observe(oe);let fe=B(`div`,`persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3`),pe=()=>{fe.scrollLeft=0},me=()=>{typeof requestAnimationFrame==`function`?requestAnimationFrame(pe):setTimeout(pe,0)};if(o){for(let e of[oe,ce])e.style.paddingLeft=o,e.style.paddingRight=o;fe.style.padding=o}m.appendChild(h),m.appendChild(oe),m.appendChild(ce),m.appendChild(fe);let he=[],ge=null,_e=!1,ve=!1,L=!0,R=!1,z=null,ye=``,be=null,xe=!1,Se=e=>e.artifactType===`markdown`&&e.file||r?v:`rendered`,Ce=e=>{r||(e&&!xe?(h.insertBefore(y.element,g),xe=!0):!e&&xe&&(y.element.remove(),xe=!1))},we=()=>ge&&he.find(e=>e.id===ge)||he[he.length-1],Te=()=>{let e=Uy(we());if(!e){ee.replaceChildren();return}let t=M.filter(t=>t.visible===void 0||t.visible(e)).map(e=>Hy(e,{documentChrome:r,onClick:()=>{let t=Uy(we());if(t)try{Promise.resolve(e.onClick(t)).catch(()=>{})}catch{}}}));ee.replaceChildren(...t)},Ee=()=>{Te();let n=r&&he.length<=1,a=!!se;if(oe.classList.toggle(`persona-hidden`,n||a),ce.classList.toggle(`persona-hidden`,n||!a),a&&se){let e=he.map(e=>e.id).join(`|`)+` `+(ge??``);if(e!==ye){ye=e;let n=se({records:he,selectedId:ge,onSelect:t.onSelect});ce.firstElementChild!==n&&ce.replaceChildren(n)}}else{le.beforeRender(),oe.replaceChildren();let e=[],n=-1;for(let[r,i]of he.entries()){let a=B(`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`);a.type=`button`;let o=i.artifactType===`markdown`?i.file:void 0,s=o?Py(o.path):i.title||i.id.slice(0,8),c=o?.path||i.title||s;a.textContent=s,a.title=c,a.setAttribute(`aria-label`,c),i.id===ge&&(a.classList.add(`persona-bg-persona-container`,`persona-border-persona-border`),n=r),a.addEventListener(`click`,()=>t.onSelect(i.id)),oe.appendChild(a),e.push(a)}if(le.render(e,n),n>=0&&ge!==z){z=ge;let t=e[n];typeof t.scrollIntoView==`function`&&t.scrollIntoView({block:`nearest`,inline:`nearest`})}ue(oe)}let o=ge&&he.find(e=>e.id===ge)||he[he.length-1];if(!o){fe.replaceChildren(),be?.destroy(),be=null,Ce(!1);return}let s=o.artifactType===`markdown`?o.file:void 0;if(Ce(!!s&&Ly(s)!==`other`),r){let e=s?Ry(s):o.artifactType===`markdown`?`MD`:o.component??`Component`,t=(o.title||`Document`).trim(),n=s?Py(s.path):t.replace(/\s*·\s*MD\s*$/i,``).trim()||`Document`;ae.textContent=`${n} · ${e}`}else g.textContent=s?Py(s.path):i;be?(be.el.parentElement!==fe&&fe.replaceChildren(be.el),be.update(o)):(be=Rb(o,{config:e,resolveViewMode:Se}),fe.replaceChildren(be.el)),fe.classList.toggle(`persona-artifact-content-flush`,!!fe.querySelector(`.persona-code-pre`))},De=()=>{let e=he.length>0;if(m.classList.toggle(`persona-hidden`,!e),f){let t=((typeof m.closest==`function`?m.closest(`[data-persona-root]`):null)?.classList.contains(`persona-artifact-narrow-host`)??!1)||typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches;e&&t&&_e?(f.classList.remove(`persona-hidden`),m.classList.add(`persona-artifact-drawer-open`)):(f.classList.add(`persona-hidden`),m.classList.remove(`persona-artifact-drawer-open`))}},Oe=()=>{R=!1,Ee(),De()};return{element:m,backdrop:f,update(e){let t=e.selectedId??e.artifacts[e.artifacts.length-1]?.id??null,n=t!==ge;he=e.artifacts,ge=t,he.length>0&&(_e=!0),R=!0,L&&Oe(),n&&pe()},setMobileOpen(e){_e=e,!e&&f?(f.classList.add(`persona-hidden`),m.classList.remove(`persona-artifact-drawer-open`)):De()},setExpanded(e){e!==ve&&(ve=e,me());let t=j(e?u.Minimize:u.Maximize,16,`currentColor`,2);t&&A.replaceChildren(t);let n=e?`Collapse artifacts panel`:`Expand artifacts panel`;A.setAttribute(`aria-label`,n),A.title=n},setExpandToggleVisible(e){A.classList.toggle(`persona-hidden`,!e)},setCopyButtonVisible(e){r||E.classList.toggle(`persona-hidden`,!e)},setRefreshButtonVisible(e){O.classList.toggle(`persona-hidden`,!e)},setCustomActions(e){M=e,Te()},setTabFade(e){let t=c(e);(t.start!==l||t.end!==d)&&(l=t.start,d=t.end,ue(oe))},setRenderTabBar(e){e!==se&&(se=e,ye=``,Ee())},setVisible(e){e!==L&&(L=e,e&&R&&Oe())},destroy(){be?.destroy(),be=null}}}var Kb=o((()=>{H(),Vy(),Gy(),Hb(),ee(),wg(),Wb()}));function qb(e,t){let n=e.file&&typeof e.file==`object`&&!Array.isArray(e.file)?e.file:void 0,r=typeof e.title==`string`&&e.title?e.title:`Untitled artifact`,i=n?Py(n.path):r,a=typeof e.artifactId==`string`?e.artifactId:``,o=e.status===`streaming`?`streaming`:`complete`,s=typeof e.artifactType==`string`?e.artifactType:`markdown`,c=e.presentation&&typeof e.presentation==`object`&&!Array.isArray(e.presentation)?e.presentation:void 0,l=n?Ry(n):s===`component`?`Component`:`Document`,u=document.createElement(`div`);u.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`,u.tabIndex=0,u.setAttribute(`role`,`button`),u.setAttribute(`aria-label`,`Open ${i} in artifact panel`),a&&u.setAttribute(`data-open-artifact`,a);let d=document.createElement(`div`);d.className=`persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg`,d.style.border=`1px solid var(--persona-border, #e5e7eb)`,d.style.color=`var(--persona-muted, #9ca3af)`,d.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 f=document.createElement(`div`);f.className=`persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5`;let p=document.createElement(`div`);p.className=`persona-truncate persona-text-sm persona-font-medium`,p.style.color=`var(--persona-text, #1f2937)`,p.textContent=i;let m=document.createElement(`div`);if(m.className=`persona-text-xs persona-flex persona-items-center persona-gap-1.5`,m.style.color=`var(--persona-muted, #9ca3af)`,o===`streaming`){let i=t?.config?.features?.artifacts;tb(m,$y({id:a,artifactType:s===`component`?`component`:`markdown`,title:r,status:`streaming`,...typeof e.markdown==`string`?{markdown:e.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},i,`card`),i)}else a&&Zy(a),m.textContent=l;if(f.append(p,m),u.append(d,f),o===`complete`){let r=t?.config?.features?.artifacts?.cardActions;if(r&&r.length>0){let t={artifactId:a||null,title:i,artifactType:s,markdown:typeof e.markdown==`string`?e.markdown:void 0,file:n};for(let e of r)try{if(e.visible===void 0||e.visible(t)){let t=Hy(e);t.setAttribute(`data-artifact-custom-action`,e.id),t.className=`${t.className} persona-flex-shrink-0`,u.append(t)}}catch{}}let o=bg({label:`Download`,className:`persona-flex-shrink-0`});o.title=`Download ${i}`,o.setAttribute(`data-download-artifact`,a),u.append(o)}return u}var Jb,Yb=o((()=>{Vy(),sb(),wg(),Gy(),Jb=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let r=typeof e.title==`string`&&e.title?e.title:`Untitled artifact`,i=typeof e.artifactId==`string`?e.artifactId:``,a=e.status===`streaming`?`streaming`:`complete`,o=n({artifact:{artifactId:i,title:r,artifactType:typeof e.artifactType==`string`?e.artifactType:`markdown`,status:a},config:t.config,defaultRenderer:()=>qb(e,t)});if(o)return o}return qb(e,t)}}));function Xb(e,t,n){if(t.length===0)return;let r=new Map(t.map(e=>[e.id,e]));e.querySelectorAll(`[data-artifact-inline]`).forEach(e=>{let t=ax.get(e);if(!t)return;let i=r.get(e.getAttribute(`data-artifact-inline`)??``);i&&t(i,n)})}function Zb(e){return ax.has(e)}function Qb(e){let t=typeof e.artifactId==`string`?e.artifactId:``,n=typeof e.title==`string`&&e.title?e.title:void 0,r=e.status===`streaming`?`streaming`:`complete`,i=e.presentation&&typeof e.presentation==`object`&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType===`component`){let a=e.componentProps,o=a&&typeof a==`object`&&!Array.isArray(a)?a:{};return{id:t,artifactType:`component`,title:n,status:r,component:typeof e.component==`string`?e.component:``,props:o,...i?{presentation:i}:{}}}let a=e.file&&typeof e.file==`object`&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:`markdown`,title:n,status:r,markdown:typeof e.markdown==`string`?e.markdown:``,...a?{file:a}:{},...i?{presentation:i}:{}}}function $b(e){let t=e.artifactType===`markdown`?e.file:void 0;return{title:t?Py(t.path):e.title&&e.title.trim()?e.title:`Untitled artifact`,typeLabel:t?Ry(t):e.artifactType===`component`?`Component`:`Document`}}function ex(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 tx(e,t,n){let{swap:r,onSettled:i}=n,a=!1;try{a=typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!=`function`){r(),i();return}e.style.height=`${t}px`,e.style.overflow=`hidden`;let o=[];for(let t of Array.from(e.children))t instanceof HTMLElement&&o.push(t.animate([{opacity:1},{opacity:0}],{duration:ox,easing:`ease-out`,fill:`forwards`}));window.setTimeout(()=>{for(let e of o)e.cancel();r();let n=()=>{e.style.removeProperty(`height`),e.style.removeProperty(`overflow`)};if(!e.isConnected){n(),i();return}e.style.height=`auto`;let a=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!a||Math.abs(a-t)<1){n(),i();return}let s=Math.abs(t-a),c=Math.round(Math.min(ux,Math.max(lx,sx+s*cx))),l=Math.round(c*px),u=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,d=u?u.animate([{opacity:0},{opacity:1}],{duration:fx,delay:l,easing:`ease-out`,fill:`backwards`}):null,f=e.animate([{height:`${t}px`},{height:`${a}px`}],{duration:c,easing:dx});e.style.height=`${a}px`;let p=!1,m=()=>{p||(p=!0,n(),i())};Promise.allSettled([f.finished,d?.finished].filter(Boolean)).then(m),window.setTimeout(m,Math.max(c,l+fx)+120)},ox)}function nx(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 rx(e){let t=e?.inlineBody,n=t?.streamingView===`status`?`status`:`source`,r=t?.viewMode===`source`?`source`:`rendered`,i=320,a=320,o=t?.height;typeof o==`number`||o===`auto`?(i=o,a=o):o&&typeof o==`object`&&(i=o.streaming??320,a=o.complete??320);let s=t?.overflow===`clip`?`clip`:`scroll`,c=s!==`clip`&&t?.followOutput!==!1,l,u,d=t?.fadeMask;d===!0?(l=!0,u=!0):d===!1?(l=!1,u=!1):d&&typeof d==`object`?(l=d.top===!0,u=d.bottom===!0):s===`clip`?(l=!1,u=!0):(l=!0,u=!0);let f=t?.transition===`none`?`none`:`auto`,p=t?.completeDisplay===`card`?`card`:`inline`;return{streamingView:n,viewMode:r,streamingHeight:i,completeHeight:a,followOutput:c,overflow:s,fadeTop:l,fadeBottom:u,transition:f,completeDisplay:p}}function ix(e,t){let n=Qb(e),r=t.config?.features?.artifacts,{chromeEnabled:i,showCopy:a,showExpand:o,showViewToggle:s}=nx(r),c=r?.inlineActions??[],l=rx(r),d=l.completeDisplay===`card`,f=null,p=n,m=B(`div`,`persona-artifact-inline persona-w-full persona-max-w-full`);m.setAttribute(`data-persona-theme-zone`,`artifact-inline`),n.id&&m.setAttribute(`data-artifact-inline`,n.id);let h=e=>Jb(ex(e),t),g=null,_=e=>{g?.destroy(),g=null,m.classList.add(`persona-artifact-inline--card`),m.style.removeProperty(mx),m.replaceChildren(h(e)),ax.set(m,e=>{m.replaceChildren(h(e))})};if(d&&n.status===`complete`)return _(n),m;let v=Rb(n,{config:t.config,bodyLayout:l,resolveViewMode:()=>f??l.viewMode});g=v;let y=B(`div`,`persona-artifact-inline-body`);y.appendChild(v.el);let b=e=>{let t=e.status!==`complete`,n=t?l.streamingHeight:l.completeHeight,r=typeof n==`number`;r?m.style.setProperty(mx,`${n}px`):m.style.removeProperty(mx);let i=!!v.el.querySelector(`.persona-code-pre`),a=!!v.el.querySelector(`iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view`);y.classList.toggle(`persona-artifact-content-flush`,i),y.classList.toggle(`persona-artifact-inline-body--sized`,r&&a),y.classList.toggle(`persona-artifact-inline-body--cap`,!t&&!a&&typeof l.completeHeight==`number`)},x=n.status,S=(e,t)=>{x!==`complete`&&e.status===`complete`?(typeof l.completeHeight==`number`?m.style.setProperty(mx,`${l.completeHeight}px`):m.style.removeProperty(mx),jb(y,t?.suppressTransition?`none`:l.transition,e.id,()=>{v.update(e),b(e)})):v.update(e),b(e),x=e.status};b(n);let C=l.overflow===`clip`&&o&&!!n.id;if(C&&(y.setAttribute(`data-expand-artifact-inline`,n.id),y.setAttribute(`role`,`button`),y.setAttribute(`tabindex`,`0`),y.classList.add(`persona-cursor-pointer`),y.setAttribute(`aria-label`,`Open ${$b(n).title} in panel`)),!i)return m.appendChild(y),ax.set(m,S),m;let w=B(`div`,`persona-artifact-inline-chrome`);w.setAttribute(`data-persona-theme-zone`,`artifact-inline-chrome`);let T=B(`div`,`persona-artifact-inline-chrome-lead`),E=B(`span`,`persona-flex persona-items-center persona-flex-shrink-0`),D=j(u.FileText,16,`currentColor`,2);D&&E.appendChild(D);let O=B(`span`,`persona-artifact-inline-title persona-truncate persona-min-w-0`),k=B(`span`,`persona-artifact-inline-type`);T.append(E,O,k);let A=B(`div`,`persona-artifact-inline-chrome-actions`),ee=B(`span`,`persona-flex persona-items-center persona-gap-1`),M=()=>f??l.viewMode,N=s?xg({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:M(),className:`persona-artifact-toggle-group persona-flex-shrink-0`,onSelect:e=>{let t=e===`source`?`source`:`rendered`;t!==M()&&(f=t,v.update(p),b(p))}}):null,P=a?yg({icon:`copy`,label:`Copy`,className:`persona-artifact-doc-icon-btn persona-flex-shrink-0`}):null;P&&n.id&&P.setAttribute(`data-copy-artifact`,n.id);let te=o?yg({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),A.appendChild(ee),N&&A.appendChild(N.element),P&&A.appendChild(P),te&&A.appendChild(te),w.append(T,A),m.append(w,y);let ne=e=>{let{title:t,typeLabel:n}=$b(e);O.textContent=t,O.title=t,C&&y.setAttribute(`aria-label`,`Open ${t} in panel`);let i=e.status!==`complete`;if(i){k.classList.contains(`persona-artifact-inline-status`)||(k.className=`persona-artifact-inline-status`,k.removeAttribute(`data-preserve-animation`),k.replaceChildren());let t=$y(e,r,`inline-chrome`);tb(k,t,r)}else Zy(e.id),k.className=`persona-artifact-inline-type`,k.removeAttribute(`data-preserve-animation`),k.replaceChildren(),k.textContent=n;if(P&&P.classList.toggle(`persona-hidden`,i),N){let t=e.artifactType===`markdown`?e.file:void 0,n=!1;if(!i&&t&&l.viewMode!==`source`){let e=Ly(t);e===`markdown`?n=!0:(e===`html`||e===`svg`)&&(n=r?.filePreview?.enabled!==!1)}N.element.classList.toggle(`persona-hidden`,!n),N.setSelected(M())}if(ee.replaceChildren(),!i&&c.length>0){let t=Uy(e);if(t)for(let e of c)try{if(e.visible===void 0||e.visible(t)){let t=Hy(e,{documentChrome:!0});t.setAttribute(`data-artifact-custom-action`,e.id),t.classList.add(`persona-flex-shrink-0`),ee.appendChild(t)}}catch{}}};return ne(n),ax.set(m,(e,t)=>{if(d&&x!==`complete`&&e.status===`complete`){let t=m.isConnected?m.getBoundingClientRect().height:0;x=`complete`;let n=e,r=!1,i=e=>{n=e,r=!0};ax.set(m,i),tx(m,t,{swap:()=>{_(n),r=!1,ax.set(m,i)},onSettled:()=>{r?_(n):ax.set(m,e=>{m.replaceChildren(h(e))})}})}else(e.status!==`complete`||e.id!==p.id)&&(f=null),p=e,S(e,t),ne(e)}),m}var ax,ox,sx,cx,lx,ux,dx,fx,px,mx,hx,gx=o((()=>{H(),Vy(),sb(),Gy(),wg(),ee(),Hb(),Yb(),ax=/* @__PURE__ */ new WeakMap,ox=180,sx=240,cx=.8,lx=300,ux=500,dx=`cubic-bezier(0.2, 0, 0, 1)`,fx=240,px=.35,mx=`--persona-artifact-inline-body-height`,hx=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let r=typeof e.title==`string`&&e.title?e.title:`Untitled artifact`,i=typeof e.artifactId==`string`?e.artifactId:``,a=e.status===`streaming`?`streaming`:`complete`,o=n({artifact:{artifactId:i,title:r,artifactType:typeof e.artifactType==`string`?e.artifactType:`markdown`,status:a},config:t.config,defaultRenderer:()=>ix(e,t)});if(o)return o}return ix(e,t)}})),_x=o((()=>{Kb(),gx(),Yb(),Hb(),Vy(),Ob(),At(),He()})),vx=/* @__PURE__ */ s({PersonaArtifactCard:()=>Jb,PersonaArtifactInline:()=>hx,__provideMarkdownParsers:()=>Ot,__setIconsExtraLoader:()=>Be,artifactCopyText:()=>kb,createArtifactPane:()=>Gb,downloadInfoFor:()=>zy,hasLiveInlineArtifactBlock:()=>Zb,initArtifactsUi:()=>Eb,triggerArtifactDownload:()=>By,updateInlineArtifactBlocks:()=>Xb}),yx=o((()=>{_x()}));Pe(),Ny(),At(),He();const bx=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:xx,load:Sx,provide:Cx,getSync:wx}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(yx(),vx))});let Tx=null;const Ex=/* @__PURE__ */ new Set,Dx=e=>{if(Tx)return Tx;Tx=e,e.initArtifactsUi({componentRegistry:My});for(let t of bx)My.has(t)||My.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=kt();t?e.__provideMarkdownParsers(t):Dt(()=>{let t=kt();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Ve());let n=[...Ex];Ex.clear();for(let e of n)try{e()}catch{}return e},Ox=()=>Sx().then(Dx),kx=()=>{if(Tx)return Tx;let e=wx();return e?Dx(e):null},Ax=e=>Tx?()=>{}:(Ex.add(e),()=>{Ex.delete(e)});function jx(e){return e?.features?.artifacts?.enabled===!0}function Mx(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`),!jx(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function Nx(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`)}const Px=[`panel`,`seamless`,`detached`];function Fx(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Px.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function Ix(e){return!e||!jx(e)?!1:Fx(e)===`detached`}function Lx(e,t){if(!jx(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`),Nx(e),Mx(e,t);return}let n=t.features?.artifacts?.layout,r=Fx(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),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 i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[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[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}Mx(e,t)}function Rx(e,t){for(let t of Px)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!jx(t))return;let n=t.features?.artifacts?.layout,r=Fx(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function zx(e,t){return!t||!jx(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}an();const Bx=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),Vx=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),Hx=/* @__PURE__ */ new Set([`markdown`,`component`]),Ux=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Wx=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gx=e=>!Bx.has(e),Kx=e=>typeof e==`string`&&Vx.has(e),qx=e=>Object.keys(e).length>0;function Jx(e,t,n,r){e.push({path:t,code:n,message:r})}const Yx=`Ignored an unsupported value.`,Xx={kind:`mode`,message:Yx},Zx={kind:`string`,message:`Expected a CSS length string.`},Qx={kind:`boolean`},$x={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:Qx,showReasoning:Qx,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:Yx},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:Yx},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:Yx},expandable:Qx,grouped:Qx}},reasoningDisplay:{kind:`object`,children:{expandable:Qx,activePreview:Qx}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:Xx,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:Xx,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:Hx,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:Hx}}},filePreview:{kind:`object`,children:{enabled:Qx}},layout:{kind:`object`,children:{paneWidth:Zx,paneMaxWidth:Zx,paneMinWidth:Zx,expandedPanelWidth:Zx,resizableMinWidth:Zx,resizableMaxWidth:Zx,expandLauncherPanelWhenOpen:Qx,resizable:Qx}}}}}};function eS(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:Jx(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:Jx(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:Jx(r,n,`invalid_value`,t.message);case`mode`:return Kx(e)?Qt(e):Jx(r,n,`invalid_value`,t.message);case`modeMap`:{if(!Wx(e))return Jx(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:$t(t);Gx(t)&&(i?i.has(t):Ux.test(e))?Kx(o)?a[e]=Qt(o):Jx(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):Jx(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return qx(a)?a:void 0}case`object`:{if(t.bareMode&&Kx(e))return Qt(e);if(!Wx(e))return Jx(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!Gx(t)||!i.includes(t))&&Jx(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=eS(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&Jx(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=Wx(l)&&Wx(s)?{...l,...s}:s}return qx(o)?o:void 0}}}function tS(e){let t=[];return{preferences:(e===null?void 0:eS(e,$x,``,t))??{},issues:t}}function nS(e){if(Array.isArray(e))return e.map(nS);if(!Wx(e))return e;let t={};for(let[n,r]of Object.entries(e))Gx(n)&&r!==void 0&&(t[n]=nS(r));return t}function rS(e,t){let n=nS(e);for(let[e,r]of Object.entries(t)){if(!Gx(e)||r===void 0)continue;let t=n[e];n[e]=Wx(t)&&Wx(r)?rS(t,r):nS(r)}return n}function iS(e){let t={},n;for(let r of e){let e=tS(r).preferences;n=oS(n,e.artifacts?.display),t=rS(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function aS(e,t){if(t===void 0)return e===void 0?void 0:nS(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...qx(i)?{byMediaType:i}:{}};return qx(a)?a:void 0}function oS(e,t){if(t===void 0)return e===void 0?void 0:nS(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=aS(n.files,t.files),o={...r?{default:r}:{},...qx(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return qx(o)?o:void 0}function sS(e={},t){let n=iS(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=oS(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function cS(e){let t=e.preferences;return!t||!qx(t)?e:{...e,features:sS(e.features??{},[t])}}function lS(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 uS(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 dS(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function fS(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function pS(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function mS(e,t,n,r,i,a,o=200){let s=lS(i,200),c=fS(t,n,r,o);c=Math.max(s,c);let l=uS(a);return l!==null&&(c=Math.min(c,l)),dS(e,s,c)}var hS,gS,_S=o((()=>{H(),hS={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`}},gS=(e,t,n,r)=>{let i=e.querySelectorAll(`[data-tv-form]`);i.length&&i.forEach(e=>{if(e.dataset.enhanced===`true`)return;let i=e.dataset.tvForm??`init`;e.dataset.enhanced=`true`;let a=hS[i]??hS.init;e.classList.add(`persona-form-card`,`persona-space-y-4`);let o=B(`div`,`persona-space-y-1`),s=B(`h3`,`persona-text-base persona-font-semibold persona-text-persona-primary`);if(s.textContent=a.title,o.appendChild(s),a.description){let e=B(`p`,`persona-text-sm persona-text-persona-muted`);e.textContent=a.description,o.appendChild(e)}let c=document.createElement(`form`);c.className=`persona-form-grid persona-space-y-3`,a.fields.forEach(e=>{let n=B(`label`,`persona-form-field persona-flex persona-flex-col persona-gap-1`);n.htmlFor=`${t.id}-${i}-${e.name}`;let r=B(`span`,`persona-text-xs persona-font-medium persona-text-persona-muted`);r.textContent=e.label,n.appendChild(r);let a=e.type??`text`,o;a===`textarea`?(o=document.createElement(`textarea`),o.rows=3):(o=document.createElement(`input`),o.type=a),o.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`,o.id=`${t.id}-${i}-${e.name}`,o.name=e.name,o.placeholder=e.placeholder??``,e.required&&(o.required=!0),n.appendChild(o),c.appendChild(n)});let l=B(`div`,`persona-flex persona-items-center persona-justify-between persona-gap-2`),u=B(`div`,`persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]`),d=B(`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`);d.type=`submit`,d.textContent=a.submitLabel??`Submit`,l.appendChild(u),l.appendChild(d),c.appendChild(l),e.replaceChildren(o,c),c.addEventListener(`submit`,async e=>{e.preventDefault();let t=n.formEndpoint??`/form`,a=new FormData(c),o={};a.forEach((e,t)=>{o[t]=e}),o.type=i,d.disabled=!0,u.textContent=`Submitting…`;try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!e.ok)throw Error(`Form submission failed (${e.status})`);let n=await e.json();u.textContent=n.message??`Thanks! We'll be in touch soon.`,n.success&&n.nextPrompt&&await r.sendMessage(String(n.nextPrompt))}catch(e){u.textContent=e instanceof Error?e.message:`Something went wrong. Please try again.`}finally{d.disabled=!1}})})}})),vS=/* @__PURE__ */ s({enhanceWithForms:()=>gS,formDefinitions:()=>hS}),yS=o((()=>{_S()}));Pe();const{setLoader:bS,load:xS,provide:SS,getSync:CS}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(yS(),vS))}),wS=xS,TS=CS,ES=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}};Ae(),_e(),le();const DS=e=>typeof e==`object`&&!!e&&!Array.isArray(e),OS=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),kS=(e,t,n)=>{if(!DS(e)||!DS(t)||OS.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=kS(e[i],t[i],a)}return r};function AS(e,t){let n=te(ke),r=ae(e,t,n),i=F(oe(kS(e,t,``),n,r),r);return me(ye(i),ge(e,t))}const jS=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},MS=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},NS=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},PS=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=MS(e),n=NS(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},FS=e=>typeof e==`string`?e:e==null?``:String(e),IS={message:e=>{if(e.type===`message`)return{handled:!0,displayText:FS(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=FS(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:FS(n.text)}}},LS=e=>Array.isArray(e)?e.map(e=>String(e)):[],RS=e=>{let t=new Set(LS(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(LS(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.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 a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},zS=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},BS=e=>e.map(e=>({...e,streaming:!1})),VS=e=>e.map(e=>({...e,status:`complete`})),HS=e=>`${e??`persona-`}state`,US=(e=HS())=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?zS(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?BS(n.messages):void 0,artifacts:n.artifacts?VS(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},WS=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,`0`)},GS=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return WS(e)},KS=async(e,t)=>{let n=await GS(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await GS(`${e}\0${t}`)}`}},qS=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await KS(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}};function JS(){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 YS=o((()=>{})),XS,ZS=o((()=>{XS=`
|
|
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,11 +1158,11 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1158
1158
|
.persona-history-view .persona-history-skeleton-bar { animation: none; }
|
|
1159
1159
|
.persona-history-rail-host { transition: none; }
|
|
1160
1160
|
}
|
|
1161
|
-
`}));function VS(e){if(!e)return US;let t={...US};for(let n of HS){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}var HS,US,WS=o((()=>{HS=/* @__PURE__ */ `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`.split(`.`),US={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 GS(e){if(!e)return qS;let t={...qS};for(let[n,r]of Object.entries(e))typeof r==`string`&&r.length>0&&(t[n]=r);return t}function KS(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e)}var qS,JS=o((()=>{WS(),qS={...US,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 YS(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function XS(e,t){let n=Date.parse(e);return Number.isFinite(n)?n:t}function ZS(e,t){let n=XS(e,t),r=YS(t);if(n>=r)return`today`;if(n>=r-nC)return`yesterday`;if(n>=r-7*nC)return`previous-7-days`;if(n>=r-30*nC)return`previous-30-days`;let i=new Date(n);return`month:${i.getFullYear()}-${i.getMonth()}`}function QS(e,t,n,r){if(e===`today`)return r.groupToday;if(e===`yesterday`)return r.groupYesterday;if(e===`previous-7-days`)return r.groupPrevious7Days;if(e===`previous-30-days`)return r.groupPrevious30Days;let i=new Date(XS(t,n));return KS(r.groupMonthYear,{month:i.toLocaleString(void 0,{month:`long`}),year:i.getFullYear()})}function $S(e,t,n,r=`time`){let i=e.filter(e=>e.starred),a=i.length>0?[{key:`starred`,label:n.groupStarred,items:i}]:[];if(r===`none`){let t=e.filter(e=>!e.starred);return t.length>0&&a.push({key:`recent`,label:n.conversationsTitle,items:t}),a}for(let r of e){if(r.starred)continue;let e=ZS(r.updatedAt,t),i=a[a.length-1];i&&i.key===e?i.items.push(r):a.push({key:e,label:QS(e,r.updatedAt,t,n),items:[r]})}return a}function eC(e,t,n){let r=Math.max(0,t-XS(e,t)),i=Math.floor(r/6e4);if(i<1)return n.relativeNow;if(i<60)return KS(n.relativeMinutes,{value:i});let a=Math.floor(i/60);if(a<24)return KS(n.relativeHours,{value:a});let o=Math.floor(a/24);if(o<7)return KS(n.relativeDays,{value:o});let s=Math.floor(o/7);return o<365?KS(n.relativeWeeks,{value:s}):KS(n.relativeYears,{value:Math.floor(o/365)})}function tC(e,t){return e===1?t.messageCountLabelOne:KS(t.messageCountLabel,{count:e})}var nC,rC=o((()=>{JS(),nC=864e5}));function iC(e,t=20){let n=document.createElementNS(aC,`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 e of[12,19,5]){let t=document.createElementNS(aC,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,`12`),t.setAttribute(`r`,`1`),n.appendChild(t)}return n}let r=sC[e];if(r){let e=document.createElementNS(aC,`rect`);e.setAttribute(`x`,String(r[0])),e.setAttribute(`y`,String(r[1])),e.setAttribute(`width`,String(r[2])),e.setAttribute(`height`,String(r[3])),e.setAttribute(`rx`,`2`),n.appendChild(e)}for(let t of oC[e]){let e=document.createElementNS(aC,`path`);e.setAttribute(`d`,t),n.appendChild(e)}return n}var aC,oC,sC,cC=o((()=>{aC=`http://www.w3.org/2000/svg`,oC={"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:[]},sC={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}}));function lC(e){let t=B(`span`,{className:`persona-history-row-avatar`,attrs:{"aria-hidden":`true`}});return hC.test(e)?t.appendChild(B(`img`,{attrs:{src:e,alt:``,loading:`lazy`}})):t.textContent=e,t}function uC(e){let{conversation:t,copy:n,busy:r,pending:i}=e,a=r||i!==null,o=t.title.trim().length>0,s=t.starred?(()=>{let e=iC(`star`,11);return e.setAttribute(`fill`,`currentColor`),e.setAttribute(`stroke-width`,`1`),B(`span`,{className:`persona-history-row-star`},e,B(`span`,{className:`persona-history-sr-only`,text:n.groupStarred}))})():null,c=B(`div`,{className:`persona-history-row-head`},B(`span`,{className:`persona-history-row-title persona-history-truncate`,text:o?t.title:t.preview??``}),s,B(`time`,{className:`persona-history-row-time`,attrs:{datetime:t.updatedAt},text:eC(t.updatedAt,e.nowMs,n)})),l=o&&t.preview?B(`span`,{className:`persona-history-row-preview persona-history-truncate`,text:t.preview}):null,u=B(`button`,{className:V(`persona-history-row`,e.active&&`persona-history-row--active`,i&&`persona-history-row--${i}`),attrs:{type:`button`,"data-persona-history-focus":gC(t.id),"data-persona-history-conversation":t.id,...e.active?{"aria-current":`page`}:{},...a?{"aria-disabled":`true`}:{},...i?{"aria-busy":`true`}:{}}},e.avatar?lC(e.avatar):null,B(`div`,{className:`persona-history-row-body`},c,l,B(`span`,{className:`persona-history-row-count persona-history-sr-only`,text:tC(t.messageCount,n)})));u.addEventListener(`click`,()=>{a||e.onOpen()});let d=e.showDelete?fC({className:`persona-history-row-menu-button`,label:`${n.rowActionsLabel}: ${t.title}`,focusKey:_C(t.id),open:e.menuOpen,inert:a,onToggle:e.onToggleMenu}):null;return B(`li`,{className:V(`persona-history-item`,!e.showDelete&&`persona-history-item--no-menu`),attrs:{"data-persona-history-item":t.id}},u,d,e.menuOpen&&e.showDelete?dC(e):null,e.error?mC(e.error,n,t.id):null)}function dC(e){let{conversation:t,copy:n}=e;return pC({label:`${n.rowActionsLabel}: ${t.title}`,items:[{label:n.deleteConversationLabel,focusKey:vC(t.id),danger:!0,onSelect:e.onDelete}],onCloseMenu:e.onCloseMenu})}function fC(e){let t=B(`button`,{className:V(`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(iC(`ellipsis`,e.iconSize));let n=()=>t.getAttribute(`aria-disabled`)===`true`;return t.addEventListener(`click`,t=>{t.stopPropagation(),!n()&&e.onToggle()}),t.addEventListener(`keydown`,r=>{(r.key===`ArrowDown`||r.key===`ArrowUp`)&&(r.preventDefault(),!(n()||t.getAttribute(`aria-expanded`)===`true`)&&e.onToggle())}),t}function pC(e){let t=B(`div`,{className:`persona-history-menu`,attrs:{role:`menu`,"aria-label":e.label}});for(let n of e.items){let r=B(`button`,{className:V(`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}});r.addEventListener(`click`,()=>{e.onCloseMenu(),n.onSelect()}),t.appendChild(r)}return t.addEventListener(`keydown`,n=>{let r=Array.from(t.querySelectorAll(`[role="menuitem"]`));if(r.length===0)return;let i=r.indexOf(document.activeElement);n.key===`Tab`?e.onCloseMenu({restoreFocus:!0}):n.key===`ArrowDown`?(n.preventDefault(),r[(i+1+r.length)%r.length]?.focus()):n.key===`ArrowUp`?(n.preventDefault(),r[(i-1+r.length)%r.length]?.focus()):n.key===`Home`?(n.preventDefault(),r[0]?.focus()):n.key===`End`&&(n.preventDefault(),r[r.length-1]?.focus())}),t}function mC(e,t,n){let r=B(`button`,{className:`persona-history-secondary persona-history-state-action`,text:t.retryLabel,attrs:{type:`button`,"data-persona-history-focus":`row-retry:${n}`}});return r.addEventListener(`click`,e.retry),B(`div`,{className:`persona-history-row-error`,attrs:{role:`alert`}},B(`span`,{text:e.message}),r)}var hC,gC,_C,vC,yC=o((()=>{H(),cC(),rC(),hC=/^(https?:|\/|data:)/i,gC=e=>`row:${e}`,_C=e=>`menu:${e}`,vC=e=>`menu-item:${e}`}));function bC(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 xC(e){if(no(e)){if(e.code===`rate_limited`)return{kind:`rate_limited`,retryAfterSeconds:e.retryAfterSeconds??0};let t=bC(e.code);return{kind:`error`,reason:t,retryable:t!==`unsupported_scope`}}return{kind:`error`,reason:`unknown`,retryable:!0}}function SC(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 CC(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 wC(e,t,n,r){let i=B(`button`,{className:`persona-history-secondary persona-history-state-action`,text:e,attrs:{type:`button`,"data-persona-history-focus":t,...n?{"aria-disabled":`true`}:{}}});return i.addEventListener(`click`,()=>{n||r()}),i}function TC(e,t,n,r,i){return B(`div`,{className:`persona-history-state`,attrs:{"data-persona-history-state":e,...i?{role:`alert`}:{role:`status`}}},B(`p`,{className:`persona-history-state-title`,text:t}),B(`p`,{className:`persona-history-state-description`,text:n}),r)}function EC(e){let t=[`42%`,`58%`,`34%`],n=[`94%`,`78%`,`88%`],r=[0,1,2].map(e=>B(`div`,{className:`persona-history-skeleton-row`,attrs:{"aria-hidden":`true`}},B(`div`,{className:`persona-history-skeleton-head`},B(`div`,{className:`persona-history-skeleton-bar persona-history-skeleton-bar--title`,style:{width:t[e]}}),B(`div`,{className:`persona-history-skeleton-bar persona-history-skeleton-bar--time`})),B(`div`,{className:`persona-history-skeleton-bar persona-history-skeleton-bar--preview`,style:{width:n[e]}})));return B(`div`,{className:`persona-history-view-loading`,attrs:{"data-persona-history-state":`loading`,role:`status`,"aria-label":e.loadingLabel}},...r)}function DC(e){let{state:t,copy:n,busy:r}=e;if(t.kind===`loading`)return EC(n);if(t.kind===`empty`){let t=SC(e.identityStatus,n);return t?TC(`identity`,t.title,t.description,e.onRetry?wC(n.retryIdentityLabel,`state-retry`,r,e.onRetry):null,!0):TC(`empty`,n.emptyTitle,n.emptyDescription,null,!1)}if(t.kind===`rate_limited`){let i=t.retryAfterSeconds>0?KS(n.rateLimitedWaitDescription,{seconds:t.retryAfterSeconds}):n.rateLimitedDescription;return TC(`rate_limited`,n.rateLimitedTitle,i,e.onRetry?wC(n.retryLabel,`state-retry`,r,e.onRetry):null,!1)}if(t.kind===`new_conversation_required`)return TC(`new_conversation_required`,n.newConversationRequiredTitle,n.newConversationRequiredDescription,e.onStartNew?wC(n.newConversationLabel,`state-retry`,r,e.onStartNew):null,!0);let{title:i,description:a}=CC(t.reason,n),o=t.reason===`authentication_required`||t.reason===`authentication_failed`||t.reason===`identity_provider_failed`?n.retryIdentityLabel:n.retryLabel;return TC(`error`,i,a,t.retryable&&e.onRetry?wC(o,`state-retry`,r,e.onRetry):null,!0)}var OC=o((()=>{H(),JS(),io()}));function kC(e){return`${e.state}:${`reason`in e?e.reason:``}`}function AC(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 jC(e){return e.state===`verified`||e.state===`browser_only`}function MC(e){return e.state===`authentication_required`||e.state===`identity_provider_failed`||e.state===`configuration_error`}function NC(e){let t=GS(e.copy),n=e.now??(()=>Date.now()),r=e.pageSize??PC,i=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,a=[],o=null,s={kind:`loading`,phase:`initial`},c=null,l=e.activeConversationId,u=e.provider.getIdentityStatus(),d=kC(u),f=null,p=!1,m=!1,h=0,g=e.presentation,_=e.collapsible!==!1,v=e.collapsed===!0,y=e.railSide===`right`,b=e.renderDom!==!1,x=/* @__PURE__ */ new Map,S=null,C=LS(),w=t=>{!b&&e.onAnnounce?e.onAnnounce(t):C.announce(t)},T=()=>c!==null,E=`${i}-body`,D=B(`button`,{className:`persona-history-icon-button persona-history-back`,attrs:{type:`button`}}),O=()=>g===`rail`&&_,k,A=()=>{if(e.railBrand){if(!O())D.classList.remove(`persona-history-back--branded`);else{if(k===void 0){let t=e.railBrand(!0);k=t?B(`span`,{className:`persona-history-brand-mark persona-history-toggle-brand`,attrs:{"aria-hidden":`true`}},t):null}k&&(D.classList.add(`persona-history-back--branded`),D.appendChild(k))}}},j=()=>{let n=O(),r=g===`rail`;D.setAttribute(`data-persona-history-focus`,n?`collapse`:`close`),D.setAttribute(`aria-label`,n?v?t.expandLabel:t.collapseLabel:r?t.closeLabel:t.backLabel),n?(D.setAttribute(`aria-expanded`,v?`false`:`true`),D.setAttribute(`aria-controls`,E),e.collapseShortcut?.aria&&D.setAttribute(`aria-keyshortcuts`,e.collapseShortcut.aria)):(D.removeAttribute(`aria-expanded`),D.removeAttribute(`aria-controls`),D.removeAttribute(`aria-keyshortcuts`)),D.replaceChildren(iC(n?`panel-left`:r?`x`:`arrow-left`)),A()};j(),D.addEventListener(`click`,()=>{O()?e.onToggleCollapse?.():e.onClose()});let M=B(`h2`,{className:`persona-history-title`,text:t.viewTitle,attrs:{id:i}}),ee=B(`span`,{className:`persona-history-scope-title`}),N=B(`p`,{className:`persona-history-scope`},B(`span`,{className:`persona-history-scope-icon`,attrs:{"aria-hidden":`true`}},iC(`monitor`,14)),ee),P=B(`div`,{className:`persona-history-heading-group`},M),F=!1,te,ne=()=>{let n=g===`rail`,r=n?e.renderRailHeader:void 0,i=null,a=r!==void 0;if(r)try{i=r({collapsed:v,defaultTitle:t.viewTitle})}catch(e){a=!1,F||(F=!0,console.warn(`[persona] history rail renderHeader threw`,e))}if(!a&&n&&e.railBrand){if(te===void 0){let n=e.railBrand(!1);te=n?B(`span`,{className:`persona-history-heading-brand`,attrs:{"aria-hidden":`true`}},B(`span`,{className:`persona-history-brand-mark`},n),B(`span`,{className:`persona-history-wordmark`,text:t.viewTitle})):null}te&&(a=!0,i=te)}M.classList.toggle(`persona-history-sr-only`,a),P.replaceChildren(M),i&&P.appendChild(i)};ne();let I=B(`button`,{className:`persona-history-icon-button persona-history-new-icon`,attrs:{type:`button`,"data-persona-history-focus":`new-icon`,"aria-label":t.newConversationLabel}});I.appendChild(iC(`plus`)),I.addEventListener(`click`,()=>void it());let re=[D,I].map(t=>e.attachTooltip?.({anchor:t,text:()=>t.getAttribute(`aria-label`)??``,...t===D&&e.collapseShortcut?{hint:()=>O()?e.collapseShortcut.hint:``}:{}})),ie=B(`div`,{className:`persona-history-topbar`}),ae=null,oe=()=>{let e=g===`rail`,t=e?y?`rail-right`:`rail`:`panel`;t!==ae&&(ae=t,t===`rail`?ie.append(P,D):ie.append(D,P),e?I.remove():ie.appendChild(I),H.classList.toggle(`persona-history-view--rail-right`,t===`rail-right`))},se=B(`div`,{className:`persona-history-scope-alert`}),ce=`${i}-scope`,le=iC(`plus`,18),L=B(`button`,{className:`persona-history-new`,attrs:{type:`button`,"data-persona-history-focus":`new`}},le,B(`span`,{text:t.newConversationLabel}));L.addEventListener(`click`,()=>void it());let R=B(`div`,{className:`persona-history-list-region`}),ue=e.showDeleteAll!==!1,de=!!e.provider.resetDevice,fe=e.listActions??[],pe=ue||de||fe.length>0?fC({className:`persona-history-list-options`,label:t.listOptionsLabel,focusKey:`menu:${FC}`,open:!1,inert:!0,iconSize:16,onToggle:()=>Ze(FC)}):null,me=B(`h3`,{className:`persona-history-conversations-title`,text:t.conversationsTitle}),he=B(`div`,{className:`persona-history-caption`,attrs:{"data-persona-history-item":FC}},me,e.showScopeStatus?N:null,pe),z=B(`div`,{className:`persona-history-body`,attrs:{id:E}},e.showScopeStatus?se:null,L,he,R),ge=e.headerPlacement??`inline`;ge===`external`&&ie.classList.add(`persona-history-topbar--shell`,`persona-history-topbar--shell-enter`);let H=B(`div`,{className:V(`persona-history-view`,`persona-history-view--${e.presentation}`,`persona-history-view--enter`),attrs:{role:`region`,"aria-labelledby":i,"data-persona-history-presentation":e.presentation}},C.element,ge===`inline`?ie:null,z),_e=()=>{H.classList.toggle(`persona-history-view--rail-collapsed`,v&&O())};_e(),oe();let ve=(e,t)=>{let n=`${i}-s${t}`,r=B(`div`,{className:V(`persona-history-nav`,e.placement===`footer`&&`persona-history-nav--footer`),attrs:{role:`group`,"data-persona-rail-section":e.id,...e.title?{"aria-labelledby":n}:{"aria-label":e.id}}});e.title&&r.appendChild(B(`h3`,{className:`persona-history-group-heading`,text:e.title,attrs:{id:n}}));for(let t of e.items){let e=t.iconNode?.()??null,n=B(`button`,{className:V(`persona-history-nav-item`,e&&`persona-history-nav-item--icon`),attrs:{type:`button`,"aria-label":t.label,"data-persona-rail-item":t.id}},e?B(`span`,{className:`persona-history-nav-icon`},e):null,B(`span`,{className:`persona-history-nav-label persona-history-truncate`,text:t.label}),t.badge?B(`span`,{className:`persona-history-nav-badge`,text:t.badge}):null);n.addEventListener(`click`,()=>t.onSelect()),r.appendChild(n)}return r},ye=null,be=null,xe=()=>{ye&&b&&g===`rail`&&v!==be&&(be=v,e.railSections.forEach((e,t)=>{if(!e.render)return;let n=ye[t],r=e.title?n.firstElementChild:null,i=null;try{i=e.render(v)}catch(t){e.render=void 0,console.warn(`[persona] history rail section threw`,e.id,t)}n.replaceChildren(...r?[r]:[],...i?[i]:[]),n.hidden=!i}))},Se=()=>{let t=e.railSections;if(H.classList.toggle(`persona-history-view--has-nav`,g===`rail`&&!!t?.some(e=>e.placement===`above-conversations`)),t?.length){if(g!==`rail`)ye?.forEach(e=>e.remove());else{ye??=t.map(ve);for(let e of[`above-conversations`,`below-conversations`,`footer`]){let n=e===`above-conversations`?he.parentNode===z?he:R:null;t.forEach((t,r)=>{t.placement===e&&z.insertBefore(ye[r],n)})}xe()}}};Se(),Os(H,`persona-history-view`,zS);let Ce=(e,t)=>{let n=H.ownerDocument.defaultView?.getComputedStyle(H).getPropertyValue(e),r=Number.parseFloat(n??``);return Number.isFinite(r)&&r>=0?r:t},we=(e,t)=>H.ownerDocument.defaultView?.getComputedStyle(H).getPropertyValue(e).trim()||t,Te=null,Ee=()=>{Te!==null&&(clearTimeout(Te),Te=null),H.removeEventListener(`animationend`,Ee),H.classList.remove(`persona-history-view--enter`)};H.addEventListener(`animationend`,Ee),Te=setTimeout(()=>{Te=setTimeout(Ee,Ce(`--persona-history-enter-ms`,IC)+60)},0);let De=null,Oe=()=>{De!==null&&(clearTimeout(De),De=null),ie.classList.remove(`persona-history-topbar--shell-enter`)},ke=()=>{Oe(),ie.classList.add(`persona-history-topbar--shell-enter`),De=setTimeout(Oe,180)};ge===`external`&&(De=setTimeout(Oe,180));let Ae=[],je=null,Me=()=>{if(je)return je;if(m||BC()||typeof H.animate!=`function`)return Ee(),null;let e=H.ownerDocument.defaultView?.getComputedStyle(z).opacity||`1`;Ee(),H.style.pointerEvents=`none`,Pe.style.pointerEvents=`none`;let t={duration:Ce(`--persona-history-exit-ms`,LC),easing:we(`--persona-history-exit-easing`,RC),fill:`forwards`},n=zC[g];return Ae=[z.animate([{opacity:e,transform:`none`},{opacity:0,transform:`translateX(${n}px)`}],t)],je=Promise.all(Ae.map(VC)).then(()=>void 0),je},Ne=(e,t)=>{e&&(t?e.setAttribute(`aria-disabled`,`true`):e.removeAttribute(`aria-disabled`))},Pe=ie,Fe=null,Ie=()=>{let n=e.slots?.header;if(!n)return;let r=`${g}|${kC(u)}|${c?`${c.kind}:${`conversationId`in c?c.conversationId:``}`:``}`;if(r===Fe)return;Fe=r;let i=n({identityStatus:u,pendingAction:c,copy:t,defaultRenderer:()=>ie})??ie;i!==Pe&&(Pe.replaceWith(i),Pe=i)},Le=null,Re=()=>{if(!e.showScopeStatus)return;let n=kC(u);if(n===Le)return;Le=n;let r=AC(u,t);ee.textContent=r.title;let i=jC(u);if(N.hidden=!i,se.replaceChildren(...i?[]:[B(`span`,{className:`persona-history-scope-alert-title`,text:r.title})],B(`span`,{className:`persona-history-scope-description`,text:r.description,attrs:{id:ce}})),se.setAttribute(`data-persona-history-scope-tone`,i?`ambient`:`attention`),i?N.setAttribute(`aria-describedby`,ce):N.removeAttribute(`aria-describedby`),r.pending?se.setAttribute(`role`,`status`):se.removeAttribute(`role`),se.setAttribute(`data-persona-history-identity`,u.state),N.setAttribute(`data-persona-history-identity`,u.state),MC(u)){let e=B(`button`,{className:`persona-history-secondary persona-history-state-action`,text:t.retryIdentityLabel,attrs:{type:`button`,"data-persona-history-focus":`identity-retry`}});e.addEventListener(`click`,()=>{T()||et(`refresh`)}),se.appendChild(e)}},U=e=>c?c.kind===`open`&&c.conversationId===e?`opening`:c.kind===`delete`&&c.conversationId===e?`deleting`:null:null,ze=()=>{let e=document.activeElement;return!(e instanceof HTMLElement)||!H.contains(e)?null:e.getAttribute(`data-persona-history-focus`)},Be=e=>{if(p&&f){p=!1;let e=H.querySelector(`[data-persona-history-focus="${vC(f)}"]`);if(e){e.focus();return}}e&&H.querySelector(`[data-persona-history-focus="${e}"]`)?.focus()},Ve=()=>{if(!S)return null;let e=B(`button`,{className:`persona-history-secondary persona-history-state-action`,text:t.retryLabel,attrs:{type:`button`,"data-persona-history-focus":`action-retry`}}),n=S;return e.addEventListener(`click`,()=>{T()||n.retry()}),B(`div`,{className:`persona-history-row-error`,attrs:{role:`alert`}},B(`span`,{text:n.message}),e)},He=()=>$S(a,n(),t,e.grouping).map((r,a)=>{let o=`${i}-g${a}`,s=B(`ul`,{className:`persona-history-list`,attrs:{"aria-labelledby":o}});for(let i of r.items){let r=()=>uC({conversation:i,active:i.id===l,pending:U(i.id),busy:T(),menuOpen:f===i.id,error:x.get(i.id)??null,avatar:e.rowAvatar,showDelete:e.showDelete!==!1,nowMs:n(),copy:t,onOpen:()=>void nt(i.id),onToggleMenu:()=>Ze(i.id),onCloseMenu:e=>Xe(e),onDelete:()=>void rt(i.id)}),a=e.slots?.conversation?.({conversation:i,active:i.id===l,pending:U(i.id),open:()=>nt(i.id),requestDelete:()=>rt(i.id),defaultRenderer:r})??r();s.appendChild(a instanceof HTMLLIElement?a:B(`li`,{className:`persona-history-item`},a))}return B(`div`,{className:`persona-history-group`,attrs:{"data-persona-history-group":r.key}},B(`h3`,{className:V(`persona-history-group-heading`,r.key===`recent`&&`persona-history-sr-only`),text:r.label,attrs:{id:o}}),s)}),Ue=()=>{if(!o)return null;let e=c?.kind===`load-more`||s.kind===`loading`&&s.phase===`load-more`,n=B(`button`,{className:`persona-history-secondary persona-history-load-more`,text:e?t.loadingMoreLabel:t.loadMoreLabel,attrs:{type:`button`,"data-persona-history-focus":`load-more`,...e?{"aria-busy":`true`,"aria-disabled":`true`}:{},...T()&&!e?{"aria-disabled":`true`}:{}}});return n.addEventListener(`click`,()=>{T()||et(`load-more`)}),n},We=()=>{let n=ze(),r=[Ve()],i=a.length>0;if(i&&(r.push(...He()),r.push(Ue())),s.kind!==`ready`&&!(s.kind===`loading`&&s.phase!==`initial`&&i)){let n=s,i=n.kind===`loading`?void 0:()=>et(`refresh`),a=n.kind===`new_conversation_required`?()=>it():void 0,o=()=>DC({state:n,copy:t,identityStatus:u,busy:T(),...i?{onRetry:()=>void i()}:{},...a?{onStartNew:()=>void a()}:{}}),c=e.slots?.state?.({state:n,identityStatus:u,copy:t,...i?{retry:i}:{},...a?{startNewConversation:a}:{},defaultRenderer:o});r.push(c??o())}R.replaceChildren(...r.filter(e=>!!e)),Be(n)},Ge=()=>{let e=s.kind===`loading`&&a.length===0,n=[],r=()=>n.length===0?vC(FC):`${vC(FC)}-${n.length}`;if(!e)for(let e of fe)n.push({label:e.label,focusKey:r(),danger:e.danger===!0,onSelect:()=>void e.onSelect({conversations:[...a]})});return ue&&(a.length!==0||s.kind!==`empty`&&!e)&&n.push({label:t.clearHistoryLabel,focusKey:r(),danger:!0,onSelect:()=>void at()}),de&&!e&&n.push({label:t.resetIdentityLabel,focusKey:r(),danger:!0,onSelect:()=>void W()}),n},Ke=()=>{if(Ne(L,T()),Ne(I,T()),pe){let e=Ge(),n=s.kind===`loading`&&a.length===0;pe.hidden=e.length===0&&!n,Ne(pe,T()||e.length===0),pe.setAttribute(`aria-expanded`,f===FC?`true`:`false`);let r=he.querySelector(`.persona-history-menu`);if(f!==FC||e.length===0)r?.remove();else{let n=pC({label:t.listOptionsLabel,items:e,onCloseMenu:e=>Xe(e)});r?r.replaceWith(n):he.appendChild(n)}}he.hidden=g!==`rail`&&(!pe||pe.hidden)&&(!e.showScopeStatus||N.hidden)},qe,Je=()=>{let t=e.onActiveConversationChange;if(!t)return;let n=a.find(e=>e.id===l)??null,r=n?`${n.id}\0${n.title}\0${+!!n.starred}`:``;r!==qe&&(qe=r,t(n))},Ye=()=>{m||(Je(),b?(Ie(),Re(),Ke(),We(),xe()):e.onModelChange?.())},Xe=e=>{if(!f)return;let t=f;f=null,p=!1,Ye(),e?.restoreFocus&&H.querySelector(`[data-persona-history-focus="menu:${t}"]`)?.focus()},Ze=e=>{f===e?Xe({restoreFocus:!0}):(f=e,p=!0,Ye())},Qe=e=>{if(!f)return;let t=e.target;t instanceof Node&&H.contains(t)&&t.closest?.(`[data-persona-history-item="${f}"]`)||Xe()};document.addEventListener(`pointerdown`,Qe,!0);let $e=e=>{e.key===`Escape`&&f&&(e.stopPropagation(),Xe({restoreFocus:!0}))};H.addEventListener(`keydown`,$e);async function et(t){if(m)return;let n=++h,i=t===`load-more`?o:null;if(t!==`load-more`||i){c={kind:t===`load-more`?`load-more`:`refresh`},s={kind:`loading`,phase:t},t!==`load-more`&&(x.clear(),S=null),Xe(),Ye();try{let t=await e.provider.list({limit:r,context:e.context,...i?{cursor:i}:{},...e.targetId?{targetId:e.targetId}:{}});if(m||n!==h)return;a=i?[...a,...t.items]:t.items,o=t.nextCursor,s=a.length===0?{kind:`empty`}:{kind:`ready`}}catch(e){if(m||n!==h)return;s=xC(e)}finally{!m&&n===h&&(c=null,Ye())}}}let tt=e=>{a=a.filter(t=>t.id!==e),x.delete(e),l===e&&(l=null),a.length===0&&!o&&(s={kind:`empty`})};async function nt(n){if(!(T()||m)){x.delete(n),Xe(),c={kind:`open`,conversationId:n},Ye();try{if(await e.onSelect(n),m)return;l=n}catch{if(m)return;x.set(n,{message:t.openFailedLabel,retry:()=>void nt(n)})}finally{m||(c=null,Ye())}}}async function rt(n){if(T()||m)return`cancelled`;x.delete(n),c={kind:`delete`,conversationId:n},Ye();try{let r=await e.onRequestDeleteConversation(n);return m||r===`deleted`&&(tt(n),w(t.conversationRemovedNotice)),r}catch(e){return m||(no(e)&&e.code===`not_found`?tt(n):x.set(n,{message:t.deleteFailedLabel,retry:()=>void rt(n)})),`cancelled`}finally{m||(c=null,Ye())}}async function it(){if(!(T()||m)){S=null,Xe(),c={kind:`start-new`},Ye();try{if(await e.onStartNew(),m)return;s.kind===`new_conversation_required`&&(s=a.length===0?{kind:`empty`}:{kind:`ready`})}catch{if(m)return;S={message:t.errorDescription,retry:()=>void it()}}finally{m||(c=null,Ye())}}}async function at(){if(T()||m)return`cancelled`;S=null,Xe(),c={kind:`clear`},Ye();try{let n=await e.onRequestClearHistory();return m||n===`cleared`&&(a=[],o=null,l=null,s={kind:`empty`},w(t.historyClearedNotice)),n}catch{return m||(S={message:t.errorDescription,retry:()=>void at()}),`cancelled`}finally{m||(c=null,Ye())}}let ot={outcome:`cancelled`};async function W(){if(T()||m||!e.onRequestResetIdentity)return ot;S=null,Xe(),c={kind:`reset`},Ye();try{let n=await e.onRequestResetIdentity();return m||n.outcome===`reset`&&(w(n.remoteRevocationConfirmed?t.identityResetNotice:t.identityResetUnconfirmedNotice),c=null,await et(`refresh`)),n}catch{return m||(S={message:t.errorDescription,retry:()=>void W()}),ot}finally{!m&&c?.kind===`reset`&&(c=null,Ye())}}let st=e.provider.subscribeIdentityStatus(e=>{if(m)return;let n=kC(e),r=n!==d;u=e,d=n,Ye(),r&&e.state!==`verifying`&&w(AC(e,t).title)}),ct=e.provider.subscribeAvailability?.(e=>{m||(e?et(`refresh`):(a=[],o=null,s={kind:`error`,reason:`unavailable`,retryable:!1},Ye()))});return Ye(),et(`initial`),{element:H,copy:t,getModel:()=>({conversations:a,activeConversationId:l,state:s,pendingAction:c,identityStatus:u,nextCursor:o}),operations:{refresh:async()=>{T()||await et(`refresh`)},loadMore:async()=>{T()||await et(`load-more`)},openConversation:e=>nt(e),startNewConversation:()=>it(),requestDeleteConversation:e=>rt(e),requestClearConversationHistory:()=>at(),requestResetHistoryIdentity:()=>W()},setDomRenderEnabled:e=>{e!==b&&(b=e,e&&Ye())},refresh:()=>{et(`refresh`)},setPresentation:e=>{if(e===g)return;Ee(),g=e,Fe=null;let t=e===`rail`;H.classList.toggle(`persona-history-view--panel`,!t),H.classList.toggle(`persona-history-view--rail`,t),H.setAttribute(`data-persona-history-presentation`,e),j(),_e(),oe(),ne(),Se(),Ye()},setCollapsed:e=>{e!==v&&(v=e,_e(),j(),ne(),xe())},setRailSide:e=>{y=e===`right`,oe()},getHeaderElement:()=>Pe,setHeaderPlacement:e=>{if(e===ge)return;ge=e;let t=e===`external`;ie.classList.toggle(`persona-history-topbar--shell`,t),t?(ke(),Pe.remove()):(Oe(),H.insertBefore(Pe,z))},setActiveConversationId:e=>{l!==e&&(l=e,Ye())},applyConversationSummary:e=>{let t=a.findIndex(t=>t.id===e.id);t!==-1&&(a[t]=e,Ye())},removeConversationSummary:e=>{a.some(t=>t.id===e)&&(tt(e),Ye())},setNewConversationRequired:e=>{e?s={kind:`new_conversation_required`}:s.kind===`new_conversation_required`&&(s=a.length===0?{kind:`empty`}:{kind:`ready`}),Ye()},playExit:Me,destroy:()=>{m=!0,h+=1,Ee(),Oe(),re.forEach(e=>e?.destroy()),Pe.remove(),Ae.forEach(e=>e.cancel()),Ae=[],st(),ct?.(),document.removeEventListener(`pointerdown`,Qe,!0),H.removeEventListener(`keydown`,$e),C.destroy(),H.remove(),H.replaceChildren()}}}var PC,FC,IC,LC,RC,zC,BC,VC,HC=o((()=>{Ps(),H(),RS(),BS(),JS(),rC(),cC(),yC(),OC(),io(),PC=25,FC=`persona:list-options`,IC=180,LC=160,RC=`cubic-bezier(0.4, 0, 1, 1)`,zC={panel:20,rail:12},BC=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,VC=e=>e.finished?e.finished.then(()=>void 0,()=>void 0):Promise.resolve()})),UC=o((()=>{HC(),JS()}));function WC(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),r=`persona-history-confirm-title-${n}`,i=`persona-history-confirm-desc-${n}`,a=B(`button`,{className:`persona-history-confirm__cancel`,text:e.cancelLabel,attrs:{type:`button`}}),o=B(`button`,{className:`persona-history-confirm__confirm`,text:e.confirmLabel,attrs:{type:`button`,"data-persona-destructive":`true`}}),s=B(`div`,{className:`persona-history-confirm__dialog`,attrs:{role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":r,"aria-describedby":i},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`}},B(`h2`,{className:`persona-history-confirm__title`,text:e.title,attrs:{id:r},style:{margin:`0`,fontSize:`1rem`,fontWeight:`600`}}),B(`p`,{className:`persona-history-confirm__description`,text:e.description,attrs:{id:i},style:{margin:`0`,fontSize:`0.875rem`,lineHeight:`1.4`}}),B(`div`,{className:`persona-history-confirm__actions`,style:{display:`flex`,gap:`8px`,justifyContent:`flex-end`,flexWrap:`wrap`}},a,o));for(let e of[a,o])e.style.minHeight=`44px`,e.style.minWidth=`88px`,e.style.padding=`0 16px`,e.style.borderRadius=`var(--persona-radius-md, 0.5rem)`,e.style.cursor=`pointer`,e.style.font=`inherit`;a.style.border=`1px solid var(--persona-border, rgba(0,0,0,0.12))`,a.style.background=`transparent`,a.style.color=`inherit`,o.style.border=`none`,o.style.background=`var(--persona-danger, #b42318)`,o.style.color=`var(--persona-danger-fg, #ffffff)`;let c=B(`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))`}},s);return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,c.removeEventListener(`keydown`,l,!0),c.remove(),t?.focus(),n(e))};function l(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),i(!1);return}if(e.key!==`Tab`)return;let t=Array.from(s.querySelectorAll(GC));if(t.length===0)return;let n=t[0],r=t[t.length-1],a=document.activeElement;e.shiftKey&&(a===n||!s.contains(a))?(e.preventDefault(),r.focus()):!e.shiftKey&&a===r&&(e.preventDefault(),n.focus())}c.addEventListener(`keydown`,l,!0),c.addEventListener(`pointerdown`,e=>{e.target===c&&i(!1)}),a.addEventListener(`click`,()=>i(!1)),o.addEventListener(`click`,()=>i(!0)),e.host.appendChild(c),a.focus()})}var GC,KC=o((()=>{H(),GC=`button:not([disabled])`})),qC=/* @__PURE__ */ s({HISTORY_VIEW_COPY_DEFAULTS:()=>qS,createHistoryView:()=>NC,resolveHistoryViewCopy:()=>GS,showHistoryConfirm:()=>WC}),JC=o((()=>{UC(),KC()}));ve();const{setLoader:YC,load:XC}=_e({fallbackImport:()=>Promise.resolve().then(()=>(JC(),qC))}),ZC=XC;function QC(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,c=[],l=()=>{for(let e of c.splice(0))try{e()}catch(e){$C(`renderHistoryView cleanup`,e)}},u=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){$C(e,t)}}return null},d=()=>({presentation:e.getPresentation(),config:n}),f={header:t=>o?u(`renderHistoryHeader`,Object.freeze({...d(),returnSurface:e.getReturnSurface(),identityStatus:ew(t.identityStatus),pendingAction:nw(t.pendingAction),copy:ew(t.copy),actions:Object.freeze({close:h.close,startNewConversation:h.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?u(`renderHistoryConversation`,Object.freeze({...d(),conversation:tw(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?u(`renderHistoryState`,Object.freeze({...d(),state:ew(e.state),identityStatus:ew(e.identityStatus),copy:ew(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},p=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:h}))}))),m=e.createView({slots:f,renderDom:!1,onModelChange:()=>y(),railSections:p}),h=Object.freeze({...m.operations,close:e.close}),g=()=>(o=!0,m.setDomRenderEnabled(!0),m.element),_=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(tw)),activeConversationId:t.activeConversationId,state:ew(t.state),pendingAction:nw(t.pendingAction),identityStatus:ew(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:ew(m.copy),actions:h,defaultRenderer:g,requestRender:()=>y(),onCleanup:e=>{c.push(e)}}),v=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(_(m.getModel()))}catch(t){$C(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(m.element);return o=n,m.setDomRenderEnabled(n),e??m.element};function y(){if(!(!a||r||i)){i=!0;try{l();let t=v();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,y(),{view:m,get element(){return s??m.element},requestRender:y,dispose:()=>{r=!0,l()}}}var $C,ew,tw,nw,rw=o((()=>{$C=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},ew=e=>Object.freeze({...e}),tw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),nw=e=>e?ew(e):null}));function iw(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=ow.get(e.code)??`unavailable`;return new n(t,cw(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,cw(`unavailable`))}function aw(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],i={scopes:r},a=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,cw(`unsupported_scope`))},o=async(t,n)=>{a(t);try{return await n()}catch(t){throw iw(t,e.errors)}},s=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:i,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return o(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return o(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),i=Ha(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:Wa([],i),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return o(t.context.scope,async()=>s(await n().prepareConversationSession(e)))},async prepareStartNew(e){return o(e.context.scope,async()=>s(await n().prepareNewConversationSession()))},async delete(e,t){await o(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return o(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var ow,sw,cw,lw=o((()=>{qa(),ow=/* @__PURE__ */ 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`]]),sw=/* @__PURE__ */ 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.`]]),cw=e=>sw.get(e)??`Conversation history is unavailable right now.`})),uw=/* @__PURE__ */ s({createHistoryShell:()=>dw}),dw,fw=o((()=>{WS(),rw(),H(),om(),Br(),lw(),dw=e=>{let t=VS(e.config.features?.history?.copy),n=null,r=!1,i=null,a=null,o=`conversation`,s=null,c=null,l=null,u=null,d=0,f=null,p=null,m=null,h=`persona-history-${Math.random().toString(36).slice(2,8)}`,g=()=>e.historyFeatureEnabled()&&!!n&&!r,_=()=>{let t=e.session.getStatus();return e.isStreaming||t===`paused`||t===`resuming`},v=()=>{let t=e.config.features?.history?.scope;if(t)return t;let r=e.config.getIdentityProof?`verified-user`:`browser`,i=n?.capabilities.scopes;return!i||i.includes(r)?r:i[0]??r},y=()=>a?.scope??v(),b=()=>e.session.getClientSession()?.targetId??null,x=e=>`${e.state}:${`reason`in e?e.reason:``}`,S=t=>{let n=x(t);n!==u&&(u=n,e.eventBus.emit(`history:identityStatusChanged`,{status:t,timestamp:Date.now()}))},C=null,w=null,T=()=>{if(!e.historyFeatureEnabled())return null;let t=e.getHistoryProviderFactory();if(t)return t();let n=e.config.features?.history?.provider;return n?typeof n==`function`?(C!==n&&(C=n,w=n()),w):n:e.session.isClientTokenMode()?aw({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof==`function`,onActivationCommitted:t=>e.session.bindActivatedSession(t),getClient:()=>e.session.getClient()}):null},E=()=>{p?.(),p=null,m?.(),m=null,r=!1,n=T();let t={...e.historyInternals};n?t.historyProvider=n:delete t.historyProvider,e.historyInternals=t,e.session.setHistoryInternals(e.historyInternals),n&&(p=n.subscribeAvailability?.(e=>{r=!e,e||ft({restoreFocus:!1}),Bt()})??null,m=n.subscribeIdentityStatus(e=>S(e)),u=x(n.getIdentityStatus()))},D=()=>{let t=e.config.features?.history?.presentation??`panel`;if(t===`panel`||t===`auto`&&e.launcherEnabled&&!e.isDockedMountMode(e.config))return`panel`;let n=e.artifactSplitRoot??e.container;return(n.getBoundingClientRect().width||n.clientWidth)>=720?`rail`:`panel`},O=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},k=`data-persona-history-suppressed`,A=null,j=null,M=null,ee=null,N=null,P=``,F=()=>e.header===N?P:e.config.layout?.showHeader===!1?`none`:``,te=()=>e.historyPresentation===`panel`&&!!M&&ee===M.element&&e.config.layout?.showHeader!==!1&&F()!==`none`,ne=()=>{for(let t of Array.from(e.header.children))t!==A&&t.setAttribute(k,``)},I=()=>{for(let t of Array.from(e.container.querySelectorAll(`[${k}]`)))t.removeAttribute(k)},re=()=>{let t=M;if(!t)return;if(Array.from(e.header.children).some(e=>e!==A&&!e.hasAttribute(k))){j&&j!==e.header&&(j.style.removeProperty(`min-height`),j=null);let t=e.header.offsetHeight;t>0&&(e.header.style.minHeight=`${t}px`,j=e.header)}A||=z(`div`,`persona-history-header-host`),t.setHeaderPlacement(`external`);let n=t.getHeaderElement();n.parentNode!==A&&A.replaceChildren(n),A.parentNode!==e.header&&e.header.appendChild(A),ne()},ie=()=>{j&&=(j.style.removeProperty(`min-height`),null),A&&(M?.setHeaderPlacement(`inline`),A.remove(),A=null,I())},ae=null,oe=()=>{ae&&(e.body.style.display=`none`,O(e.body,!0),e.footer.hidden=!0,O(e.footer,!0),te()?(re(),e.header.style.display=F(),O(e.header,!1)):(ie(),e.header.style.display=`none`,O(e.header,!0)))};e.reapplyHistoryHostChrome=oe;let se=t=>{let n=e.body.style.display,r=e.footer.hidden,i=e.footer,a=e.header,o=e.header.style.display;N=a,P=o,ae=()=>{ae=null,ie(),N=null,e.body.style.display=n,O(e.body,!1),i.hidden=r,O(i,!1),e.footer!==i&&(e.footer.hidden=!1,O(e.footer,!1)),a.style.display=o,O(a,!1),e.header!==a&&(e.header.style.display=e.config.layout?.showHeader===!1?`none`:``,O(e.header,!1))},e.footer.parentNode?.insertBefore(t,e.footer),oe()},ce=null,le=null,L=null,R=null,ue=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],de=()=>e.config.features?.history?.rail?.collapsible!==!1,fe=()=>e.config.features?.history?.rail?.side===`right`?`right`:`left`,pe=e=>Math.min(400,Math.max(200,Math.round(e))),me=()=>e.config.features?.history?.rail?.resizable===!0,he,ge=()=>{if(he===void 0&&(he=null,e.config.persistState!==!1))try{let t=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));t&&(he=t)}catch{}return he},H=()=>pe(ge()??e.config.features?.history?.rail?.width??260),_e=t=>{if(he=t,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(t))}catch{}},ve=()=>de()&&e.config.features?.history?.rail?.collapsedBehavior===`overlay`,ye=!1,be=e=>{let t=z(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},xe=()=>{let t=e.config.features?.history?.rail?.brand;if(!t)return;let n=!1,r;return i=>{if(t.render)try{return t.render({collapsed:i})??null}catch(e){return n||(n=!0,console.warn(`[persona] history rail brand threw`,e)),null}return r===void 0&&(r=t.iconUrl?be(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null),r?r.cloneNode(!0):null}},Se=()=>e.config.features?.history?.rail?.sections?.map(t=>{let n=!1,r=e=>{n||(n=!0,console.warn(`[persona] history rail section threw`,t.id,e))};return{id:t.id,title:t.title,placement:t.placement??`above-conversations`,items:t.items.map(t=>{let n;return{id:t.id,label:t.label,badge:t.badge,iconNode:()=>{if(n!==void 0)return n;try{n=t.renderIcon?t.renderIcon()??null:t.iconUrl?be(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null}catch(e){r(e),n=null}return n},onSelect:()=>{try{t.onSelect()}catch(e){r(e)}}}})}})??[],Ce=e=>{let t=Se();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},we=null,Te=()=>`${e.currentKeyPrefix()}rail-collapsed`,Ee=()=>{if(we===null&&(we=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let e=window.localStorage.getItem(Te());e&&(we=e===`1`)}catch{}return we},De=t=>{if(we=t,e.config.persistState!==!1)try{window.localStorage.setItem(Te(),t?`1`:`0`)}catch{}},Oe=()=>e.historyPresentation===`rail`&&de()&&!ve()&&Ee(),ke=()=>{},Ae=()=>{ve()?ke():(De(!Ee()),i?.view.setCollapsed(Oe()),e.applyRailChrome(),e.repinAnchoredMessage())},je=()=>{let t=e.config.features?.history?.rail?.collapseShortcut;return!t||!Qp(t)?null:{combo:t,hint:tm(t),aria:nm(t)}},Me=`var(--persona-history-overlay-margin,8px)`,Ne=null,Pe=null,Fe=0,Ie=null,Le=null,Re=!1,U=0,ze=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,Be=()=>g()&&ve()&&(e.historyPresentation??D())===`rail`,Ve=()=>e.historyVisible&&!ye,He=()=>{Le!==null&&clearTimeout(Le),Le=null},Ue=()=>{e.loadHistoryView().catch(()=>{})},We=()=>{He(),ye&&(Le=setTimeout(()=>{Le=null,!Re&&ye&&(Ie?.contains(document.activeElement)||ft({restoreFocus:!1}))},300))},Ge=(e,t)=>{let n=Ie?.getBoundingClientRect();if(!n)return!1;let r=Ne?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Ke=e=>{ye&&(Re=Ge(e.clientX,e.clientY),Re?He():Le===null&&We())},qe=t=>{!e.historyVisible&&Be()&&(ye=!0,dt({invoker:Ne,keyboard:t?.keyboard===!0}).then(()=>{e.historyVisible?!Re&&document.activeElement!==Ne&&ft():ye=!1}))},Je=()=>{let e=ee?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,ye?t.expandLabel:t.collapseLabel),e.setAttribute(`aria-expanded`,ye?`false`:`true`))},Ye=()=>{De(!1);let t=i;if(!ye||!t){dt({invoker:Ne});return}let n=document.activeElement===Ne;ye=!1,ct(),t.element.remove(),K(t.element),Je(),n&&ut(),e.repinAnchoredMessage(),Bt()},Xe=()=>{De(!0),ft()};ke=()=>{!e.historyVisible||ye?Ye():Xe()};let Ze=()=>{let n=je(),r=e.createHeaderIconButton({ariaLabel:t.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":h,...n?{"aria-keyshortcuts":n.aria}:{}}}),i=r.button;i.addEventListener(`mouseenter`,()=>{Re=!0,He(),!(ze()||Date.now()<U)&&qe()}),i.addEventListener(`mouseleave`,()=>{Re=!1,U=0,We()}),i.addEventListener(`focus`,()=>{e.historyVisible||Ue()}),i.addEventListener(`click`,t=>{g()&&(t.detail!==0&&ze()&&!e.historyVisible?qe():Ye())}),Ne=i,Pe=r.wrapper},Qe=()=>{if(Pe&&!Pe.isConnected&&(Pe=null,Ne=null),!Be()){Pe?.remove(),Pe=null,Ne=null;return}Ne||Ze();let n=Pe,r=Ne;if(!n||!r)return;let i=fe()===`right`?null:e.header.firstChild;(i??e.header.lastChild)!==n&&e.header.insertBefore(n,i),n.style.display=Ve()||Fe>0?`none`:``,r.setAttribute(`aria-label`,t.expandLabel),r.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),Ie&&e.applyRailChrome()},$e=e=>{if(!ye)return;let t=e.target;t instanceof Node&&(Ie?.contains(t)||Pe?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||ft({restoreFocus:!1}))};document.addEventListener(`pointerdown`,$e,!0),e.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,$e,!0),document.removeEventListener(`pointermove`,Ke),tt?.(),He()});let et=null,tt=null,nt=t=>{_e(pe(t)),e.applyRailChrome(),e.repinAnchoredMessage()},rt=()=>{let t=z(`div`,`persona-rail-resizer`);return t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-valuemin`,`200`),t.setAttribute(`aria-valuemax`,`400`),t.addEventListener(`pointerdown`,n=>{let r=le;if(!r||n.button!==0)return;n.preventDefault(),tt?.();let i=n.clientX,a=r.getBoundingClientRect().width||H(),o=fe()===`right`?-1:1,s=a,c=e.mount.ownerDocument;r.style.transition=`none`;let l=e=>{s=pe(a+o*(e.clientX-i)),r.style.flex=`0 0 ${s}px`,t.setAttribute(`aria-valuenow`,String(s))},u=()=>{tt=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),r.style.removeProperty(`transition`);try{t.releasePointerCapture(n.pointerId)}catch{}nt(s)};tt=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{t.setPointerCapture(n.pointerId)}catch{}}),t.addEventListener(`keydown`,e=>{let t=fe()===`right`?-16:16,n=H(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),nt(r))}),t},it=(e,n)=>{if(!me()||Oe()){tt?.(),et?.remove();return}let r=et??rt();et=r,r.setAttribute(`aria-label`,t.resizeLabel),r.setAttribute(`aria-valuenow`,String(H())),r.nextElementSibling!==n&&e.insertBefore(r,n)};e.applyRailChrome=()=>{i?.view.setRailSide(fe());let t=fe()===`right`,n=Ie;if(n){let r=Ne?Ne.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;n.style.top=`calc(${Math.max(0,Math.round(r))}px + ${Me})`,n.style.width=`${H()}px`,n.style.left=t?``:Me,n.style.right=t?Me:``}let r=le,a=ce,o=L;if(!r||!a||!o)return;r.style.flex=`0 0 ${Oe()?52:H()}px`;let s=`1px solid var(--persona-divider,#e5e7eb)`;r.style.borderRight=t?``:s,r.style.borderLeft=t?s:``;let c=t?o:r;a.firstElementChild!==c&&a.append(c,t?r:o),it(a,t?r:o)};let at=t=>{if(R&&le){R.replaceWith(t),R=null,e.applyRailChrome();return}let n=z(`div`,`persona-history-rail-shell`);n.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=z(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let i=z(`div`,`persona-history-rail-host`);i.style.cssText=`display:flex;min-height:0;overflow:hidden`,e.container.insertBefore(n,e.header.parentNode===e.container?e.header:e.body);for(let t of ue())t?.parentNode===e.container&&r.appendChild(t);n.append(i,r),i.appendChild(t),ce=n,le=i,L=r,e.applyRailChrome()},ot=()=>{if(ce)return;let t=z(`div`,`persona-history-rail-placeholder`);t.style.cssText=`flex:1 1 auto;min-height:0`,R=t,at(t),e.repinAnchoredMessage()},W=()=>{R&&(ct(),e.repinAnchoredMessage())},st=t=>{let n=z(`div`,`persona-history-rail-overlay`);n.style.cssText=`position:absolute;bottom:${Me};display:flex;overflow:hidden;z-index:${zr-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(n),n.appendChild(t),document.addEventListener(`pointermove`,Ke),Ie=n,e.applyRailChrome(),Je()},ct=()=>{ae?.(),Ie&&=(Re&&(U=Date.now()+150),document.removeEventListener(`pointermove`,Ke),Ie.remove(),null);let t=ce;if(t){tt?.();for(let n of ue())n&&t.contains(n)&&e.container.insertBefore(n,t);t.remove(),ce=null,le=null,L=null,R=null}},G=e=>{ee=e,e.id=h,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},K=t=>{G(t),(e.historyPresentation!==`rail`||ye)&&W(),e.historyPresentation===`rail`?ye?st(t):at(t):se(t)},q=()=>{if(Qe(),Lt(),!e.historyVisible||!i)return;let t=D();if(t===e.historyPresentation)return;let n=document.activeElement,r=n instanceof HTMLElement&&(i.element.contains(n)||A?.contains(n)===!0)?n:null;ct(),i.element.remove(),i.view.setHeaderPlacement(`inline`),e.historyPresentation=t,i.view.setPresentation(t),i.view.setCollapsed(Oe()),i.requestRender(),i.element.isConnected||K(i.element),r?.isConnected?r.focus():ut(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Bt()},lt=(e,t)=>A?.querySelector(t)??e.querySelector(t),ut=()=>{let e=i?.element??ee;if(!e)return;let t=lt(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=lt(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},dt=async r=>{if(!g()||e.historyVisible)return;let l=n;if(!l)return;if(!ye&&Be()&&Ee()){Qe();return}J();let u=++d;o=r?.returnSurface??`conversation`,s=r?.invoker??c;let f=Be()&&!ye;f&&(Fe+=1,Qe(),ot());let p;try{p=await e.loadHistoryView()}catch{e.announceHistory(t.openHistoryLabel),f&&(--Fe,u===d&&(W(),Qe()));return}if(f&&--Fe,u!==d||e.historyVisible)return;a={scope:v()},e.historyPresentation=D(),e.historyVisible=!0;let m=e.historyPresentation===`panel`&&e.config.layout?.showHeader!==!1&&e.header.style.display!==`none`?`external`:`inline`,h=e.config.features?.history?.rowAvatar,_=je(),y=_?{hint:_.hint,aria:_.aria}:null,x={provider:l,context:a,targetId:b(),presentation:e.historyPresentation,collapsible:de(),collapsed:Oe(),railSide:fe(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:xe(),onToggleCollapse:Ae,...y?{collapseShortcut:y}:{},headerPlacement:m,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:h===!1?!1:typeof h==`string`?h: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:e=>wt(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:t=>e.setActiveConversationSummary(t),attachTooltip:e.attachTooltip,onStartNew:()=>Tt({focusComposer:!0}),onClose:()=>ft(),onRequestDeleteConversation:e=>Mt(e),onRequestClearHistory:()=>Nt(),...l.resetDevice?{onRequestResetIdentity:()=>Pt()}:{}};i=QC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??`panel`,getReturnSurface:()=>o,close:()=>ft(),createView:({slots:t,renderDom:n,onModelChange:r,railSections:i})=>(M=p.createHistoryView({...x,railSections:Ce(i),slots:t,renderDom:n,onModelChange:r,onAnnounce:e.announceHistory}),M),onElementChanged:(e,t)=>{if(!t?.isConnected)return K(e);G(e),t.replaceWith(e),oe()}}),i.view.setNewConversationRequired(e.historySessionState.recovery===`new_conversation_required`),r?.focus!==!1&&(e.historyPresentation!==`rail`||r?.keyboard===!0)&&ut(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Bt(),e.eventBus.emit(`history:opened`,{presentation:e.historyPresentation,returnSurface:o,timestamp:Date.now()})},J=()=>{},ft=t=>{if(!e.historyVisible)return;d+=1;let n=o,r=s,l=i,u=t?.restoreFocus!==!1;e.historyVisible=!1;let f=!1,p=null,m=()=>{if(!f){if(f=!0,J=()=>{},p!==null&&clearTimeout(p),ye=!1,He(),ct(),l?.dispose(),l?.view.destroy(),l?.element.remove(),i===l&&(i=null,M=null,ee=null,e.historyPresentation=null,a=null,s=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Bt(),u){let t=r??c;t?.isConnected?t.focus():e.maybeFocusInput()}e.eventBus.emit(`history:closed`,{returnSurface:n,timestamp:Date.now()})}},h=l&&l.element===l.view.element?l.view.playExit():null;h?(J=m,p=setTimeout(m,250),h.then(m)):m()},pt=t=>{if(t.key===`Escape`&&e.historyVisible&&i){if(e.historyPresentation===`rail`){let e=t.target;if(!(e instanceof Node)||!(i.element.contains(e)||ye&&Pe?.contains(e)===!0))return}t.preventDefault(),t.stopPropagation(),ft()}};e.container.addEventListener(`keydown`,pt),e.destroyCallbacks.push(()=>e.container.removeEventListener(`keydown`,pt));let Y=0,mt=null,ht=()=>{mt&&clearTimeout(mt),mt=null};e.destroyCallbacks.push(ht);let gt=()=>{ht();let t=e.conversationOpenPendingEl;t&&(e.conversationOpenTakeover=!0,t.hidden=!1,e.messagesWrapper.style.display=`none`,e.updateWelcome())},_t=()=>{Y+=1,ht(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty(`display`),O(e.footer,!1),e.updateWelcome())},vt=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},yt=(e,t)=>B(`div`,{className:V(`persona-conversation-loading-bubble`,t&&`persona-conversation-loading-bubble--trailing`),attrs:{"aria-hidden":`true`},style:{width:e}}),bt=()=>B(`div`,{className:`persona-conversation-loading-body`},yt(`58%`,!1),yt(`72%`,!0),yt(`44%`,!1)),xt=t=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=t,t.hidden=!e.conversationOpenTakeover,e.body.insertBefore(t,e.messagesWrapper),ht(),e.conversationOpenTakeover||(mt=setTimeout(gt,250)),O(e.footer,!0)},St=()=>{let n={config:e.config,streaming:!1,location:`conversation-open`,defaultRenderer:bt},r=null,i=e.plugins.find(e=>e.renderLoadingIndicator);i?.renderLoadingIndicator&&(r=i.renderLoadingIndicator(n)),r===null&&e.config.loadingIndicator?.render&&(r=e.config.loadingIndicator.render(n)),xt(B(`div`,{className:`persona-conversation-loading`,attrs:{role:`status`,"aria-label":t.openConversationLoadingLabel}},r??bt()))},Ct=n=>{let r=()=>{wt(n,{focusComposer:!0}).catch(()=>{})},i=g()?()=>{_t(),dt()}:void 0,a=(e,t)=>{let n=B(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return n.addEventListener(`click`,t),n},o=()=>B(`div`,{className:`persona-conversation-loading-error-body`},B(`p`,{className:`persona-conversation-loading-error-title`,text:t.openConversationErrorTitle}),B(`div`,{className:`persona-conversation-loading-error-actions`},a(t.openConversationRetryLabel,r),i?a(t.openConversationBackLabel,i):null)),s=Object.freeze({conversationId:n,config:e.config,copy:Object.freeze({title:t.openConversationErrorTitle,retryLabel:t.openConversationRetryLabel,backLabel:t.openConversationBackLabel}),retry:r,...i?{back:i}:{},defaultRenderer:o}),c=null;for(let t of e.plugins)if(t.renderHistoryOpenError){try{c=t.renderHistoryOpenError(s)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),c=null}if(c)break}xt(B(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},c??o())),gt()};e.eventBus.on(`history:closed`,()=>{e.conversationOpenPendingEl&&O(e.footer,!0)});let wt=async(t,{focusComposer:n=!1}={})=>{let r=y(),a=!!i;i?.view.setActiveConversationId(t),_t();let o=Y;St(),e.historyVisible&&(e.historyPresentation===`panel`||ye)&&ft({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(t,{scope:r})}catch(e){throw o===Y&&Ct(t),e}finally{e.suppressScrollSend=!1}o===Y&&(_t(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),vt(),X(),a||e.setActiveConversationSummary(null),e.eventBus.emit(`history:conversationOpened`,{conversationId:t,title:e.activeConversationTitle,scope:r,timestamp:Date.now()}),n&&e.maybeFocusInput())},Tt=async({focusComposer:t=!1}={})=>{_t(),await e.session.startNewConversation({scope:y()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),X();let n=e.session.getActiveConversationId();i?.view.setActiveConversationId(n),e.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation===`panel`||ye)&&ft({restoreFocus:!1}),t&&e.maybeFocusInput()},Et=async(t,n)=>{let r=await e.session.updateConversation(t,{...n,...n.title===void 0?{}:{title:n.title.trim()}});return i?.view.applyConversationSummary(r),!i&&t===e.session.getActiveConversationId()&&e.setActiveConversationSummary(r),r},Dt=async t=>{let n=y(),r=e.session.getActiveConversationId()===t;await e.session.deleteConversation(t,{scope:n}),i?.view.removeConversationSummary(t),r&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),X()),e.eventBus.emit(`history:conversationDeleted`,{conversationId:t,scope:n,wasActive:r,timestamp:Date.now()})},Ot=async t=>{let n=t?.scope??y(),r=t?.allTargets?null:t?.targetId??b(),i=await e.session.clearConversationHistory({...r?{targetId:r}:{},scope:n});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),X(),e.eventBus.emit(`history:cleared`,{deleted:i.deleted,scope:n,targetId:r,timestamp:Date.now()}),i},kt=async()=>{if(!n?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let r=!1;try{r=(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 t=e.storageAdapter;t?.clear&&e.runStorageMutation(()=>t.clear(),`[AgentWidget] Failed to clear storage adapter:`),e.resetAnchorState(),e.resumeAutoScroll(),X(),ft({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(r?t.identityResetNotice:t.identityResetUnconfirmedNotice),e.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},At=()=>e.artifactSplitRoot?e.panel:e.container,jt=async t=>{let n=await e.loadHistoryView().catch(()=>null);return typeof n?.showHistoryConfirm==`function`?n.showHistoryConfirm(t):window.confirm(`${t.title}\n\n${t.description}`)},Mt=async e=>await jt({host:At(),title:t.deleteConversationConfirmTitle,description:t.deleteConversationConfirm,confirmLabel:t.deleteConversationConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Dt(e),`deleted`):`cancelled`,Nt=async()=>{let e=y()===`verified-user`;return await jt({host:At(),title:t.clearHistoryConfirmTitle,description:e?t.clearHistoryVerifiedConfirm:t.clearHistoryConfirm,confirmLabel:t.clearHistoryConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Ot(),`cleared`):`cancelled`},Pt=async()=>{if(!await jt({host:At(),title:t.resetIdentityConfirmTitle,description:t.resetIdentityConfirm,confirmLabel:t.resetIdentityConfirmLabel,cancelLabel:t.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await kt();return{outcome:`reset`,remoteRevocationConfirmed:e}},Ft=z(`button`,`persona-history-earlier`);Ft.type=`button`,Ft.textContent=t.showEarlierMessagesLabel,Ft.setAttribute(`data-persona-history-earlier`,``),Object.assign(Ft.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 X=()=>{g()&&e.historySessionState.nextMessageCursor&&e.session.getActiveConversationId()?(Ft.textContent=t.showEarlierMessagesLabel,Ft.parentNode!==e.body&&e.body.insertBefore(Ft,e.body.firstChild)):Ft.remove()};Ft.addEventListener(`click`,()=>{let t=e.session.getActiveConversationId(),n=e.historySessionState.nextMessageCursor;if(!t||!n||Ft.disabled)return;Ft.disabled=!0;let r=e.body.scrollHeight,i=e.body.scrollTop;e.session.loadOlderMessages(t,n,{scope:y()}).then(()=>{e.body.scrollTop=i+(e.body.scrollHeight-r),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Ft.disabled=!1,X()})});let It=()=>{let n=e.createHeaderIconButton({ariaLabel:t.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 n.button.addEventListener(`click`,t=>{g()&&!_()&&(e.historyVisible?ft():dt({invoker:n.button,keyboard:t.detail===0}))}),n},Lt=()=>{if(!g()){l?.remove(),c=null,l=null;return}if(l&&!l.isConnected&&(c=null,l=null),!c&&e.header){let t=It();c=t.button,l=t.wrapper;let n=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;n?.parentNode&&e.header.contains(n)?n.parentNode.insertBefore(l,n):e.header.appendChild(l)}if(!c||!l)return;let n=Be()||e.historyVisible&&e.historyPresentation===`rail`;if(l.style.display=n?`none`:``,n){document.activeElement===c&&ut();return}let r=_();c.disabled=r,c.setAttribute(`aria-disabled`,r?`true`:`false`);let i=r?t.openHistoryBusyLabel:t.openHistoryLabel;c.setAttribute(`aria-label`,i),(e.config.features?.history?.presentation??`panel`)===`panel`?(c.removeAttribute(`aria-expanded`),c.removeAttribute(`aria-controls`)):(c.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),c.setAttribute(`aria-controls`,h))},Rt=!1,zt=()=>{let n=e.panelElements.clearChatButton;n&&(g()?(Rt||=(f=n.getAttribute(`aria-label`)??``,!0),n.setAttribute(`aria-label`,t.newConversationLabel),n.removeAttribute(`title`)):Rt&&(Rt=!1,f&&n.setAttribute(`aria-label`,f)))},Bt=()=>{t=VS(e.config.features?.history?.copy),Lt(),Qe(),zt(),X()};return e.historyChromeSync=Bt,E(),Bt(),e.destroyCallbacks.push(()=>{p?.(),m?.(),d+=1,J(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:g,historyScope:v,installHistoryProvider:E,syncHistoryChromeImpl:Bt,syncHistoryPresentation:q,syncEarlierMessagesPill:X,openHistory:dt,closeHistory:ft,openHistoryConversation:wt,startNewConversation:Tt,updateHistoryConversation:Et,deleteHistoryConversation:Dt,requestDeleteConversation:Mt,clearConversationHistory:Ot,resetHistoryIdentity:kt,railCollapseShortcut:je,railCollapsible:de,railTriggerApplies:Be,railOverlayMode:ve,toggleRailCollapsed:Ae,toggleRailPinned:()=>ke(),get historyProvider(){return n},get historySurface(){return i},get railShell(){return ce},get railHost(){return le},get railColumn(){return L}}}}));ve();const{setLoader:pw,load:mw,provide:hw,getSync:gw}=_e({fallbackImport:()=>Promise.resolve().then(()=>(fw(),uw))}),_w=mw,vw=gw;function yw(){return null}Cy(),H();function bw(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Sy.get(e.component);if(!a){if(ux.includes(e.component)){vx().catch(()=>{});let e=z(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function xw(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 Sw(e){let t=xw(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Cw(e){let t=xw(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const ww=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function Tw(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=ww}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
1161
|
+
`}));function QS(e){if(!e)return eC;let t={...eC};for(let n of $S){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}var $S,eC,tC=o((()=>{$S=/* @__PURE__ */ `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`.split(`.`),eC={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 nC(e){if(!e)return iC;let t={...iC};for(let[n,r]of Object.entries(e))typeof r==`string`&&r.length>0&&(t[n]=r);return t}function rC(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e)}var iC,aC=o((()=>{tC(),iC={...eC,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 oC(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function sC(e,t){let n=Date.parse(e);return Number.isFinite(n)?n:t}function cC(e,t){let n=sC(e,t),r=oC(t);if(n>=r)return`today`;if(n>=r-pC)return`yesterday`;if(n>=r-7*pC)return`previous-7-days`;if(n>=r-30*pC)return`previous-30-days`;let i=new Date(n);return`month:${i.getFullYear()}-${i.getMonth()}`}function lC(e,t,n,r){if(e===`today`)return r.groupToday;if(e===`yesterday`)return r.groupYesterday;if(e===`previous-7-days`)return r.groupPrevious7Days;if(e===`previous-30-days`)return r.groupPrevious30Days;let i=new Date(sC(t,n));return rC(r.groupMonthYear,{month:i.toLocaleString(void 0,{month:`long`}),year:i.getFullYear()})}function uC(e,t,n,r=`time`){let i=e.filter(e=>e.starred),a=i.length>0?[{key:`starred`,label:n.groupStarred,items:i}]:[];if(r===`none`){let t=e.filter(e=>!e.starred);return t.length>0&&a.push({key:`recent`,label:n.conversationsTitle,items:t}),a}for(let r of e){if(r.starred)continue;let e=cC(r.updatedAt,t),i=a[a.length-1];i&&i.key===e?i.items.push(r):a.push({key:e,label:lC(e,r.updatedAt,t,n),items:[r]})}return a}function dC(e,t,n){let r=Math.max(0,t-sC(e,t)),i=Math.floor(r/6e4);if(i<1)return n.relativeNow;if(i<60)return rC(n.relativeMinutes,{value:i});let a=Math.floor(i/60);if(a<24)return rC(n.relativeHours,{value:a});let o=Math.floor(a/24);if(o<7)return rC(n.relativeDays,{value:o});let s=Math.floor(o/7);return o<365?rC(n.relativeWeeks,{value:s}):rC(n.relativeYears,{value:Math.floor(o/365)})}function fC(e,t){return e===1?t.messageCountLabelOne:rC(t.messageCountLabel,{count:e})}var pC,mC=o((()=>{aC(),pC=864e5}));function hC(e,t=20){let n=document.createElementNS(gC,`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 e of[12,19,5]){let t=document.createElementNS(gC,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,`12`),t.setAttribute(`r`,`1`),n.appendChild(t)}return n}let r=vC[e];if(r){let e=document.createElementNS(gC,`rect`);e.setAttribute(`x`,String(r[0])),e.setAttribute(`y`,String(r[1])),e.setAttribute(`width`,String(r[2])),e.setAttribute(`height`,String(r[3])),e.setAttribute(`rx`,`2`),n.appendChild(e)}for(let t of _C[e]){let e=document.createElementNS(gC,`path`);e.setAttribute(`d`,t),n.appendChild(e)}return n}var gC,_C,vC,yC=o((()=>{gC=`http://www.w3.org/2000/svg`,_C={"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:[]},vC={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}}));function bC(e){let t=V(`span`,{className:`persona-history-row-avatar`,attrs:{"aria-hidden":`true`}});return EC.test(e)?t.appendChild(V(`img`,{attrs:{src:e,alt:``,loading:`lazy`}})):t.textContent=e,t}function xC(e){let{conversation:t,copy:n,busy:r,pending:i}=e,a=r||i!==null,o=t.title.trim().length>0,s=t.starred?(()=>{let e=hC(`star`,11);return e.setAttribute(`fill`,`currentColor`),e.setAttribute(`stroke-width`,`1`),V(`span`,{className:`persona-history-row-star`},e,V(`span`,{className:`persona-history-sr-only`,text:n.groupStarred}))})():null,c=V(`div`,{className:`persona-history-row-head`},V(`span`,{className:`persona-history-row-title persona-history-truncate`,text:o?t.title:t.preview??``}),s,V(`time`,{className:`persona-history-row-time`,attrs:{datetime:t.updatedAt},text:dC(t.updatedAt,e.nowMs,n)})),l=o&&t.preview?V(`span`,{className:`persona-history-row-preview persona-history-truncate`,text:t.preview}):null,u=V(`button`,{className:Me(`persona-history-row`,e.active&&`persona-history-row--active`,i&&`persona-history-row--${i}`),attrs:{type:`button`,"data-persona-history-focus":DC(t.id),"data-persona-history-conversation":t.id,...e.active?{"aria-current":`page`}:{},...a?{"aria-disabled":`true`}:{},...i?{"aria-busy":`true`}:{}}},e.avatar?bC(e.avatar):null,V(`div`,{className:`persona-history-row-body`},c,l,V(`span`,{className:`persona-history-row-count persona-history-sr-only`,text:fC(t.messageCount,n)})));u.addEventListener(`click`,()=>{a||e.onOpen()});let d=e.showDelete?CC({className:`persona-history-row-menu-button`,label:`${n.rowActionsLabel}: ${t.title}`,focusKey:OC(t.id),open:e.menuOpen,inert:a,onToggle:e.onToggleMenu}):null;return V(`li`,{className:Me(`persona-history-item`,!e.showDelete&&`persona-history-item--no-menu`),attrs:{"data-persona-history-item":t.id}},u,d,e.menuOpen&&e.showDelete?SC(e):null,e.error?TC(e.error,n,t.id):null)}function SC(e){let{conversation:t,copy:n}=e;return wC({label:`${n.rowActionsLabel}: ${t.title}`,items:[{label:n.deleteConversationLabel,focusKey:kC(t.id),danger:!0,onSelect:e.onDelete}],onCloseMenu:e.onCloseMenu})}function CC(e){let t=V(`button`,{className:Me(`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(hC(`ellipsis`,e.iconSize));let n=()=>t.getAttribute(`aria-disabled`)===`true`;return t.addEventListener(`click`,t=>{t.stopPropagation(),!n()&&e.onToggle()}),t.addEventListener(`keydown`,r=>{(r.key===`ArrowDown`||r.key===`ArrowUp`)&&(r.preventDefault(),!(n()||t.getAttribute(`aria-expanded`)===`true`)&&e.onToggle())}),t}function wC(e){let t=V(`div`,{className:`persona-history-menu`,attrs:{role:`menu`,"aria-label":e.label}});for(let n of e.items){let r=V(`button`,{className:Me(`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}});r.addEventListener(`click`,()=>{e.onCloseMenu(),n.onSelect()}),t.appendChild(r)}return t.addEventListener(`keydown`,n=>{let r=Array.from(t.querySelectorAll(`[role="menuitem"]`));if(r.length===0)return;let i=r.indexOf(document.activeElement);n.key===`Tab`?e.onCloseMenu({restoreFocus:!0}):n.key===`ArrowDown`?(n.preventDefault(),r[(i+1+r.length)%r.length]?.focus()):n.key===`ArrowUp`?(n.preventDefault(),r[(i-1+r.length)%r.length]?.focus()):n.key===`Home`?(n.preventDefault(),r[0]?.focus()):n.key===`End`&&(n.preventDefault(),r[r.length-1]?.focus())}),t}function TC(e,t,n){let r=V(`button`,{className:`persona-history-secondary persona-history-state-action`,text:t.retryLabel,attrs:{type:`button`,"data-persona-history-focus":`row-retry:${n}`}});return r.addEventListener(`click`,e.retry),V(`div`,{className:`persona-history-row-error`,attrs:{role:`alert`}},V(`span`,{text:e.message}),r)}var EC,DC,OC,kC,AC=o((()=>{H(),yC(),mC(),EC=/^(https?:|\/|data:)/i,DC=e=>`row:${e}`,OC=e=>`menu:${e}`,kC=e=>`menu-item:${e}`}));function jC(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 MC(e){if(uo(e)){if(e.code===`rate_limited`)return{kind:`rate_limited`,retryAfterSeconds:e.retryAfterSeconds??0};let t=jC(e.code);return{kind:`error`,reason:t,retryable:t!==`unsupported_scope`}}return{kind:`error`,reason:`unknown`,retryable:!0}}function NC(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 PC(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 FC(e,t,n,r){let i=V(`button`,{className:`persona-history-secondary persona-history-state-action`,text:e,attrs:{type:`button`,"data-persona-history-focus":t,...n?{"aria-disabled":`true`}:{}}});return i.addEventListener(`click`,()=>{n||r()}),i}function IC(e,t,n,r,i){return V(`div`,{className:`persona-history-state`,attrs:{"data-persona-history-state":e,...i?{role:`alert`}:{role:`status`}}},V(`p`,{className:`persona-history-state-title`,text:t}),V(`p`,{className:`persona-history-state-description`,text:n}),r)}function LC(e){let t=[`42%`,`58%`,`34%`],n=[`94%`,`78%`,`88%`],r=[0,1,2].map(e=>V(`div`,{className:`persona-history-skeleton-row`,attrs:{"aria-hidden":`true`}},V(`div`,{className:`persona-history-skeleton-head`},V(`div`,{className:`persona-history-skeleton-bar persona-history-skeleton-bar--title`,style:{width:t[e]}}),V(`div`,{className:`persona-history-skeleton-bar persona-history-skeleton-bar--time`})),V(`div`,{className:`persona-history-skeleton-bar persona-history-skeleton-bar--preview`,style:{width:n[e]}})));return V(`div`,{className:`persona-history-view-loading`,attrs:{"data-persona-history-state":`loading`,role:`status`,"aria-label":e.loadingLabel}},...r)}function RC(e){let{state:t,copy:n,busy:r}=e;if(t.kind===`loading`)return LC(n);if(t.kind===`empty`){let t=NC(e.identityStatus,n);return t?IC(`identity`,t.title,t.description,e.onRetry?FC(n.retryIdentityLabel,`state-retry`,r,e.onRetry):null,!0):IC(`empty`,n.emptyTitle,n.emptyDescription,null,!1)}if(t.kind===`rate_limited`){let i=t.retryAfterSeconds>0?rC(n.rateLimitedWaitDescription,{seconds:t.retryAfterSeconds}):n.rateLimitedDescription;return IC(`rate_limited`,n.rateLimitedTitle,i,e.onRetry?FC(n.retryLabel,`state-retry`,r,e.onRetry):null,!1)}if(t.kind===`new_conversation_required`)return IC(`new_conversation_required`,n.newConversationRequiredTitle,n.newConversationRequiredDescription,e.onStartNew?FC(n.newConversationLabel,`state-retry`,r,e.onStartNew):null,!0);let{title:i,description:a}=PC(t.reason,n),o=t.reason===`authentication_required`||t.reason===`authentication_failed`||t.reason===`identity_provider_failed`?n.retryIdentityLabel:n.retryLabel;return IC(`error`,i,a,t.retryable&&e.onRetry?FC(o,`state-retry`,r,e.onRetry):null,!0)}var zC=o((()=>{H(),aC(),po()}));function BC(e){return`${e.state}:${`reason`in e?e.reason:``}`}function VC(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 HC(e){return e.state===`verified`||e.state===`browser_only`}function UC(e){return e.state===`authentication_required`||e.state===`identity_provider_failed`||e.state===`configuration_error`}function WC(e){let t=nC(e.copy),n=e.now??(()=>Date.now()),r=e.pageSize??GC,i=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,a=[],o=null,s={kind:`loading`,phase:`initial`},c=null,l=e.activeConversationId,u=e.provider.getIdentityStatus(),d=BC(u),f=null,p=!1,m=!1,h=0,g=e.presentation,_=e.collapsible!==!1,v=e.collapsed===!0,y=e.railSide===`right`,b=e.renderDom!==!1,x=/* @__PURE__ */ new Map,S=null,C=JS(),w=t=>{!b&&e.onAnnounce?e.onAnnounce(t):C.announce(t)},T=()=>c!==null,E=`${i}-body`,D=V(`button`,{className:`persona-history-icon-button persona-history-back`,attrs:{type:`button`}}),O=()=>g===`rail`&&_,k,A=()=>{if(e.railBrand){if(!O())D.classList.remove(`persona-history-back--branded`);else{if(k===void 0){let t=e.railBrand(!0);k=t?V(`span`,{className:`persona-history-brand-mark persona-history-toggle-brand`,attrs:{"aria-hidden":`true`}},t):null}k&&(D.classList.add(`persona-history-back--branded`),D.appendChild(k))}}},j=()=>{let n=O(),r=g===`rail`;D.setAttribute(`data-persona-history-focus`,n?`collapse`:`close`),D.setAttribute(`aria-label`,n?v?t.expandLabel:t.collapseLabel:r?t.closeLabel:t.backLabel),n?(D.setAttribute(`aria-expanded`,v?`false`:`true`),D.setAttribute(`aria-controls`,E),e.collapseShortcut?.aria&&D.setAttribute(`aria-keyshortcuts`,e.collapseShortcut.aria)):(D.removeAttribute(`aria-expanded`),D.removeAttribute(`aria-controls`),D.removeAttribute(`aria-keyshortcuts`)),D.replaceChildren(hC(n?`panel-left`:r?`x`:`arrow-left`)),A()};j(),D.addEventListener(`click`,()=>{O()?e.onToggleCollapse?.():e.onClose()});let ee=V(`h2`,{className:`persona-history-title`,text:t.viewTitle,attrs:{id:i}}),M=V(`span`,{className:`persona-history-scope-title`}),N=V(`p`,{className:`persona-history-scope`},V(`span`,{className:`persona-history-scope-icon`,attrs:{"aria-hidden":`true`}},hC(`monitor`,14)),M),P=V(`div`,{className:`persona-history-heading-group`},ee),te=!1,ne,re=()=>{let n=g===`rail`,r=n?e.renderRailHeader:void 0,i=null,a=r!==void 0;if(r)try{i=r({collapsed:v,defaultTitle:t.viewTitle})}catch(e){a=!1,te||(te=!0,console.warn(`[persona] history rail renderHeader threw`,e))}if(!a&&n&&e.railBrand){if(ne===void 0){let n=e.railBrand(!1);ne=n?V(`span`,{className:`persona-history-heading-brand`,attrs:{"aria-hidden":`true`}},V(`span`,{className:`persona-history-brand-mark`},n),V(`span`,{className:`persona-history-wordmark`,text:t.viewTitle})):null}ne&&(a=!0,i=ne)}ee.classList.toggle(`persona-history-sr-only`,a),P.replaceChildren(ee),i&&P.appendChild(i)};re();let F=V(`button`,{className:`persona-history-icon-button persona-history-new-icon`,attrs:{type:`button`,"data-persona-history-focus":`new-icon`,"aria-label":t.newConversationLabel}});F.appendChild(hC(`plus`)),F.addEventListener(`click`,()=>void nt());let ie=[D,F].map(t=>e.attachTooltip?.({anchor:t,text:()=>t.getAttribute(`aria-label`)??``,...t===D&&e.collapseShortcut?{hint:()=>O()?e.collapseShortcut.hint:``}:{}})),ae=V(`div`,{className:`persona-history-topbar`}),oe=null,se=()=>{let e=g===`rail`,t=e?y?`rail-right`:`rail`:`panel`;t!==oe&&(oe=t,t===`rail`?ae.append(P,D):ae.append(D,P),e?F.remove():ae.appendChild(F),R.classList.toggle(`persona-history-view--rail-right`,t===`rail-right`))},ce=V(`div`,{className:`persona-history-scope-alert`}),le=`${i}-scope`,ue=hC(`plus`,18),de=V(`button`,{className:`persona-history-new`,attrs:{type:`button`,"data-persona-history-focus":`new`}},ue,V(`span`,{text:t.newConversationLabel}));de.addEventListener(`click`,()=>void nt());let I=V(`div`,{className:`persona-history-list-region`}),fe=e.showDeleteAll!==!1,pe=!!e.provider.resetDevice,me=e.listActions??[],he=fe||pe||me.length>0?CC({className:`persona-history-list-options`,label:t.listOptionsLabel,focusKey:`menu:${KC}`,open:!1,inert:!0,iconSize:16,onToggle:()=>Qe(KC)}):null,ge=V(`h3`,{className:`persona-history-conversations-title`,text:t.conversationsTitle}),_e=V(`div`,{className:`persona-history-caption`,attrs:{"data-persona-history-item":KC}},ge,e.showScopeStatus?N:null,he),ve=V(`div`,{className:`persona-history-body`,attrs:{id:E}},e.showScopeStatus?ce:null,de,_e,I),L=e.headerPlacement??`inline`;L===`external`&&ae.classList.add(`persona-history-topbar--shell`,`persona-history-topbar--shell-enter`);let R=V(`div`,{className:Me(`persona-history-view`,`persona-history-view--${e.presentation}`,`persona-history-view--enter`),attrs:{role:`region`,"aria-labelledby":i,"data-persona-history-presentation":e.presentation}},C.element,L===`inline`?ae:null,ve),z=()=>{R.classList.toggle(`persona-history-view--rail-collapsed`,v&&O())};z(),se();let ye=(e,t)=>{let n=`${i}-s${t}`,r=V(`div`,{className:Me(`persona-history-nav`,e.placement===`footer`&&`persona-history-nav--footer`),attrs:{role:`group`,"data-persona-rail-section":e.id,...e.title?{"aria-labelledby":n}:{"aria-label":e.id}}});e.title&&r.appendChild(V(`h3`,{className:`persona-history-group-heading`,text:e.title,attrs:{id:n}}));for(let t of e.items){let e=t.iconNode?.()??null,n=V(`button`,{className:Me(`persona-history-nav-item`,e&&`persona-history-nav-item--icon`),attrs:{type:`button`,"aria-label":t.label,"data-persona-rail-item":t.id}},e?V(`span`,{className:`persona-history-nav-icon`},e):null,V(`span`,{className:`persona-history-nav-label persona-history-truncate`,text:t.label}),t.badge?V(`span`,{className:`persona-history-nav-badge`,text:t.badge}):null);n.addEventListener(`click`,()=>t.onSelect()),r.appendChild(n)}return r},be=null,xe=null,Se=()=>{be&&b&&g===`rail`&&v!==xe&&(xe=v,e.railSections.forEach((e,t)=>{if(!e.render)return;let n=be[t],r=e.title?n.firstElementChild:null,i=null;try{i=e.render(v)}catch(t){e.render=void 0,console.warn(`[persona] history rail section threw`,e.id,t)}n.replaceChildren(...r?[r]:[],...i?[i]:[]),n.hidden=!i}))},Ce=()=>{let t=e.railSections;if(R.classList.toggle(`persona-history-view--has-nav`,g===`rail`&&!!t?.some(e=>e.placement===`above-conversations`)),t?.length){if(g!==`rail`)be?.forEach(e=>e.remove());else{be??=t.map(ye);for(let e of[`above-conversations`,`below-conversations`,`footer`]){let n=e===`above-conversations`?_e.parentNode===ve?_e:I:null;t.forEach((t,r)=>{t.placement===e&&ve.insertBefore(be[r],n)})}Se()}}};Ce(),Is(R,`persona-history-view`,XS);let we=(e,t)=>{let n=R.ownerDocument.defaultView?.getComputedStyle(R).getPropertyValue(e),r=Number.parseFloat(n??``);return Number.isFinite(r)&&r>=0?r:t},Te=(e,t)=>R.ownerDocument.defaultView?.getComputedStyle(R).getPropertyValue(e).trim()||t,Ee=null,De=()=>{Ee!==null&&(clearTimeout(Ee),Ee=null),R.removeEventListener(`animationend`,De),R.classList.remove(`persona-history-view--enter`)};R.addEventListener(`animationend`,De),Ee=setTimeout(()=>{Ee=setTimeout(De,we(`--persona-history-enter-ms`,qC)+60)},0);let Oe=null,ke=()=>{Oe!==null&&(clearTimeout(Oe),Oe=null),ae.classList.remove(`persona-history-topbar--shell-enter`)},Ae=()=>{ke(),ae.classList.add(`persona-history-topbar--shell-enter`),Oe=setTimeout(ke,180)};L===`external`&&(Oe=setTimeout(ke,180));let B=[],je=null,H=()=>{if(je)return je;if(m||ZC()||typeof R.animate!=`function`)return De(),null;let e=R.ownerDocument.defaultView?.getComputedStyle(ve).opacity||`1`;De(),R.style.pointerEvents=`none`,Pe.style.pointerEvents=`none`;let t={duration:we(`--persona-history-exit-ms`,JC),easing:Te(`--persona-history-exit-easing`,YC),fill:`forwards`},n=XC[g];return B=[ve.animate([{opacity:e,transform:`none`},{opacity:0,transform:`translateX(${n}px)`}],t)],je=Promise.all(B.map(QC)).then(()=>void 0),je},Ne=(e,t)=>{e&&(t?e.setAttribute(`aria-disabled`,`true`):e.removeAttribute(`aria-disabled`))},Pe=ae,Fe=null,Ie=()=>{let n=e.slots?.header;if(!n)return;let r=`${g}|${BC(u)}|${c?`${c.kind}:${`conversationId`in c?c.conversationId:``}`:``}`;if(r===Fe)return;Fe=r;let i=n({identityStatus:u,pendingAction:c,copy:t,defaultRenderer:()=>ae})??ae;i!==Pe&&(Pe.replaceWith(i),Pe=i)},Le=null,Re=()=>{if(!e.showScopeStatus)return;let n=BC(u);if(n===Le)return;Le=n;let r=VC(u,t);M.textContent=r.title;let i=HC(u);if(N.hidden=!i,ce.replaceChildren(...i?[]:[V(`span`,{className:`persona-history-scope-alert-title`,text:r.title})],V(`span`,{className:`persona-history-scope-description`,text:r.description,attrs:{id:le}})),ce.setAttribute(`data-persona-history-scope-tone`,i?`ambient`:`attention`),i?N.setAttribute(`aria-describedby`,le):N.removeAttribute(`aria-describedby`),r.pending?ce.setAttribute(`role`,`status`):ce.removeAttribute(`role`),ce.setAttribute(`data-persona-history-identity`,u.state),N.setAttribute(`data-persona-history-identity`,u.state),UC(u)){let e=V(`button`,{className:`persona-history-secondary persona-history-state-action`,text:t.retryIdentityLabel,attrs:{type:`button`,"data-persona-history-focus":`identity-retry`}});e.addEventListener(`click`,()=>{T()||U(`refresh`)}),ce.appendChild(e)}},ze=e=>c?c.kind===`open`&&c.conversationId===e?`opening`:c.kind===`delete`&&c.conversationId===e?`deleting`:null:null,Be=()=>{let e=document.activeElement;return!(e instanceof HTMLElement)||!R.contains(e)?null:e.getAttribute(`data-persona-history-focus`)},Ve=e=>{if(p&&f){p=!1;let e=R.querySelector(`[data-persona-history-focus="${kC(f)}"]`);if(e){e.focus();return}}e&&R.querySelector(`[data-persona-history-focus="${e}"]`)?.focus()},He=()=>{if(!S)return null;let e=V(`button`,{className:`persona-history-secondary persona-history-state-action`,text:t.retryLabel,attrs:{type:`button`,"data-persona-history-focus":`action-retry`}}),n=S;return e.addEventListener(`click`,()=>{T()||n.retry()}),V(`div`,{className:`persona-history-row-error`,attrs:{role:`alert`}},V(`span`,{text:n.message}),e)},Ue=()=>uC(a,n(),t,e.grouping).map((r,a)=>{let o=`${i}-g${a}`,s=V(`ul`,{className:`persona-history-list`,attrs:{"aria-labelledby":o}});for(let i of r.items){let r=()=>xC({conversation:i,active:i.id===l,pending:ze(i.id),busy:T(),menuOpen:f===i.id,error:x.get(i.id)??null,avatar:e.rowAvatar,showDelete:e.showDelete!==!1,nowMs:n(),copy:t,onOpen:()=>void G(i.id),onToggleMenu:()=>Qe(i.id),onCloseMenu:e=>Ze(e),onDelete:()=>void tt(i.id)}),a=e.slots?.conversation?.({conversation:i,active:i.id===l,pending:ze(i.id),open:()=>G(i.id),requestDelete:()=>tt(i.id),defaultRenderer:r})??r();s.appendChild(a instanceof HTMLLIElement?a:V(`li`,{className:`persona-history-item`},a))}return V(`div`,{className:`persona-history-group`,attrs:{"data-persona-history-group":r.key}},V(`h3`,{className:Me(`persona-history-group-heading`,r.key===`recent`&&`persona-history-sr-only`),text:r.label,attrs:{id:o}}),s)}),We=()=>{if(!o)return null;let e=c?.kind===`load-more`||s.kind===`loading`&&s.phase===`load-more`,n=V(`button`,{className:`persona-history-secondary persona-history-load-more`,text:e?t.loadingMoreLabel:t.loadMoreLabel,attrs:{type:`button`,"data-persona-history-focus":`load-more`,...e?{"aria-busy":`true`,"aria-disabled":`true`}:{},...T()&&!e?{"aria-disabled":`true`}:{}}});return n.addEventListener(`click`,()=>{T()||U(`load-more`)}),n},Ge=()=>{let n=Be(),r=[He()],i=a.length>0;if(i&&(r.push(...Ue()),r.push(We())),s.kind!==`ready`&&!(s.kind===`loading`&&s.phase!==`initial`&&i)){let n=s,i=n.kind===`loading`?void 0:()=>U(`refresh`),a=n.kind===`new_conversation_required`?()=>nt():void 0,o=()=>RC({state:n,copy:t,identityStatus:u,busy:T(),...i?{onRetry:()=>void i()}:{},...a?{onStartNew:()=>void a()}:{}}),c=e.slots?.state?.({state:n,identityStatus:u,copy:t,...i?{retry:i}:{},...a?{startNewConversation:a}:{},defaultRenderer:o});r.push(c??o())}I.replaceChildren(...r.filter(e=>!!e)),Ve(n)},Ke=()=>{let e=s.kind===`loading`&&a.length===0,n=[],r=()=>n.length===0?kC(KC):`${kC(KC)}-${n.length}`;if(!e)for(let e of me)n.push({label:e.label,focusKey:r(),danger:e.danger===!0,onSelect:()=>void e.onSelect({conversations:[...a]})});return fe&&(a.length!==0||s.kind!==`empty`&&!e)&&n.push({label:t.clearHistoryLabel,focusKey:r(),danger:!0,onSelect:()=>void K()}),pe&&!e&&n.push({label:t.resetIdentityLabel,focusKey:r(),danger:!0,onSelect:()=>void J()}),n},qe=()=>{if(Ne(de,T()),Ne(F,T()),he){let e=Ke(),n=s.kind===`loading`&&a.length===0;he.hidden=e.length===0&&!n,Ne(he,T()||e.length===0),he.setAttribute(`aria-expanded`,f===KC?`true`:`false`);let r=_e.querySelector(`.persona-history-menu`);if(f!==KC||e.length===0)r?.remove();else{let n=wC({label:t.listOptionsLabel,items:e,onCloseMenu:e=>Ze(e)});r?r.replaceWith(n):_e.appendChild(n)}}_e.hidden=g!==`rail`&&(!he||he.hidden)&&(!e.showScopeStatus||N.hidden)},Je,Ye=()=>{let t=e.onActiveConversationChange;if(!t)return;let n=a.find(e=>e.id===l)??null,r=n?`${n.id}\0${n.title}\0${+!!n.starred}`:``;r!==Je&&(Je=r,t(n))},Xe=()=>{m||(Ye(),b?(Ie(),Re(),qe(),Ge(),Se()):e.onModelChange?.())},Ze=e=>{if(!f)return;let t=f;f=null,p=!1,Xe(),e?.restoreFocus&&R.querySelector(`[data-persona-history-focus="menu:${t}"]`)?.focus()},Qe=e=>{f===e?Ze({restoreFocus:!0}):(f=e,p=!0,Xe())},$e=e=>{if(!f)return;let t=e.target;t instanceof Node&&R.contains(t)&&t.closest?.(`[data-persona-history-item="${f}"]`)||Ze()};document.addEventListener(`pointerdown`,$e,!0);let et=e=>{e.key===`Escape`&&f&&(e.stopPropagation(),Ze({restoreFocus:!0}))};R.addEventListener(`keydown`,et);async function U(t){if(m)return;let n=++h,i=t===`load-more`?o:null;if(t!==`load-more`||i){c={kind:t===`load-more`?`load-more`:`refresh`},s={kind:`loading`,phase:t},t!==`load-more`&&(x.clear(),S=null),Ze(),Xe();try{let t=await e.provider.list({limit:r,context:e.context,...i?{cursor:i}:{},...e.targetId?{targetId:e.targetId}:{}});if(m||n!==h)return;a=i?[...a,...t.items]:t.items,o=t.nextCursor,s=a.length===0?{kind:`empty`}:{kind:`ready`}}catch(e){if(m||n!==h)return;s=MC(e)}finally{!m&&n===h&&(c=null,Xe())}}}let W=e=>{a=a.filter(t=>t.id!==e),x.delete(e),l===e&&(l=null),a.length===0&&!o&&(s={kind:`empty`})};async function G(n){if(!(T()||m)){x.delete(n),Ze(),c={kind:`open`,conversationId:n},Xe();try{if(await e.onSelect(n),m)return;l=n}catch{if(m)return;x.set(n,{message:t.openFailedLabel,retry:()=>void G(n)})}finally{m||(c=null,Xe())}}}async function tt(n){if(T()||m)return`cancelled`;x.delete(n),c={kind:`delete`,conversationId:n},Xe();try{let r=await e.onRequestDeleteConversation(n);return m||r===`deleted`&&(W(n),w(t.conversationRemovedNotice)),r}catch(e){return m||(uo(e)&&e.code===`not_found`?W(n):x.set(n,{message:t.deleteFailedLabel,retry:()=>void tt(n)})),`cancelled`}finally{m||(c=null,Xe())}}async function nt(){if(!(T()||m)){S=null,Ze(),c={kind:`start-new`},Xe();try{if(await e.onStartNew(),m)return;s.kind===`new_conversation_required`&&(s=a.length===0?{kind:`empty`}:{kind:`ready`})}catch{if(m)return;S={message:t.errorDescription,retry:()=>void nt()}}finally{m||(c=null,Xe())}}}async function K(){if(T()||m)return`cancelled`;S=null,Ze(),c={kind:`clear`},Xe();try{let n=await e.onRequestClearHistory();return m||n===`cleared`&&(a=[],o=null,l=null,s={kind:`empty`},w(t.historyClearedNotice)),n}catch{return m||(S={message:t.errorDescription,retry:()=>void K()}),`cancelled`}finally{m||(c=null,Xe())}}let q={outcome:`cancelled`};async function J(){if(T()||m||!e.onRequestResetIdentity)return q;S=null,Ze(),c={kind:`reset`},Xe();try{let n=await e.onRequestResetIdentity();return m||n.outcome===`reset`&&(w(n.remoteRevocationConfirmed?t.identityResetNotice:t.identityResetUnconfirmedNotice),c=null,await U(`refresh`)),n}catch{return m||(S={message:t.errorDescription,retry:()=>void J()}),q}finally{!m&&c?.kind===`reset`&&(c=null,Xe())}}let rt=e.provider.subscribeIdentityStatus(e=>{if(m)return;let n=BC(e),r=n!==d;u=e,d=n,Xe(),r&&e.state!==`verifying`&&w(VC(e,t).title)}),it=e.provider.subscribeAvailability?.(e=>{m||(e?U(`refresh`):(a=[],o=null,s={kind:`error`,reason:`unavailable`,retryable:!1},Xe()))});return Xe(),U(`initial`),{element:R,copy:t,getModel:()=>({conversations:a,activeConversationId:l,state:s,pendingAction:c,identityStatus:u,nextCursor:o}),operations:{refresh:async()=>{T()||await U(`refresh`)},loadMore:async()=>{T()||await U(`load-more`)},openConversation:e=>G(e),startNewConversation:()=>nt(),requestDeleteConversation:e=>tt(e),requestClearConversationHistory:()=>K(),requestResetHistoryIdentity:()=>J()},setDomRenderEnabled:e=>{e!==b&&(b=e,e&&Xe())},refresh:()=>{U(`refresh`)},setPresentation:e=>{if(e===g)return;De(),g=e,Fe=null;let t=e===`rail`;R.classList.toggle(`persona-history-view--panel`,!t),R.classList.toggle(`persona-history-view--rail`,t),R.setAttribute(`data-persona-history-presentation`,e),j(),z(),se(),re(),Ce(),Xe()},setCollapsed:e=>{e!==v&&(v=e,z(),j(),re(),Se())},setRailSide:e=>{y=e===`right`,se()},getHeaderElement:()=>Pe,setHeaderPlacement:e=>{if(e===L)return;L=e;let t=e===`external`;ae.classList.toggle(`persona-history-topbar--shell`,t),t?(Ae(),Pe.remove()):(ke(),R.insertBefore(Pe,ve))},setActiveConversationId:e=>{l!==e&&(l=e,Xe())},applyConversationSummary:e=>{let t=a.findIndex(t=>t.id===e.id);t!==-1&&(a[t]=e,Xe())},removeConversationSummary:e=>{a.some(t=>t.id===e)&&(W(e),Xe())},setNewConversationRequired:e=>{e?s={kind:`new_conversation_required`}:s.kind===`new_conversation_required`&&(s=a.length===0?{kind:`empty`}:{kind:`ready`}),Xe()},playExit:H,destroy:()=>{m=!0,h+=1,De(),ke(),ie.forEach(e=>e?.destroy()),Pe.remove(),B.forEach(e=>e.cancel()),B=[],rt(),it?.(),document.removeEventListener(`pointerdown`,$e,!0),R.removeEventListener(`keydown`,et),C.destroy(),R.remove(),R.replaceChildren()}}}var GC,KC,qC,JC,YC,XC,ZC,QC,$C=o((()=>{Hs(),H(),YS(),ZS(),aC(),mC(),yC(),AC(),zC(),po(),GC=25,KC=`persona:list-options`,qC=180,JC=160,YC=`cubic-bezier(0.4, 0, 1, 1)`,XC={panel:20,rail:12},ZC=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,QC=e=>e.finished?e.finished.then(()=>void 0,()=>void 0):Promise.resolve()})),ew=o((()=>{$C(),aC()}));function tw(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),r=`persona-history-confirm-title-${n}`,i=`persona-history-confirm-desc-${n}`,a=V(`button`,{className:`persona-history-confirm__cancel`,text:e.cancelLabel,attrs:{type:`button`}}),o=V(`button`,{className:`persona-history-confirm__confirm`,text:e.confirmLabel,attrs:{type:`button`,"data-persona-destructive":`true`}}),s=V(`div`,{className:`persona-history-confirm__dialog`,attrs:{role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":r,"aria-describedby":i},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`}},V(`h2`,{className:`persona-history-confirm__title`,text:e.title,attrs:{id:r},style:{margin:`0`,fontSize:`1rem`,fontWeight:`600`}}),V(`p`,{className:`persona-history-confirm__description`,text:e.description,attrs:{id:i},style:{margin:`0`,fontSize:`0.875rem`,lineHeight:`1.4`}}),V(`div`,{className:`persona-history-confirm__actions`,style:{display:`flex`,gap:`8px`,justifyContent:`flex-end`,flexWrap:`wrap`}},a,o));for(let e of[a,o])e.style.minHeight=`44px`,e.style.minWidth=`88px`,e.style.padding=`0 16px`,e.style.borderRadius=`var(--persona-radius-md, 0.5rem)`,e.style.cursor=`pointer`,e.style.font=`inherit`;a.style.border=`1px solid var(--persona-border, rgba(0,0,0,0.12))`,a.style.background=`transparent`,a.style.color=`inherit`,o.style.border=`none`,o.style.background=`var(--persona-danger, #b42318)`,o.style.color=`var(--persona-danger-fg, #ffffff)`;let c=V(`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))`}},s);return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,c.removeEventListener(`keydown`,l,!0),c.remove(),t?.focus(),n(e))};function l(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),i(!1);return}if(e.key!==`Tab`)return;let t=Array.from(s.querySelectorAll(nw));if(t.length===0)return;let n=t[0],r=t[t.length-1],a=document.activeElement;e.shiftKey&&(a===n||!s.contains(a))?(e.preventDefault(),r.focus()):!e.shiftKey&&a===r&&(e.preventDefault(),n.focus())}c.addEventListener(`keydown`,l,!0),c.addEventListener(`pointerdown`,e=>{e.target===c&&i(!1)}),a.addEventListener(`click`,()=>i(!1)),o.addEventListener(`click`,()=>i(!0)),e.host.appendChild(c),a.focus()})}var nw,rw=o((()=>{H(),nw=`button:not([disabled])`})),iw=/* @__PURE__ */ s({HISTORY_VIEW_COPY_DEFAULTS:()=>iC,createHistoryView:()=>WC,resolveHistoryViewCopy:()=>nC,showHistoryConfirm:()=>tw}),aw=o((()=>{ew(),rw()}));Pe();const{setLoader:ow,load:sw}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(aw(),iw))}),cw=sw;function lw(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,c=[],l=()=>{for(let e of c.splice(0))try{e()}catch(e){uw(`renderHistoryView cleanup`,e)}},u=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){uw(e,t)}}return null},d=()=>({presentation:e.getPresentation(),config:n}),f={header:t=>o?u(`renderHistoryHeader`,Object.freeze({...d(),returnSurface:e.getReturnSurface(),identityStatus:dw(t.identityStatus),pendingAction:pw(t.pendingAction),copy:dw(t.copy),actions:Object.freeze({close:h.close,startNewConversation:h.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?u(`renderHistoryConversation`,Object.freeze({...d(),conversation:fw(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?u(`renderHistoryState`,Object.freeze({...d(),state:dw(e.state),identityStatus:dw(e.identityStatus),copy:dw(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},p=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:h}))}))),m=e.createView({slots:f,renderDom:!1,onModelChange:()=>y(),railSections:p}),h=Object.freeze({...m.operations,close:e.close}),g=()=>(o=!0,m.setDomRenderEnabled(!0),m.element),_=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(fw)),activeConversationId:t.activeConversationId,state:dw(t.state),pendingAction:pw(t.pendingAction),identityStatus:dw(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:dw(m.copy),actions:h,defaultRenderer:g,requestRender:()=>y(),onCleanup:e=>{c.push(e)}}),v=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(_(m.getModel()))}catch(t){uw(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(m.element);return o=n,m.setDomRenderEnabled(n),e??m.element};function y(){if(!(!a||r||i)){i=!0;try{l();let t=v();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,y(),{view:m,get element(){return s??m.element},requestRender:y,dispose:()=>{r=!0,l()}}}var uw,dw,fw,pw,mw=o((()=>{uw=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},dw=e=>Object.freeze({...e}),fw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),pw=e=>e?dw(e):null}));function hw(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=_w.get(e.code)??`unavailable`;return new n(t,yw(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,yw(`unavailable`))}function gw(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],i={scopes:r},a=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,yw(`unsupported_scope`))},o=async(t,n)=>{a(t);try{return await n()}catch(t){throw hw(t,e.errors)}},s=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:i,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return o(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return o(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),i=qa(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:Ya([],i),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return o(t.context.scope,async()=>s(await n().prepareConversationSession(e)))},async prepareStartNew(e){return o(e.context.scope,async()=>s(await n().prepareNewConversationSession()))},async delete(e,t){await o(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return o(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var _w,vw,yw,bw=o((()=>{Qa(),_w=/* @__PURE__ */ 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`]]),vw=/* @__PURE__ */ 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.`]]),yw=e=>vw.get(e)??`Conversation history is unavailable right now.`})),xw=/* @__PURE__ */ s({createHistoryShell:()=>Sw}),Sw,Cw=o((()=>{tC(),mw(),H(),gm(),Wr(),bw(),Sw=e=>{let t=QS(e.config.features?.history?.copy),n=null,r=!1,i=null,a=null,o=`conversation`,s=null,c=null,l=null,u=null,d=0,f=null,p=null,m=null,h=`persona-history-${Math.random().toString(36).slice(2,8)}`,g=()=>e.historyFeatureEnabled()&&!!n&&!r,_=()=>{let t=e.session.getStatus();return e.isStreaming||t===`paused`||t===`resuming`},v=()=>{let t=e.config.features?.history?.scope;if(t)return t;let r=e.config.getIdentityProof?`verified-user`:`browser`,i=n?.capabilities.scopes;return!i||i.includes(r)?r:i[0]??r},y=()=>a?.scope??v(),b=()=>e.session.getClientSession()?.targetId??null,x=e=>`${e.state}:${`reason`in e?e.reason:``}`,S=t=>{let n=x(t);n!==u&&(u=n,e.eventBus.emit(`history:identityStatusChanged`,{status:t,timestamp:Date.now()}))},C=null,w=null,T=()=>{if(!e.historyFeatureEnabled())return null;let t=e.getHistoryProviderFactory();if(t)return t();let n=e.config.features?.history?.provider;return n?typeof n==`function`?(C!==n&&(C=n,w=n()),w):n:e.session.isClientTokenMode()?gw({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof==`function`,onActivationCommitted:t=>e.session.bindActivatedSession(t),getClient:()=>e.session.getClient()}):null},E=()=>{p?.(),p=null,m?.(),m=null,r=!1,n=T();let t={...e.historyInternals};n?t.historyProvider=n:delete t.historyProvider,e.historyInternals=t,e.session.setHistoryInternals(e.historyInternals),n&&(p=n.subscribeAvailability?.(e=>{r=!e,e||ut({restoreFocus:!1}),zt()})??null,m=n.subscribeIdentityStatus(e=>S(e)),u=x(n.getIdentityStatus()))},D=()=>{let t=e.config.features?.history?.presentation??`panel`;if(t===`panel`||t===`auto`&&e.launcherEnabled&&!e.isDockedMountMode(e.config))return`panel`;let n=e.artifactSplitRoot??e.container;return(n.getBoundingClientRect().width||n.clientWidth)>=720?`rail`:`panel`},O=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},k=`data-persona-history-suppressed`,A=null,j=null,ee=null,M=null,N=null,P=``,te=()=>e.header===N?P:e.config.layout?.showHeader===!1?`none`:``,ne=()=>e.historyPresentation===`panel`&&!!ee&&M===ee.element&&e.config.layout?.showHeader!==!1&&te()!==`none`,re=()=>{for(let t of Array.from(e.header.children))t!==A&&t.setAttribute(k,``)},F=()=>{for(let t of Array.from(e.container.querySelectorAll(`[${k}]`)))t.removeAttribute(k)},ie=()=>{let t=ee;if(!t)return;if(Array.from(e.header.children).some(e=>e!==A&&!e.hasAttribute(k))){j&&j!==e.header&&(j.style.removeProperty(`min-height`),j=null);let t=e.header.offsetHeight;t>0&&(e.header.style.minHeight=`${t}px`,j=e.header)}A||=B(`div`,`persona-history-header-host`),t.setHeaderPlacement(`external`);let n=t.getHeaderElement();n.parentNode!==A&&A.replaceChildren(n),A.parentNode!==e.header&&e.header.appendChild(A),re()},ae=()=>{j&&=(j.style.removeProperty(`min-height`),null),A&&(ee?.setHeaderPlacement(`inline`),A.remove(),A=null,F())},oe=null,se=()=>{oe&&(e.body.style.display=`none`,O(e.body,!0),e.footer.hidden=!0,O(e.footer,!0),ne()?(ie(),e.header.style.display=te(),O(e.header,!1)):(ae(),e.header.style.display=`none`,O(e.header,!0)))};e.reapplyHistoryHostChrome=se;let ce=t=>{let n=e.body.style.display,r=e.footer.hidden,i=e.footer,a=e.header,o=e.header.style.display;N=a,P=o,oe=()=>{oe=null,ae(),N=null,e.body.style.display=n,O(e.body,!1),i.hidden=r,O(i,!1),e.footer!==i&&(e.footer.hidden=!1,O(e.footer,!1)),a.style.display=o,O(a,!1),e.header!==a&&(e.header.style.display=e.config.layout?.showHeader===!1?`none`:``,O(e.header,!1))},e.footer.parentNode?.insertBefore(t,e.footer),se()},le=null,ue=null,de=null,I=null,fe=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],pe=()=>e.config.features?.history?.rail?.collapsible!==!1,me=()=>e.config.features?.history?.rail?.side===`right`?`right`:`left`,he=e=>Math.min(400,Math.max(200,Math.round(e))),ge=()=>e.config.features?.history?.rail?.resizable===!0,_e,ve=()=>{if(_e===void 0&&(_e=null,e.config.persistState!==!1))try{let t=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));t&&(_e=t)}catch{}return _e},L=()=>he(ve()??e.config.features?.history?.rail?.width??260),R=t=>{if(_e=t,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(t))}catch{}},z=()=>pe()&&e.config.features?.history?.rail?.collapsedBehavior===`overlay`,ye=!1,be=e=>{let t=B(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},xe=()=>{let t=e.config.features?.history?.rail?.brand;if(!t)return;let n=!1,r;return i=>{if(t.render)try{return t.render({collapsed:i})??null}catch(e){return n||(n=!0,console.warn(`[persona] history rail brand threw`,e)),null}return r===void 0&&(r=t.iconUrl?be(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null),r?r.cloneNode(!0):null}},Se=()=>e.config.features?.history?.rail?.sections?.map(t=>{let n=!1,r=e=>{n||(n=!0,console.warn(`[persona] history rail section threw`,t.id,e))};return{id:t.id,title:t.title,placement:t.placement??`above-conversations`,items:t.items.map(t=>{let n;return{id:t.id,label:t.label,badge:t.badge,iconNode:()=>{if(n!==void 0)return n;try{n=t.renderIcon?t.renderIcon()??null:t.iconUrl?be(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null}catch(e){r(e),n=null}return n},onSelect:()=>{try{t.onSelect()}catch(e){r(e)}}}})}})??[],Ce=e=>{let t=Se();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},we=null,Te=()=>`${e.currentKeyPrefix()}rail-collapsed`,Ee=()=>{if(we===null&&(we=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let e=window.localStorage.getItem(Te());e&&(we=e===`1`)}catch{}return we},De=t=>{if(we=t,e.config.persistState!==!1)try{window.localStorage.setItem(Te(),t?`1`:`0`)}catch{}},Oe=()=>e.historyPresentation===`rail`&&pe()&&!z()&&Ee(),ke=()=>{},Ae=()=>{z()?ke():(De(!Ee()),i?.view.setCollapsed(Oe()),e.applyRailChrome(),e.repinAnchoredMessage())},je=()=>{let t=e.config.features?.history?.rail?.collapseShortcut;return!t||!cm(t)?null:{combo:t,hint:dm(t),aria:fm(t)}},H=`var(--persona-history-overlay-margin,8px)`,Ne=null,Pe=null,Fe=0,Ie=null,Le=null,Re=!1,ze=0,Be=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,Ve=()=>g()&&z()&&(e.historyPresentation??D())===`rail`,He=()=>e.historyVisible&&!ye,Ue=()=>{Le!==null&&clearTimeout(Le),Le=null},We=()=>{e.loadHistoryView().catch(()=>{})},Ge=()=>{Ue(),ye&&(Le=setTimeout(()=>{Le=null,!Re&&ye&&(Ie?.contains(document.activeElement)||ut({restoreFocus:!1}))},300))},Ke=(e,t)=>{let n=Ie?.getBoundingClientRect();if(!n)return!1;let r=Ne?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},qe=e=>{ye&&(Re=Ke(e.clientX,e.clientY),Re?Ue():Le===null&&Ge())},Je=t=>{!e.historyVisible&&Ve()&&(ye=!0,ct({invoker:Ne,keyboard:t?.keyboard===!0}).then(()=>{e.historyVisible?!Re&&document.activeElement!==Ne&&ut():ye=!1}))},Ye=()=>{let e=M?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,ye?t.expandLabel:t.collapseLabel),e.setAttribute(`aria-expanded`,ye?`false`:`true`))},Xe=()=>{De(!1);let t=i;if(!ye||!t){ct({invoker:Ne});return}let n=document.activeElement===Ne;ye=!1,it(),t.element.remove(),Y(t.element),Ye(),n&&X(),e.repinAnchoredMessage(),zt()},Ze=()=>{De(!0),ut()};ke=()=>{!e.historyVisible||ye?Xe():Ze()};let Qe=()=>{let n=je(),r=e.createHeaderIconButton({ariaLabel:t.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":h,...n?{"aria-keyshortcuts":n.aria}:{}}}),i=r.button;i.addEventListener(`mouseenter`,()=>{Re=!0,Ue(),!(Be()||Date.now()<ze)&&Je()}),i.addEventListener(`mouseleave`,()=>{Re=!1,ze=0,Ge()}),i.addEventListener(`focus`,()=>{e.historyVisible||We()}),i.addEventListener(`click`,t=>{g()&&(t.detail!==0&&Be()&&!e.historyVisible?Je():Xe())}),Ne=i,Pe=r.wrapper},$e=()=>{if(Pe&&!Pe.isConnected&&(Pe=null,Ne=null),!Ve()){Pe?.remove(),Pe=null,Ne=null;return}Ne||Qe();let n=Pe,r=Ne;if(!n||!r)return;let i=me()===`right`?null:e.header.firstChild;(i??e.header.lastChild)!==n&&e.header.insertBefore(n,i),n.style.display=He()||Fe>0?`none`:``,r.setAttribute(`aria-label`,t.expandLabel),r.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),Ie&&e.applyRailChrome()},et=e=>{if(!ye)return;let t=e.target;t instanceof Node&&(Ie?.contains(t)||Pe?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||ut({restoreFocus:!1}))};document.addEventListener(`pointerdown`,et,!0),e.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,et,!0),document.removeEventListener(`pointermove`,qe),W?.(),Ue()});let U=null,W=null,G=t=>{R(he(t)),e.applyRailChrome(),e.repinAnchoredMessage()},tt=()=>{let t=B(`div`,`persona-rail-resizer`);return t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-valuemin`,`200`),t.setAttribute(`aria-valuemax`,`400`),t.addEventListener(`pointerdown`,n=>{let r=ue;if(!r||n.button!==0)return;n.preventDefault(),W?.();let i=n.clientX,a=r.getBoundingClientRect().width||L(),o=me()===`right`?-1:1,s=a,c=e.mount.ownerDocument;r.style.transition=`none`;let l=e=>{s=he(a+o*(e.clientX-i)),r.style.flex=`0 0 ${s}px`,t.setAttribute(`aria-valuenow`,String(s))},u=()=>{W=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),r.style.removeProperty(`transition`);try{t.releasePointerCapture(n.pointerId)}catch{}G(s)};W=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{t.setPointerCapture(n.pointerId)}catch{}}),t.addEventListener(`keydown`,e=>{let t=me()===`right`?-16:16,n=L(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),G(r))}),t},nt=(e,n)=>{if(!ge()||Oe()){W?.(),U?.remove();return}let r=U??tt();U=r,r.setAttribute(`aria-label`,t.resizeLabel),r.setAttribute(`aria-valuenow`,String(L())),r.nextElementSibling!==n&&e.insertBefore(r,n)};e.applyRailChrome=()=>{i?.view.setRailSide(me());let t=me()===`right`,n=Ie;if(n){let r=Ne?Ne.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;n.style.top=`calc(${Math.max(0,Math.round(r))}px + ${H})`,n.style.width=`${L()}px`,n.style.left=t?``:H,n.style.right=t?H:``}let r=ue,a=le,o=de;if(!r||!a||!o)return;r.style.flex=`0 0 ${Oe()?52:L()}px`;let s=`1px solid var(--persona-divider,#e5e7eb)`;r.style.borderRight=t?``:s,r.style.borderLeft=t?s:``;let c=t?o:r;a.firstElementChild!==c&&a.append(c,t?r:o),nt(a,t?r:o)};let K=t=>{if(I&&ue){I.replaceWith(t),I=null,e.applyRailChrome();return}let n=B(`div`,`persona-history-rail-shell`);n.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=B(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let i=B(`div`,`persona-history-rail-host`);i.style.cssText=`display:flex;min-height:0;overflow:hidden`,e.container.insertBefore(n,e.header.parentNode===e.container?e.header:e.body);for(let t of fe())t?.parentNode===e.container&&r.appendChild(t);n.append(i,r),i.appendChild(t),le=n,ue=i,de=r,e.applyRailChrome()},q=()=>{if(le)return;let t=B(`div`,`persona-history-rail-placeholder`);t.style.cssText=`flex:1 1 auto;min-height:0`,I=t,K(t),e.repinAnchoredMessage()},J=()=>{I&&(it(),e.repinAnchoredMessage())},rt=t=>{let n=B(`div`,`persona-history-rail-overlay`);n.style.cssText=`position:absolute;bottom:${H};display:flex;overflow:hidden;z-index:${Ur-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(n),n.appendChild(t),document.addEventListener(`pointermove`,qe),Ie=n,e.applyRailChrome(),Ye()},it=()=>{oe?.(),Ie&&=(Re&&(ze=Date.now()+150),document.removeEventListener(`pointermove`,qe),Ie.remove(),null);let t=le;if(t){W?.();for(let n of fe())n&&t.contains(n)&&e.container.insertBefore(n,t);t.remove(),le=null,ue=null,de=null,I=null}},at=e=>{M=e,e.id=h,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},Y=t=>{at(t),(e.historyPresentation!==`rail`||ye)&&J(),e.historyPresentation===`rail`?ye?rt(t):K(t):ce(t)},ot=()=>{if($e(),It(),!e.historyVisible||!i)return;let t=D();if(t===e.historyPresentation)return;let n=document.activeElement,r=n instanceof HTMLElement&&(i.element.contains(n)||A?.contains(n)===!0)?n:null;it(),i.element.remove(),i.view.setHeaderPlacement(`inline`),e.historyPresentation=t,i.view.setPresentation(t),i.view.setCollapsed(Oe()),i.requestRender(),i.element.isConnected||Y(i.element),r?.isConnected?r.focus():X(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),zt()},st=(e,t)=>A?.querySelector(t)??e.querySelector(t),X=()=>{let e=i?.element??M;if(!e)return;let t=st(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=st(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},ct=async r=>{if(!g()||e.historyVisible)return;let l=n;if(!l)return;if(!ye&&Ve()&&Ee()){$e();return}lt();let u=++d;o=r?.returnSurface??`conversation`,s=r?.invoker??c;let f=Ve()&&!ye;f&&(Fe+=1,$e(),q());let p;try{p=await e.loadHistoryView()}catch{e.announceHistory(t.openHistoryLabel),f&&(--Fe,u===d&&(J(),$e()));return}if(f&&--Fe,u!==d||e.historyVisible)return;a={scope:v()},e.historyPresentation=D(),e.historyVisible=!0;let m=e.historyPresentation===`panel`&&e.config.layout?.showHeader!==!1&&e.header.style.display!==`none`?`external`:`inline`,h=e.config.features?.history?.rowAvatar,_=je(),y=_?{hint:_.hint,aria:_.aria}:null,x={provider:l,context:a,targetId:b(),presentation:e.historyPresentation,collapsible:pe(),collapsed:Oe(),railSide:me(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:xe(),onToggleCollapse:Ae,...y?{collapseShortcut:y}:{},headerPlacement:m,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:h===!1?!1:typeof h==`string`?h: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:e=>Ct(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:t=>e.setActiveConversationSummary(t),attachTooltip:e.attachTooltip,onStartNew:()=>wt({focusComposer:!0}),onClose:()=>ut(),onRequestDeleteConversation:e=>jt(e),onRequestClearHistory:()=>Mt(),...l.resetDevice?{onRequestResetIdentity:()=>Nt()}:{}};i=lw({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??`panel`,getReturnSurface:()=>o,close:()=>ut(),createView:({slots:t,renderDom:n,onModelChange:r,railSections:i})=>(ee=p.createHistoryView({...x,railSections:Ce(i),slots:t,renderDom:n,onModelChange:r,onAnnounce:e.announceHistory}),ee),onElementChanged:(e,t)=>{if(!t?.isConnected)return Y(e);at(e),t.replaceWith(e),se()}}),i.view.setNewConversationRequired(e.historySessionState.recovery===`new_conversation_required`),r?.focus!==!1&&(e.historyPresentation!==`rail`||r?.keyboard===!0)&&X(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),zt(),e.eventBus.emit(`history:opened`,{presentation:e.historyPresentation,returnSurface:o,timestamp:Date.now()})},lt=()=>{},ut=t=>{if(!e.historyVisible)return;d+=1;let n=o,r=s,l=i,u=t?.restoreFocus!==!1;e.historyVisible=!1;let f=!1,p=null,m=()=>{if(!f){if(f=!0,lt=()=>{},p!==null&&clearTimeout(p),ye=!1,Ue(),it(),l?.dispose(),l?.view.destroy(),l?.element.remove(),i===l&&(i=null,ee=null,M=null,e.historyPresentation=null,a=null,s=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),zt(),u){let t=r??c;t?.isConnected?t.focus():e.maybeFocusInput()}e.eventBus.emit(`history:closed`,{returnSurface:n,timestamp:Date.now()})}},h=l&&l.element===l.view.element?l.view.playExit():null;h?(lt=m,p=setTimeout(m,250),h.then(m)):m()},dt=t=>{if(t.key===`Escape`&&e.historyVisible&&i){if(e.historyPresentation===`rail`){let e=t.target;if(!(e instanceof Node)||!(i.element.contains(e)||ye&&Pe?.contains(e)===!0))return}t.preventDefault(),t.stopPropagation(),ut()}};e.container.addEventListener(`keydown`,dt),e.destroyCallbacks.push(()=>e.container.removeEventListener(`keydown`,dt));let ft=0,pt=null,mt=()=>{pt&&clearTimeout(pt),pt=null};e.destroyCallbacks.push(mt);let ht=()=>{mt();let t=e.conversationOpenPendingEl;t&&(e.conversationOpenTakeover=!0,t.hidden=!1,e.messagesWrapper.style.display=`none`,e.updateWelcome())},gt=()=>{ft+=1,mt(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty(`display`),O(e.footer,!1),e.updateWelcome())},_t=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},vt=(e,t)=>V(`div`,{className:Me(`persona-conversation-loading-bubble`,t&&`persona-conversation-loading-bubble--trailing`),attrs:{"aria-hidden":`true`},style:{width:e}}),yt=()=>V(`div`,{className:`persona-conversation-loading-body`},vt(`58%`,!1),vt(`72%`,!0),vt(`44%`,!1)),bt=t=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=t,t.hidden=!e.conversationOpenTakeover,e.body.insertBefore(t,e.messagesWrapper),mt(),e.conversationOpenTakeover||(pt=setTimeout(ht,250)),O(e.footer,!0)},xt=()=>{let n={config:e.config,streaming:!1,location:`conversation-open`,defaultRenderer:yt},r=null,i=e.plugins.find(e=>e.renderLoadingIndicator);i?.renderLoadingIndicator&&(r=i.renderLoadingIndicator(n)),r===null&&e.config.loadingIndicator?.render&&(r=e.config.loadingIndicator.render(n)),bt(V(`div`,{className:`persona-conversation-loading`,attrs:{role:`status`,"aria-label":t.openConversationLoadingLabel}},r??yt()))},St=n=>{let r=()=>{Ct(n,{focusComposer:!0}).catch(()=>{})},i=g()?()=>{gt(),ct()}:void 0,a=(e,t)=>{let n=V(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return n.addEventListener(`click`,t),n},o=()=>V(`div`,{className:`persona-conversation-loading-error-body`},V(`p`,{className:`persona-conversation-loading-error-title`,text:t.openConversationErrorTitle}),V(`div`,{className:`persona-conversation-loading-error-actions`},a(t.openConversationRetryLabel,r),i?a(t.openConversationBackLabel,i):null)),s=Object.freeze({conversationId:n,config:e.config,copy:Object.freeze({title:t.openConversationErrorTitle,retryLabel:t.openConversationRetryLabel,backLabel:t.openConversationBackLabel}),retry:r,...i?{back:i}:{},defaultRenderer:o}),c=null;for(let t of e.plugins)if(t.renderHistoryOpenError){try{c=t.renderHistoryOpenError(s)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),c=null}if(c)break}bt(V(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},c??o())),ht()};e.eventBus.on(`history:closed`,()=>{e.conversationOpenPendingEl&&O(e.footer,!0)});let Ct=async(t,{focusComposer:n=!1}={})=>{let r=y(),a=!!i;i?.view.setActiveConversationId(t),gt();let o=ft;xt(),e.historyVisible&&(e.historyPresentation===`panel`||ye)&&ut({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(t,{scope:r})}catch(e){throw o===ft&&St(t),e}finally{e.suppressScrollSend=!1}o===ft&&(gt(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),_t(),Ft(),a||e.setActiveConversationSummary(null),e.eventBus.emit(`history:conversationOpened`,{conversationId:t,title:e.activeConversationTitle,scope:r,timestamp:Date.now()}),n&&e.maybeFocusInput())},wt=async({focusComposer:t=!1}={})=>{gt(),await e.session.startNewConversation({scope:y()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Ft();let n=e.session.getActiveConversationId();i?.view.setActiveConversationId(n),e.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation===`panel`||ye)&&ut({restoreFocus:!1}),t&&e.maybeFocusInput()},Tt=async(t,n)=>{let r=await e.session.updateConversation(t,{...n,...n.title===void 0?{}:{title:n.title.trim()}});return i?.view.applyConversationSummary(r),!i&&t===e.session.getActiveConversationId()&&e.setActiveConversationSummary(r),r},Et=async t=>{let n=y(),r=e.session.getActiveConversationId()===t;await e.session.deleteConversation(t,{scope:n}),i?.view.removeConversationSummary(t),r&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Ft()),e.eventBus.emit(`history:conversationDeleted`,{conversationId:t,scope:n,wasActive:r,timestamp:Date.now()})},Dt=async t=>{let n=t?.scope??y(),r=t?.allTargets?null:t?.targetId??b(),i=await e.session.clearConversationHistory({...r?{targetId:r}:{},scope:n});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Ft(),e.eventBus.emit(`history:cleared`,{deleted:i.deleted,scope:n,targetId:r,timestamp:Date.now()}),i},Ot=async()=>{if(!n?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let r=!1;try{r=(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 t=e.storageAdapter;t?.clear&&e.runStorageMutation(()=>t.clear(),`[AgentWidget] Failed to clear storage adapter:`),e.resetAnchorState(),e.resumeAutoScroll(),Ft(),ut({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(r?t.identityResetNotice:t.identityResetUnconfirmedNotice),e.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},kt=()=>e.artifactSplitRoot?e.panel:e.container,At=async t=>{let n=await e.loadHistoryView().catch(()=>null);return typeof n?.showHistoryConfirm==`function`?n.showHistoryConfirm(t):window.confirm(`${t.title}\n\n${t.description}`)},jt=async e=>await At({host:kt(),title:t.deleteConversationConfirmTitle,description:t.deleteConversationConfirm,confirmLabel:t.deleteConversationConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Et(e),`deleted`):`cancelled`,Mt=async()=>{let e=y()===`verified-user`;return await At({host:kt(),title:t.clearHistoryConfirmTitle,description:e?t.clearHistoryVerifiedConfirm:t.clearHistoryConfirm,confirmLabel:t.clearHistoryConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Dt(),`cleared`):`cancelled`},Nt=async()=>{if(!await At({host:kt(),title:t.resetIdentityConfirmTitle,description:t.resetIdentityConfirm,confirmLabel:t.resetIdentityConfirmLabel,cancelLabel:t.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await Ot();return{outcome:`reset`,remoteRevocationConfirmed:e}},Pt=B(`button`,`persona-history-earlier`);Pt.type=`button`,Pt.textContent=t.showEarlierMessagesLabel,Pt.setAttribute(`data-persona-history-earlier`,``),Object.assign(Pt.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 Ft=()=>{g()&&e.historySessionState.nextMessageCursor&&e.session.getActiveConversationId()?(Pt.textContent=t.showEarlierMessagesLabel,Pt.parentNode!==e.body&&e.body.insertBefore(Pt,e.body.firstChild)):Pt.remove()};Pt.addEventListener(`click`,()=>{let t=e.session.getActiveConversationId(),n=e.historySessionState.nextMessageCursor;if(!t||!n||Pt.disabled)return;Pt.disabled=!0;let r=e.body.scrollHeight,i=e.body.scrollTop;e.session.loadOlderMessages(t,n,{scope:y()}).then(()=>{e.body.scrollTop=i+(e.body.scrollHeight-r),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Pt.disabled=!1,Ft()})});let Z=()=>{let n=e.createHeaderIconButton({ariaLabel:t.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 n.button.addEventListener(`click`,t=>{g()&&!_()&&(e.historyVisible?ut():ct({invoker:n.button,keyboard:t.detail===0}))}),n},It=()=>{if(!g()){l?.remove(),c=null,l=null;return}if(l&&!l.isConnected&&(c=null,l=null),!c&&e.header){let t=Z();c=t.button,l=t.wrapper;let n=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;n?.parentNode&&e.header.contains(n)?n.parentNode.insertBefore(l,n):e.header.appendChild(l)}if(!c||!l)return;let n=Ve()||e.historyVisible&&e.historyPresentation===`rail`;if(l.style.display=n?`none`:``,n){document.activeElement===c&&X();return}let r=_();c.disabled=r,c.setAttribute(`aria-disabled`,r?`true`:`false`);let i=r?t.openHistoryBusyLabel:t.openHistoryLabel;c.setAttribute(`aria-label`,i),(e.config.features?.history?.presentation??`panel`)===`panel`?(c.removeAttribute(`aria-expanded`),c.removeAttribute(`aria-controls`)):(c.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),c.setAttribute(`aria-controls`,h))},Lt=!1,Rt=()=>{let n=e.panelElements.clearChatButton;n&&(g()?(Lt||=(f=n.getAttribute(`aria-label`)??``,!0),n.setAttribute(`aria-label`,t.newConversationLabel),n.removeAttribute(`title`)):Lt&&(Lt=!1,f&&n.setAttribute(`aria-label`,f)))},zt=()=>{t=QS(e.config.features?.history?.copy),It(),$e(),Rt(),Ft()};return e.historyChromeSync=zt,E(),zt(),e.destroyCallbacks.push(()=>{p?.(),m?.(),d+=1,lt(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:g,historyScope:v,installHistoryProvider:E,syncHistoryChromeImpl:zt,syncHistoryPresentation:ot,syncEarlierMessagesPill:Ft,openHistory:ct,closeHistory:ut,openHistoryConversation:Ct,startNewConversation:wt,updateHistoryConversation:Tt,deleteHistoryConversation:Et,requestDeleteConversation:jt,clearConversationHistory:Dt,resetHistoryIdentity:Ot,railCollapseShortcut:je,railCollapsible:pe,railTriggerApplies:Ve,railOverlayMode:z,toggleRailCollapsed:Ae,toggleRailPinned:()=>ke(),get historyProvider(){return n},get historySurface(){return i},get railShell(){return le},get railHost(){return ue},get railColumn(){return de}}}}));Pe();const{setLoader:ww,load:Tw,provide:Ew,getSync:Dw}=Ne({fallbackImport:()=>Promise.resolve().then(()=>(Cw(),xw))}),Ow=Tw,kw=Dw;function Aw(){return null}Ny(),H();function jw(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=My.get(e.component);if(!a){if(bx.includes(e.component)){Ox().catch(()=>{});let e=B(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Mw(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 Nw(e){let t=Mw(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Pw(e){let t=Mw(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const Fw=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function Iw(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=Fw}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
1162
1162
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1163
1163
|
<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>
|
|
1164
1164
|
</svg>
|
|
1165
|
-
`,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function Ew(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}it(),bt(),Tt(),ht(),io(),gs(),Ys(),qo(),oc(),qc(),os(),La(),y(),ze(),g(),H(),Io(),I(),om(),Tm(),Br(),Xm(),is(),xr(),Mr(),Sn(),Jt(),tn(),he(),ne(),Cy();const Dw=`persona-chat-history`,Ow=`data-persona-composer-reason`,kw=`data-persona-composer-notice`,Aw={"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 jw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Aw[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function Mw(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 Nw(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 Pw(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const Fw=e=>!e||typeof e!=`object`?{}:{...e},Iw=e=>e.map(e=>({...e,streaming:!1})),Lw=(e,t,n)=>{let r=e?.markdown?vt(e.markdown):null,i=wt(e?.sanitize);e?.postprocessMessage&&i&&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 a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=mt()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?Mt(o):o,t=r(e);l=i&&c?i(t):t}else l=yt(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),yt(e.text??``)}}};function Rw(e){let t=z(`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`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=U(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=z(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const zw=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Bw=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:zw(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Vw=(e,t,n)=>{if(e==null)throw 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 r=oe(t),i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=$e((e,t)=>{ta.delete(e);let n=Array.from(q.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?$_(e,n,i,r):H_(e,n,a))}),s=/* @__PURE__ */ new Map,c=()=>{_o({delayMs:r.tooltip?.delayMs??200,skipDelayMs:r.tooltip?.skipDelayMs??300})};c();let l=r.features;r=Qx(r);let d=gS.getForInstance(r.plugins),f=am(e),p=[],m=!1,g=R_(()=>r),v=null,y=null,b=null,x=!1,S=null,C=e=>{v=e,e.initApprovalUi({webMcpToolTitle:Ut});let t=e.createBuiltInApprovalPlugin(s);y=t.plugin,b=t.teardown},w=()=>{if(v)return v;let e=jv();return e?(C(e),e):(Av().then(e=>{x||v||(C(e),S?.())}).catch(()=>{}),null)},T=!1,E=!1,D=null,O=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=hS();i?i.enhanceWithForms(e,t,n,r):mS().then(()=>{T||E||!D||(E=!0,D())}).catch(()=>{})};r.components&&Sy.registerAll(r.components);let k=xS(),A=r.persistState===!1?null:r.storageAdapter??MS(),j=!!r.clientToken&&typeof r.reconnectStream!=`function`,M={},ee=null,P,F=new Promise(e=>{P=e}),te=()=>{},ne=new Promise(e=>{te=e}),I,re=!1,ie=e=>{if(r.onStateLoaded)try{let t=r.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(re=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(A?.load)try{let e=A.load();if(e&&typeof e.then==`function`)ee=e.then(e=>ie(e??{messages:[],metadata:{}}));else{let t=ie(e??{messages:[],metadata:{}});t.metadata&&(M=Fw(t.metadata)),t.messages?.length&&(r={...r,initialMessages:t.messages}),t.artifacts?.length&&(r={...r,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),I=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(r.onStateLoaded)try{let e=ie({messages:[],metadata:{}});e.messages?.length&&(r={...r,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}ee||P();let ae=()=>M,se=e=>{M=e({...M})??{},qa()},ce=r.actionParsers&&r.actionParsers.length?r.actionParsers:[wS],le=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ES.message,ES.messageAndClick],L=OS({parsers:ce,handlers:le,getSessionMetadata:ae,updateSessionMetadata:se,emit:k.emit,documentRef:typeof document<`u`?document:null});L.syncFromMetadata();let R=r.launcher?.enabled??!0,ue=r.launcher?.autoExpand??!1,de=r.autoFocusInput??!1,fe=ue,pe=R,me=r.layout?.header?.layout,he=!1,ge=()=>Bh(r),B=()=>R||ge(),V=ge()?!1:!R||ue,H=!1,_e=null,ve=()=>{H=!0,_e&&clearTimeout(_e),_e=setTimeout(()=>{H&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},ye=Lw(r,L,ve),be=r.features?.showReasoning??!0,xe=r.features?.showToolCalls??!0,Se=r.features?.showEventStreamToggle??!1,Ce=r.features?.scrollToBottom??{},we=r.features?.scrollBehavior??{},Te=()=>(typeof r.persistState==`object`?r.persistState?.keyPrefix:void 0)??`persona-`,Ee=`${Te()}event-stream`,De=null,Oe=r.features?.eventStream?.maxEvents??2e3,ke=null,Ae=null,je=null,Me=!1,Ne=null,Fe=!1,Ie=null,Le=0,Re=(e,t)=>{ke?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},ze=(e,t)=>{Ae?.processEvent(e,t),ke?Re(e,t):je&&(je.length>=Oe&&je.shift(),je.push({type:e,payload:t}))},Be=()=>{!ke&&Se&&(je??=[],by().then(e=>{if(Me||ke||!Se)return;De=new e.EventStreamStore(Ee),ke=new e.EventStreamBuffer(Oe,De),Ae??=new e.ThroughputTracker,De.open().then(()=>ke?.restore()).catch(e=>{r.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=je??[];je=null;for(let e of t)Ae?.processEvent(e.type,e.payload),Re(e.type,e.payload)}).catch(()=>{}))};Se&&Be();let Ve=!1,He=null,Ue=()=>{},We=()=>{},Ge=()=>{},Ke=()=>{},qe=()=>{},Je=()=>Fe||Ve&&He===`panel`,Ye={onCopy:e=>{k.emit(`message:copy`,e),$?.isClientTokenMode()&&$.submitMessageFeedback(e.id,`copy`).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),r.messageActions?.onCopy?.(e)},onFeedback:e=>{k.emit(`message:feedback`,e),$?.isClientTokenMode()&&$.submitMessageFeedback(e.messageId,e.type).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),r.messageActions?.onFeedback?.(e)}};r.statusIndicator;let Qe=(e,t=r.statusIndicator??{})=>e===`idle`?t.idleText??Lr.idle:e===`connecting`?t.connectingText??Lr.connecting:e===`connected`?t.connectedText??Lr.connected:e===`error`?t.errorText??Lr.error:e===`paused`?t.pausedText??Lr.paused:e===`resuming`?t.resumingText??Lr.resuming:Lr[e];function tt(e,t,n,r){if(!ge()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(rt(e,ht,n),nt(e,n,r)),!(e.hasAttribute(Ow)||e.hasAttribute(kw))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let it=P_({config:r,showClose:B()}),{wrapper:at,panel:W,pillRoot:st}=it.shell,ct=it.panelElements,{container:G,body:K,messagesWrapper:q,starterSuggestions:lt,transcriptSuggestions:ut,suggestions:dt,textarea:J,sendButton:Y,composerForm:ht,statusText:gt,welcomeHost:_t,welcomeIconHolder:vt,greetingHost:bt,introKicker:xt,introTitle:St,introSubtitle:Ct,closeButton:wt,iconHolder:Tt,headerTitle:Et,headerSubtitle:Dt,header:Ot,footer:kt,actionsRow:At}=ct,jt=ct.leftActions,Mt=ct.rightActions,Nt=ct.sendButtonWrapper,Pt=ct.setSendButtonMode,X=ct.micButton,Lt=ct.micButtonWrapper,Rt=ct.attachmentButton,zt=ct.attachmentButtonWrapper,Bt=ct.attachmentInput,Vt=ct.attachmentPreviewsContainer;G.classList.add(`persona-relative`),K.classList.add(`persona-relative`);let Ht=()=>Ce.label??``,Wt=()=>Ce.iconName??`arrow-down`,Gt=()=>Ce.enabled!==!1,Kt=()=>we.mode??`anchor-top`,qt=()=>Kt()===`follow`||Kt()===`anchor-top`&&xa,Jt=()=>we.anchorTopOffset??16,Yt=()=>we.restorePosition??`bottom`,Xt=()=>we.pauseOnInteraction===!0,Zt=()=>we.showActivityWhilePinned!==!1,Qt=()=>we.announce===!0,en=()=>we.scrollbar??`on-scroll`,tn=z(`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`);tn.type=`button`,tn.style.display=`none`,tn.setAttribute(`data-persona-scroll-to-bottom`,`true`);let nn=z(`span`,`persona-flex persona-items-center`),rn=z(`span`,``),an=z(`span`,``);an.setAttribute(`data-persona-scroll-to-bottom-count`,``),an.style.display=`none`,tn.append(nn,rn,an),G.appendChild(tn);let on=z(`div`,`persona-stream-anchor-spacer`);on.setAttribute(`aria-hidden`,`true`),on.setAttribute(`data-persona-anchor-spacer`,``),on.style.flexShrink=`0`,on.style.pointerEvents=`none`,on.style.height=`0px`,on.style.display=`none`,K.appendChild(on);let cn=z(`div`,`persona-sr-only`);cn.setAttribute(`aria-live`,`polite`),cn.setAttribute(`aria-atomic`,`true`),cn.setAttribute(`role`,`status`),cn.setAttribute(`data-persona-live-region`,``),Object.assign(cn.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`}),G.appendChild(cn);let ln=null,dn=null,fn=e=>{Qt()&&e&&(dn=e,ln===null&&(ln=setTimeout(()=>{ln=null,dn&&Qt()&&(cn.textContent=dn),dn=null},400)))},pn=()=>{let t=e.ownerDocument.defaultView??window;return(r.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(r.launcher?.mobileBreakpoint??640)&&(R||zh(r))||r.launcher?.fullHeight===!0&&!r.launcher.sidebarMode&&!zh(r)},mn=()=>p_(r,pn()),hn=`empty`,gn=0,_n=()=>gn||parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,vn=()=>{let e=kt.style.display===`none`?0:kt.offsetHeight;tn.style.bottom=`${e+_n()+12}px`};vn();let yn=()=>{er||(kt.style.marginBottom=gn>0?`${gn}px`:``)},bn=()=>{let t=Gp(r,ge()),n=mn();e.setAttribute(`data-persona-welcome-fullscreen`,String(pn())),e.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),e.setAttribute(`data-persona-welcome-layout-explicit`,r.welcome?.layout??``),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let i=kt.style.display===`none`?0:kt.offsetHeight,a=n.anchor===`center`&&hn===`empty`?Kp(n.anchorComposerTop)??Kp(`44%`):null,o=a!==null&&n.layout===`centered`&&r.welcome?.anchor===void 0&&r.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(K):null,c=parseFloat(e.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(t===`overlay`?c+l:0)),d=o?K.getBoundingClientRect().top-G.getBoundingClientRect().top:0,f=!o||_t.hidden?0:(_t.querySelector(`[data-persona-welcome-plugin]`)??_t).offsetHeight,p=a===null||ge()?0:o?Math.max(0,Math.round((G.clientHeight-d-f-u-i)/2)):qp({columnHeight:G.clientHeight,footerHeight:i,fraction:a});e.style.setProperty(`--persona-composer-overlay-height`,`${i}px`),e.style.setProperty(`--persona-composer-lift`,`${t===`overlay`?p:0}px`),gn=t===`block`?p:0,yn(),vn()},xn=()=>{let e=!!Ht();tn.setAttribute(`aria-label`,Ht()||`Jump to latest`),tn.title=Ht(),tn.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),nn.innerHTML=``;let t=U(Wt(),`14px`,`currentColor`,2);t?(nn.appendChild(t),nn.style.display=``):nn.style.display=`none`,rn.textContent=Ht(),rn.style.display=e?``:`none`};xn();let Sn=null,Cn=null,Z=Gd();Z.subscribe(e=>{try{G.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let wn=()=>{Z.setText(J?.value??``)},Tn=()=>{Z.setMentionRefs(Cn?.getMentionRefs()??[])},En=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),Dn=e=>{let t=Object.freeze(e.map(En));Z.setAttachments(t);try{r.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}Ts()};Z.setSelectedModelId(r.composer?.selectedModelId);let On=()=>r.composer?.modes??[],kn=()=>Af(On(),r.composer?.modeGroups);{let e=Nf(r.composer?.defaultActiveModeIds??[],On());e.length&&Z.setActiveModeIds(e)}function An(e){if(Z.getState().selectedModelId!==e){Z.setSelectedModelId(e),Nn?.repaint();try{r.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function jn(e){Z.setActiveModeIds(e),Fn?.render(e,kn()),In.forEach(e=>e.repaint()),fr?.resolve(),ec(),Sr()}function Mn(e){jn(Mf(Z.getState().activeModeIds,e,On(),r.composer?.modeGroups))}let Nn=null,Pn=null,Fn=null,In=/* @__PURE__ */ new Map,Ln=null;function Rn(e){Z.setQuote(e),Ln?.render(Z.getState().quote),Sr(),Qa()}let zn=!1;function Bn(){let e=r.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?r.clientToken?`interrupt`:(!zn&&r.debug===!0&&(zn=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let Vn=null;function Un(e){Z.setPendingSubmission(e),Vn?.render(Z.getState().pendingSubmission),Sr()}let Gn=e=>{let t=In.get(e);if(t)return t;let n=If({groupId:e,getGroup:()=>r.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>On().filter(t=>t.groupId===e),getActiveIds:()=>Z.getState().activeModeIds,onSelect:e=>Mn(e)});return In.set(e,n),n},Kn=()=>{let e=[],t=Z.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(On().forEach((i,a)=>{if(Of(i.groupId,r.composer?.modeGroups)){let t=i.groupId;if(n.has(t))return;n.add(t);let o=Gn(t);o.action.order=Ef(a),o.action.label=r.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:Tf(i.id),kind:`button`,placement:`start`,order:Ef(a),presentation:i.presentation??`auto`,label:i.label,shortLabel:i.shortLabel,iconName:i.iconName,pressed:t.includes(i.id),onSelect:()=>Mn(i.id)})}),r.composer?.models?.length&&!d.some(e=>e.renderComposer)){let t=r.composer?.modelPicker?.presentation??`native`;(!Nn||Pn!==t)&&(Pn=t,Nn=Cf({getModels:()=>r.composer?.models??[],getSelectedModelId:()=>Z.getState().selectedModelId,onSelect:e=>An(e),presentation:t,getSuffix:()=>r.composer?.modelPicker?.suffix})),e.push(Nn.action)}return e},qn=null,Jn=d.find(e=>e.renderHeader);if(Jn?.renderHeader){let e=Jn.renderHeader({config:r,defaultRenderer:()=>{let e=ag({config:r,showClose:B()});return og(G,e,r),e.header},onClose:()=>ys(!1,`user`)});if(e){let t=Ot;t&&(t.replaceWith(e),Ot=e,it.header.element=e)}}let Yn=()=>{Ne&&(K.style.display=`none`,kt.parentNode?.insertBefore(Ne.element,kt),Ne.update())},Xn=()=>{if(!ke){Be();return}if(Fe=!0,Ne?Yn():by().then(e=>{!Ne&&Fe&&ke&&(Ne=e.createEventStreamView({buffer:ke,getFullHistory:()=>ke.getAllFromStore(),onClose:()=>Zn(),config:r,plugins:d,getThroughput:()=>Ae?.getMetric()??{status:`idle`},renderIconByName:U}),Yn())}).catch(()=>{Zn()}),Qn){Qn.style.boxShadow=`inset 0 0 0 1.5px ${ng.actionIconColor}`;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Qn.classList.add(e))}let e=()=>{if(!Fe)return;let t=Date.now();t-Le>=200&&(Ne?.update(),Le=t),Ie=requestAnimationFrame(e)};Le=0,Ie=requestAnimationFrame(e),mo(),k.emit(`eventStream:opened`,{timestamp:Date.now()})},Zn=()=>{if(Fe){if(Fe=!1,Ne&&Ne.element.remove(),K.style.display=``,Qn){Qn.style.boxShadow=``;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Qn.classList.remove(e))}Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),mo(),k.emit(`eventStream:closed`,{timestamp:Date.now()})}},Qn=null;if(Se){let e=r.features?.eventStream?.classNames,t=`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`+(e?.toggleButton?` `+e.toggleButton:``);Qn=z(`button`,t),Qn.style.width=`28px`,Qn.style.height=`28px`,Qn.style.color=ng.actionIconColor,Qn.type=`button`,Qn.setAttribute(`aria-label`,`Event Stream`),Qn.title=`Event Stream`;let n=h(u.Activity,`18px`,`currentColor`,1.5);n&&Qn.appendChild(n);let i=ct.clearChatButtonWrapper,a=ct.closeButtonWrapper,o=i||a;o&&o.parentNode===Ot?Ot.insertBefore(Qn,o):Ot.appendChild(Qn),Qn.addEventListener(`click`,()=>{Fe?Zn():Xn()})}let $n=e=>{let t=r.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=z(`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 t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=z(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??Ia).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},er=!1,tr=e=>{let t=d.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=r.composer,i=m?$.isStreaming():!1;return t.renderComposer({config:r,defaultRenderer:e,requestRender:()=>Ku(),storage:g(t.id),onSubmit:e=>{$&&!$.isStreaming()&&Cl(e.trim(),{consumeDraft:!1})},streaming:i,disabled:i,openAttachmentPicker:()=>{xs()||Bt?.click()},models:n?.models,selectedModelId:Z.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>An(e),onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{qn?.()}:void 0})},nr=tr(()=>bg({config:r}).footer);nr&&(it.replaceComposer(nr),kt=it.composer.footer,er=!0);let rr=null,ir=e=>{ht=e.form,J=e.input,Nt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(Y=e.sendButton),e.micButton&&(X=e.micButton,Lt=e.micButton.parentElement),e.found.status&&(gt=e.found.status),e.found.suggestions&&(dt=e.found.suggestions),e.attachmentButton&&(Rt=e.attachmentButton,zt=e.attachmentButton.parentElement),Bt=e.attachmentInput??null,Vt=e.attachmentPreviews??null,e.found.actionsRow&&(At=e.found.actionsRow),jt=e.found.actionsStart,Mt=e.found.actionsEnd};function ar(){let e=J;if(!e)return;let t=r.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;Go(e,t),n&&e.setAttribute(`aria-label`,n),Wo(e,{submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:Bo(e)}),zo(e,Ro(r.composer?.maxLines,ge()?5:3))}let or=e=>{rr=Jd(e,{debug:r.debug===!0}),rr&&ir(rr),ar()};$n(kt),or(kt),wn();let sr=Wp(r,ge());sr&&(q.style.maxWidth=sr,q.style.marginLeft=`auto`,q.style.marginRight=`auto`,q.style.width=`100%`,bt.style.maxWidth=sr,bt.style.marginLeft=`auto`,bt.style.marginRight=`auto`,bt.style.width=`100%`,lt.style.maxWidth=sr,ut.style.maxWidth=sr,ut.style.marginLeft=`auto`,ut.style.marginRight=`auto`,ut.style.width=`100%`);let cr=()=>{let e=Wp(r,ge());if(e&&!ge())for(let t of[ht,dt,Vt,gt])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};cr();let lr=()=>{r.attachments?.enabled&&Bt&&Vt&&(Sn?Sn.remountPreviews(Vt):(Sn=Hd.fromConfig(r.attachments,Dn),Sn.setPreviewsContainer(Vt)),rr?.addListener(Bt,`change`,e=>{let t=e.target;Sn?.handleFileSelect(t.files),t.value=``}),G.querySelector(`.persona-attachment-drop-overlay`)||G.appendChild(Rw(r.attachments.dropOverlay)))};lr();let ur=()=>Cn?.prefetch(),dr=()=>{if(!r.contextMentions?.enabled||!J)return;let e=ol();if(!e){let e=J;al().then(()=>{!Cn&&J===e&&e.isConnected&&(dr(),fr?.resolve())},()=>{});return}let t=rr?.header??null,n=t?ms(t):void 0;if(Cn=e.createContextMentionOrchestrator({deps:{loadContextMentions:ac,loadContextMentionsInline:Kc,renderLucideIcon:U,createMentionButton:as},config:r,textarea:J,anchor:ht??J,getMessages:()=>$.getMessages(),liveRegionHost:G,chipRow:n}),Cn&&!n){let e=J;e.parentElement?.insertBefore(Cn.contextRow,e)}};dr();let fr=null,pr={getState:()=>Z.getState(),getValue:()=>J?.value??``,setValue:e=>{J&&(J.value=e,J.dispatchEvent(new Event(`input`,{bubbles:!0})),wn())},submit:()=>{qs(rr?.form??null)},openAttachmentPicker:()=>{xs()||Bt?.click()},toggleVoice:()=>{qn?.()},requestRender:()=>fr?.resolve()},mr=()=>{let e=[];return(Cn?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:tf.mention+n,element:t,managed:!0})}),zt&&e.push({id:`core:attachment`,placement:`start`,order:tf.attachment,element:zt}),Lt&&e.push({id:`core:mic`,placement:`end`,order:tf.mic,element:Lt}),Nt&&e.push({id:`core:send`,placement:`end`,order:tf.send,element:Nt}),e},hr=()=>{fr?.destroy(),fr=bf({getBindings:()=>rr,collect:()=>({builtIns:mr(),configActions:[...Kn(),...r.composer?.actions??[]],plugins:d,contributionContext:{config:r,getState:()=>Z.getState(),requestRender:()=>fr?.resolve()},debug:r.debug===!0}),actionContext:pr,getState:()=>Z.getState(),getOverflow:()=>r.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),fr.resolve()};hr();let vr=()=>{if(Fn?.destroy(),Fn=null,!kn().length)return;let e=rr?.header;e&&(Fn=wf({row:ms(e),onRemove:e=>Mn(e),initialIds:Z.getState().activeModeIds}),Fn.render(Z.getState().activeModeIds,kn()))};vr();let yr=()=>{Ln?.destroy(),Ln=null,Vn?.destroy(),Vn=null;let e=rr?.header;e&&(Ln=Lf({onDismiss:()=>Rn(void 0)}),e.appendChild(Ln.element),Ln.render(Z.getState().quote),Bn()===`defer-one`&&(Vn=Rf({onEdit:()=>fl(),onRemove:()=>Un(void 0)}),e.appendChild(Vn.element),Vn.render(Z.getState().pendingSubmission)))};yr();let br=Wf(),xr=()=>{let e=rr?.header?.querySelector(hs);if(e)return e.childElementCount>0;let t=Z.getState();return t.mentionRefs.length>0||Nf(t.activeModeIds,kn()).length>0};function Sr(){let e=Z.getState(),t=br.observe(Gf(J),e.text);kt.toggleAttribute(`data-persona-composer-compact`,Uf({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:xr(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function Cr(){r.composer?.layout===`single-row`&&!ge()?kt.setAttribute(`data-persona-composer-layout`,`single-row`):kt.removeAttribute(`data-persona-composer-layout`)}Cr(),Z.subscribe(()=>{fr?.sync(),Ts(),Es(),Sr(),Qa()}),Es();let wr=!1,Tr=e=>{if(wr||r.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(wr=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.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 e=r.layout?.slots??{};Tr(e);let t=e=>{switch(e){case`body-top`:return K.querySelector(`[data-persona-intro-card]`);case`messages`:return q;case`footer-top`:return dt;case`composer`:return ht;case`footer-bottom`:return gt;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)Ot.insertBefore(t,Ot.firstChild);else if(e===`header-right`)Ot.appendChild(t);else{let e=Ot.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):Ot.appendChild(t)}break;case`body-top`:{let e=K.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):K.insertBefore(t,K.firstChild);break}case`body-bottom`:K.appendChild(t);break;case`footer-top`:dt.replaceWith(t);break;case`footer-bottom`:gt.replaceWith(t)}};for(let[i,a]of Object.entries(e))if(a)try{let e=a({config:r,defaultContent:()=>t(i)});e&&n(i,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${i}":`,e)}})(),q.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),J_(n))});let Dr=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let c=n.getAttribute(`data-message-id`);if(!c)return;Ea(),ho();let l=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){o.manual(c);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&o.manual(e.dataset.messageId)}if(l===`reasoning`)a.has(c)?a.delete(c):a.add(c),H_(c,n,a);else if(l===`tool`)i.has(c)?i.delete(c):i.add(c),$_(c,n,i,r);else if(l===`approval`&&v){let e=((r.approval===!1?void 0:r.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=s.get(c)??e;s.set(c,!t),v.updateApprovalDetailsUI(c,n,r,s)}ta.delete(c)};q.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),Dr(e))}),q.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&Dr(e)}),q.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),Dr(e))}),q.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=q.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=cm(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let kr=/* @__PURE__ */ new Map,Ar=null,Mr=`idle`,Nr={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},Pr=(e,t)=>{let{icon:n,label:r}=Nr[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=U(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},Fr=()=>{q.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;Pr(e,t&&t===Ar?Mr:`idle`)})};q.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let i=n.getAttribute(`data-actions-for`);if(!i)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=$.getMessages().find(e=>e.id===i);if(e&&Ye.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=h(u.Check,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=h(u.Copy,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),Ye.onCopy(e)}}else if(a===`read-aloud`)$.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(kr.get(i)??null)===a,r=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){kr.delete(i),t.classList.remove(`persona-message-action-active`);let e=U(r,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=U(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}kr.set(i,a),t.classList.add(`persona-message-action-active`);let s=U(r,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=$.getMessages().find(e=>e.id===i);c&&Ye.onFeedback&&Ye.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)Ir?.regenerate(i);else if(a===`edit`)Ir?.edit(i);else if(a===`quote`)Ir?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=r.messageActions?.custom?.find(t=>t.id===e),n=$.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Ir=null;q.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=$.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),o.approval.toolType===`webmcp`?$.resolveWebMcpApproval(r,a):$.resolveApproval(o.approval,a)});let Rr=null,zr=!1,Br=null,Vr=()=>{},Hr=`none`,Ur=null,Wr={artifacts:[],selectedId:null},Gr=!1,Kr=!1,qr=!1,Jr=!1,Yr=()=>Jr||Wr.artifacts.some(e=>$t(r.features?.artifacts,e)===`panel`),Xr=()=>Wr.artifacts.length>0&&!Gr&&Yr(),Zr={current:null},Qr=(e,t)=>{let n=$.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=$.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};q.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||r.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:i,title:a,file:o}=Qr(t,n);if(!i)return;let s=yx();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:i,file:o}))}),q.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let i=t.closest(`[data-artifact-inline]`),a=i?null:t.closest(`[data-open-artifact]`),o=i?i.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(i?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Qr(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),q.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=$.getArtifactById(n),i=yx();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Qr(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=h(u.Check,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=h(u.Copy,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),q.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Gr=!1,Jr=!0,Kr=!0,qr=!0,$.selectArtifact(n),xi())}),q.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let i=n.getAttribute(`data-open-artifact`);i&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:i})!==!0&&(e.preventDefault(),e.stopPropagation(),Gr=!1,Jr=!0,$.selectArtifact(i),xi())}),q.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let $r=ct.composerOverlay,ei=e=>{al().catch(()=>{}),gr(e,r,$r)},ni=null,ri={mount:e,overlay:$r,sessionRef:Zr,config:()=>r},ii=!1,ai=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{ni??=n.createAskUserSheetHandlers(ri),ni[e](t)},a=ol();a?i(a):ii||(ii=!0,al().then(e=>{ii=!1,r.isConnected&&i(e)},()=>{ii=!1}))};$r.addEventListener(`click`,ai(`click`)),$r.addEventListener(`keydown`,ai(`keydown`));let oi=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=$r.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,oi);let si=null,ci=null,li=null,ui=null,di=()=>{},fi=!1,pi=``,mi=``;function hi(){ui?.(),ui=null}let gi=()=>{let e=Ac?.railShell?Ac.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},_i=()=>{if(!si||!ci)return;let t=e.classList.contains(`persona-artifact-welded-split`),n=e.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!t||e.classList.contains(`persona-artifact-narrow-host`)||r){ci.style.removeProperty(`position`),ci.style.removeProperty(`left`),ci.style.removeProperty(`top`),ci.style.removeProperty(`bottom`),ci.style.removeProperty(`width`),ci.style.removeProperty(`z-index`);return}let i=si.firstElementChild;if(!i||i===ci)return;ci.style.position=`absolute`,ci.style.top=`0`,ci.style.bottom=`0`,ci.style.width=`10px`,ci.style.zIndex=`5`;let a=rS(si,n),o=i.offsetWidth+a/2-5;ci.style.left=`${Math.max(0,o)}px`},vi=()=>{},yi=()=>{let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;return!n||t.innerWidth>i?!1:R||zh(r)},bi=()=>!xx(r)||!Xr()||e.classList.contains(`persona-artifact-narrow-host`)||yi()||(e.ownerDocument.defaultView??window).innerWidth<641?`none`:Ex(r)?`detached`:`welded`,xi=()=>{if(!Rr||!xx(r))return;Dx(e,r),Ox(e,r),vi();let t=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=W.getBoundingClientRect().width||0;e.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=t);let i=Xr();Rr.setVisible(i),Rr.update(Wr),Gr?(Rr.setMobileOpen(!1),Rr.element.classList.add(`persona-hidden`),Rr.backdrop?.classList.add(`persona-hidden`),Kr=!1,qr=!1):Wr.artifacts.length>0&&Yr()?(Rr.element.classList.remove(`persona-hidden`),Rr.setMobileOpen(!0)):(Rr.setMobileOpen(!1),Rr.element.classList.add(`persona-hidden`),Rr.backdrop?.classList.add(`persona-hidden`),Kr=!1,qr=!1);let a=r.features?.artifacts?.layout?.showExpandToggle===!0;if(Rr.setExpandToggleVisible(a),Rr.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),Rr.setRefreshButtonVisible(typeof r.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),Rr.setCustomActions(r.features?.artifacts?.toolbarActions??[]),Rr.setTabFade(r.features?.artifacts?.layout?.tabFade),Rr.setRenderTabBar(r.features?.artifacts?.renderTabBar),!a&&!qr&&(Kr=!1),Kr!==fi){let e=Rr.element;Kr?(pi=e.style.width,mi=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(pi&&(e.style.width=pi),mi&&(e.style.maxWidth=mi),pi=``,mi=``),fi=Kr}e.classList.toggle(`persona-artifact-expanded`,Kr),Rr.setExpanded(Kr);let o=bi();o!==Hr&&(Hr=o,Vr()),di()};if(xx(r)){W.style.position=`relative`;let t=z(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=z(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);t.appendChild(G),si=n,n.appendChild(t),W.appendChild(n);let i=e=>{zr||Rr||(Rr=e.createArtifactPane(r,{onSelect:e=>Zr.current?.selectArtifact(e),onDismiss:()=>{Gr=!0,xi()},onToggleExpand:()=>{let e=!Kr,t=Wr.selectedId??Wr.artifacts[Wr.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(Kr=e,e||(qr=!1),xi())}}),Rr.element.classList.add(`persona-hidden`),n.appendChild(Rr.element),Rr.backdrop&&W.appendChild(Rr.backdrop),di(),xi())},a=yx();a?i(a):(bx(()=>{let e=yx();e&&i(e)}),vx().catch(()=>{})),di=()=>{if(si&&Rr){if(r.features?.artifacts?.layout?.resizable!==!0)li?.(),li=null,hi(),ci&&=(ci.remove(),null),Rr.element.style.removeProperty(`width`),Rr.element.style.removeProperty(`maxWidth`);else{if(!ci){let t=z(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,`Resize artifacts panel`),t.tabIndex=0;let n=e.ownerDocument,i=n.defaultView??window,a=a=>{if(!Rr||a.button!==0||e.classList.contains(`persona-artifact-narrow-host`)||e.classList.contains(`persona-artifact-expanded`)||i.innerWidth<=640)return;a.preventDefault(),hi();let o=a.clientX,s=Rr.element.getBoundingClientRect().width,c=r.features?.artifacts?.layout,l=n=>{let r=si.getBoundingClientRect().width,a=e.classList.contains(`persona-artifact-welded-split`),l=rS(si,i),u=a?0:t.getBoundingClientRect().width||6,d=iS(s-(n.clientX-o),r,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,gi());Rr.element.style.width=`${d}px`,Rr.element.style.maxWidth=`none`,_i()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),ui=null;try{t.releasePointerCapture(a.pointerId)}catch{}};ui=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener(`pointerdown`,a),ci=t,si.insertBefore(t,Rr.element),li=()=>{t.removeEventListener(`pointerdown`,a)}}if(ci){let e=Xr();ci.classList.toggle(`persona-hidden`,!e),_i()}}}},vi=()=>{if(!R||!Rr||(r.launcher?.sidebarMode??!1)||zh(r)&&Vh(r).reveal===`emerge`)return;let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;if(n&&t.innerWidth<=i||!kx(r,R))return;let a=__(r).width,o=r.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Xr()?(W.style.width=o,W.style.maxWidth=o):(W.style.width=a,W.style.maxWidth=a)},typeof ResizeObserver<`u`&&(Br=new ResizeObserver(()=>{xi()}),Br.observe(W))}else W.appendChild(G);ge()&&st&&(ct.peekBanner&&st.appendChild(ct.peekBanner),st.appendChild(kt)),e.appendChild(at),st&&e.appendChild(st);let Si=()=>{let t=yi()||ge()&&r.launcher?.composerBar?.expandedSize===`fullscreen`||r.launcher?.fullHeight===!0&&!r.launcher?.sidebarMode&&!zh(r);if(q.style.gap=t?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,q.style.setProperty(`--persona-transcript-gap`,q.style.gap),ge()){W.style.width=`100%`,W.style.maxWidth=`100%`;let e=r.launcher?.composerBar??{},t=at.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){G.style.background=``,G.style.border=``,G.style.borderRadius=``,G.style.overflow=``,G.style.boxShadow=``;return}let i=r.theme?.components?.panel,a=Bp(r),o=(e,t)=>e==null||e===``?t:mp(a,e)??e;G.style.background=`var(--persona-surface, #ffffff)`,G.style.border=o(i?.border,`1px solid var(--persona-border)`),G.style.borderRadius=o(i?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),G.style.boxShadow=o(i?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),G.style.overflow=`hidden`;return}let n=zh(r),i=r.launcher?.sidebarMode??!1,a=n||i||(r.launcher?.fullHeight??!1),o=r.launcher?.enabled===!1,s=r.launcher?.detachedPanel===!0,c=r.theme?.components?.panel,l=r.darkTheme?.components?.panel,u=Lp(r)===`dark`?_(c??{},l??{}):c,d=Bp(r),f=(e,t)=>e==null||e===``?t:mp(d,e)??e,p=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,h=r.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,v=m&&g&&R,y=n&&m&&g,b=r.launcher?.position??`bottom-left`,x=b===`bottom-left`||b===`top-left`,S=r.launcher?.zIndex??1e5,C=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,w=u?.modes?.floating,T=f(w?.border??u?.border,C(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),E=f(w?.shadow??u?.shadow,C(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),D=f(w?.borderRadius??u?.borderRadius,C(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),O=s&&!v&&!y,k=v||y?`mobile`:O?`floating`:n?`docked`:i?`sidebar`:o?`inline`:`floating`,A=u?.modes?.[k];O?e.setAttribute(`data-persona-panel-detached`,`true`):e.removeAttribute(`data-persona-panel-detached`);let j=O?T:i||v?`none`:T,M=O?E:v?`none`:i?x?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:E;n&&!v&&!O&&(M=`none`,j=`none`);let ee=O?D:i||v?`0`:D,P=f(A?.border??u?.border,C(k,`border`,j)),F=f(A?.shadow??u?.shadow,C(k,`shadow`,M)),te=f(A?.borderRadius??u?.borderRadius,C(k,`borderRadius`,ee)),ne=bi(),I=ne===`detached`,re=ne===`welded`;e.classList.toggle(`persona-artifact-detached-split`,I),e.classList.toggle(`persona-artifact-welded-split`,re);let ie=`var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))`,ae=(r.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&xx(r)&&Ex(r)&&o&&!n;e.classList.toggle(`persona-artifact-chat-flush`,ae);let oe=I||ae?`none`:F,se=I?T:re?`none`:P,ce=I?D:te;ae&&(se=`none`,ce=`0`);let le=A?.borderRadius!=null&&A.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,L=ae&&!le?`0`:te,ue=K.scrollTop;e.style.cssText=``,at.style.cssText=``,W.style.cssText=``,G.style.cssText=``,K.style.cssText=``,er||(kt.style.cssText=``),Fe&&(K.style.display=`none`),(a||o)&&(e.style.minWidth=`0`);let de=()=>{ue<=0||(K.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(K.scrollTop===ue)return;let e=K.scrollHeight-K.clientHeight;e<=0||(K.scrollTop=Math.min(ue,e))})};if(v){at.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`),at.style.cssText=`
|
|
1165
|
+
`,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function Lw(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}A(),pt(),Ft(),zt(),At(),po(),ws(),rc(),ts(),mc(),tl(),ms(),Ha(),P(),W(),ee(),H(),Wo(),ve(),gm(),Fm(),Wr(),oh(),fs(),Tr(),Ir(),Tn(),E(),an(),Ae(),_e(),to(),Ny();const Rw=`persona-chat-history`,zw=`data-persona-composer-reason`,Bw=`data-persona-composer-notice`,Vw={"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 Hw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Vw[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function Uw(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 Ww(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 Gw(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const Kw=e=>!e||typeof e!=`object`?{}:{...e},qw=e=>e.filter(e=>!eo(e)).map(e=>({...e,streaming:!1})),Jw=(e,t,n)=>{let r=e?.markdown?Nt(e.markdown):null,i=Rt(e?.sanitize);e?.postprocessMessage&&i&&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 a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=kt()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?Kt(o):o,t=r(e);l=i&&c?i(t):t}else l=Pt(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),Pt(e.text??``)}}};function Yw(e){let t=B(`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`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=U(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=B(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const Xw=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Zw=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Xw(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Qw=(e,t,n)=>{if(e==null)throw 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 r=ye(t),i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=ct((e,t)=>{na.delete(e);let n=Array.from(J.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?lv(e,n,i,r):Q_(e,n,a))}),s=/* @__PURE__ */ new Map,c=()=>{To({delayMs:r.tooltip?.delayMs??200,skipDelayMs:r.tooltip?.skipDelayMs??300})};c();let l=r.features;r=cS(r);let d=ES.getForInstance(r.plugins),f=hm(e),p=[],m=!1,h=J_(()=>r),g=null,_=null,v=null,y=!1,b=null,S=e=>{g=e,e.initApprovalUi({webMcpToolTitle:x});let t=e.createBuiltInApprovalPlugin(s);_=t.plugin,v=t.teardown},C=()=>{if(g)return g;let e=Vv();return e?(S(e),e):(Bv().then(e=>{y||g||(S(e),b?.())}).catch(()=>{}),null)},w=!1,T=!1,E=null,O=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=TS();i?i.enhanceWithForms(e,t,n,r):wS().then(()=>{w||T||!E||(T=!0,E())}).catch(()=>{})};r.components&&My.registerAll(r.components);let k=jS(),A=r.persistState===!1?null:r.storageAdapter??US(HS(typeof r.persistState==`object`?r.persistState.keyPrefix:void 0)),ee=!!r.clientToken&&typeof r.reconnectStream!=`function`,N={},P=null,te,ne=new Promise(e=>{te=e}),re=()=>{},F=new Promise(e=>{re=e}),ie,ae=!1,oe=e=>{if(r.onStateLoaded)try{let t=r.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(ae=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(A?.load)try{let e=A.load();if(e&&typeof e.then==`function`)P=e.then(e=>oe(e??{messages:[],metadata:{}}));else{let t=oe(e??{messages:[],metadata:{}});t.metadata&&(N=Kw(t.metadata)),t.messages?.length&&(r={...r,initialMessages:t.messages}),t.artifacts?.length&&(r={...r,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),ie=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(r.onStateLoaded)try{let e=oe({messages:[],metadata:{}});e.messages?.length&&(r={...r,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}P||te();let se=()=>N,ce=e=>{N=e({...N})??{},Ja()},le=r.actionParsers&&r.actionParsers.length?r.actionParsers:[PS],ue=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[IS.message,IS.messageAndClick],de=RS({parsers:le,handlers:ue,getSessionMetadata:se,updateSessionMetadata:ce,emit:k.emit,documentRef:typeof document<`u`?document:null});de.syncFromMetadata();let I=r.launcher?.enabled??!0,fe=r.launcher?.autoExpand??!1,me=r.autoFocusInput??!1,he=fe,ge=I,_e=r.layout?.header?.layout,ve=!1,L=()=>Xh(r),R=()=>I||L(),z=L()?!1:!I||fe,be=!1,xe=null,Se=()=>{be=!0,xe&&clearTimeout(xe),xe=setTimeout(()=>{be&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},Ce=Jw(r,de,Se),we=r.features?.showReasoning??!0,Te=r.features?.showToolCalls??!0,Ee=r.features?.showEventStreamToggle??!1,De=r.features?.scrollToBottom??{},Oe=r.features?.scrollBehavior??{},ke=()=>(typeof r.persistState==`object`?r.persistState?.keyPrefix:void 0)??`persona-`,Ae=`${ke()}event-stream`,je=null,V=r.features?.eventStream?.maxEvents??2e3,Me=null,H=null,Ne=null,Pe=!1,Fe=null,Ie=!1,Le=null,Re=0,ze=(e,t)=>{Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Be=(e,t)=>{H?.processEvent(e,t),Me?ze(e,t):Ne&&(Ne.length>=V&&Ne.shift(),Ne.push({type:e,payload:t}))},Ve=()=>{!Me&&Ee&&(Ne??=[],Ay().then(e=>{if(Pe||Me||!Ee)return;je=new e.EventStreamStore(Ae),Me=new e.EventStreamBuffer(V,je),H??=new e.ThroughputTracker,je.open().then(()=>Me?.restore()).catch(e=>{r.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Ne??[];Ne=null;for(let e of t)H?.processEvent(e.type,e.payload),ze(e.type,e.payload)}).catch(()=>{}))};Ee&&Ve();let He=!1,Ue=null,We=()=>{},Ge=()=>{},Ke=()=>{},qe=()=>{},Je=()=>{},Ye=()=>Ie||He&&Ue===`panel`,Ze={onCopy:e=>{k.emit(`message:copy`,e),$?.isClientTokenMode()&&$.submitMessageFeedback(e.id,`copy`).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),r.messageActions?.onCopy?.(e)},onFeedback:e=>{k.emit(`message:feedback`,e),$?.isClientTokenMode()&&$.submitMessageFeedback(e.messageId,e.type).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),r.messageActions?.onFeedback?.(e)}};r.statusIndicator;let Qe=(e,t=r.statusIndicator??{})=>e===`idle`?t.idleText??Vr.idle:e===`connecting`?t.connectingText??Vr.connecting:e===`connected`?t.connectedText??Vr.connected:e===`error`?t.errorText??Vr.error:e===`paused`?t.pausedText??Vr.paused:e===`resuming`?t.resumingText??Vr.resuming:Vr[e];function $e(e,t,n,r){if(!L()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(ft(e,ut,n),dt(e,n,r)),!(e.hasAttribute(zw)||e.hasAttribute(Bw))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let et=W_({config:r,showClose:R()}),{wrapper:W,panel:G,pillRoot:tt}=et.shell,nt=et.panelElements,{container:K,body:q,messagesWrapper:J,starterSuggestions:rt,transcriptSuggestions:it,suggestions:at,textarea:Y,sendButton:X,composerForm:ut,statusText:pt,welcomeHost:mt,welcomeIconHolder:gt,greetingHost:_t,introKicker:vt,introTitle:yt,introSubtitle:bt,closeButton:xt,iconHolder:St,headerTitle:Ct,headerSubtitle:wt,header:Tt,footer:Ot,actionsRow:At}=nt,jt=nt.leftActions,Mt=nt.rightActions,Nt=nt.sendButtonWrapper,Ft=nt.setSendButtonMode,Z=nt.micButton,It=nt.micButtonWrapper,Lt=nt.attachmentButton,Rt=nt.attachmentButtonWrapper,zt=nt.attachmentInput,Bt=nt.attachmentPreviewsContainer;K.classList.add(`persona-relative`),q.classList.add(`persona-relative`);let Vt=()=>De.label??``,Ht=()=>De.iconName??`arrow-down`,Ut=()=>De.enabled!==!1,Wt=()=>Oe.mode??`anchor-top`,Gt=()=>Wt()===`follow`||Wt()===`anchor-top`&&Sa,Kt=()=>Oe.anchorTopOffset??16,qt=()=>Oe.restorePosition??`bottom`,Jt=()=>Oe.pauseOnInteraction===!0,Xt=()=>Oe.showActivityWhilePinned!==!1,Qt=()=>Oe.announce===!0,$t=()=>Oe.scrollbar??`on-scroll`,en=B(`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`);en.type=`button`,en.style.display=`none`,en.setAttribute(`data-persona-scroll-to-bottom`,`true`);let tn=B(`span`,`persona-flex persona-items-center`),rn=B(`span`,``),an=B(`span`,``);an.setAttribute(`data-persona-scroll-to-bottom-count`,``),an.style.display=`none`,en.append(tn,rn,an),K.appendChild(en);let on=B(`div`,`persona-stream-anchor-spacer`);on.setAttribute(`aria-hidden`,`true`),on.setAttribute(`data-persona-anchor-spacer`,``),on.style.flexShrink=`0`,on.style.pointerEvents=`none`,on.style.height=`0px`,on.style.display=`none`,q.appendChild(on);let sn=B(`div`,`persona-sr-only`);sn.setAttribute(`aria-live`,`polite`),sn.setAttribute(`aria-atomic`,`true`),sn.setAttribute(`role`,`status`),sn.setAttribute(`data-persona-live-region`,``),Object.assign(sn.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`}),K.appendChild(sn);let cn=null,ln=null,dn=e=>{Qt()&&e&&(ln=e,cn===null&&(cn=setTimeout(()=>{cn=null,ln&&Qt()&&(sn.textContent=ln),ln=null},400)))},fn=()=>{let t=e.ownerDocument.defaultView??window;return(r.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(r.launcher?.mobileBreakpoint??640)&&(I||Yh(r))||r.launcher?.fullHeight===!0&&!r.launcher.sidebarMode&&!Yh(r)},mn=()=>C_(r,fn()),hn=`empty`,gn=0,_n=()=>gn||parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,vn=()=>{let e=Ot.style.display===`none`?0:Ot.offsetHeight;en.style.bottom=`${e+_n()+12}px`};vn();let yn=()=>{tr||(Ot.style.marginBottom=gn>0?`${gn}px`:``)},bn=()=>{let t=tm(r,L()),n=mn();e.setAttribute(`data-persona-welcome-fullscreen`,String(fn())),e.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),e.setAttribute(`data-persona-welcome-layout-explicit`,r.welcome?.layout??``),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let i=Ot.style.display===`none`?0:Ot.offsetHeight,a=n.anchor===`center`&&hn===`empty`?nm(n.anchorComposerTop)??nm(`44%`):null,o=a!==null&&n.layout===`centered`&&r.welcome?.anchor===void 0&&r.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(q):null,c=parseFloat(e.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(t===`overlay`?c+l:0)),d=o?q.getBoundingClientRect().top-K.getBoundingClientRect().top:0,f=!o||mt.hidden?0:(mt.querySelector(`[data-persona-welcome-plugin]`)??mt).offsetHeight,p=a===null||L()?0:o?Math.max(0,Math.round((K.clientHeight-d-f-u-i)/2)):rm({columnHeight:K.clientHeight,footerHeight:i,fraction:a});e.style.setProperty(`--persona-composer-overlay-height`,`${i}px`),e.style.setProperty(`--persona-composer-lift`,`${t===`overlay`?p:0}px`),gn=t===`block`?p:0,yn(),vn()},xn=()=>{let e=!!Vt();en.setAttribute(`aria-label`,Vt()||`Jump to latest`),en.title=Vt(),en.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),tn.innerHTML=``;let t=U(Ht(),`14px`,`currentColor`,2);t?(tn.appendChild(t),tn.style.display=``):tn.style.display=`none`,rn.textContent=Vt(),rn.style.display=e?``:`none`};xn();let Sn=null,Cn=null,wn=tf();wn.subscribe(e=>{try{K.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let Tn=()=>{wn.setText(Y?.value??``)},En=()=>{wn.setMentionRefs(Cn?.getMentionRefs()??[])},Dn=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),On=e=>{let t=Object.freeze(e.map(Dn));wn.setAttachments(t);try{r.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}Es()};wn.setSelectedModelId(r.composer?.selectedModelId);let kn=()=>r.composer?.modes??[],An=()=>Bf(kn(),r.composer?.modeGroups);{let e=Uf(r.composer?.defaultActiveModeIds??[],kn());e.length&&wn.setActiveModeIds(e)}function jn(e){if(wn.getState().selectedModelId!==e){wn.setSelectedModelId(e),Pn?.repaint();try{r.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function Mn(e){wn.setActiveModeIds(e),In?.render(e,An()),Ln.forEach(e=>e.repaint()),pr?.resolve(),ec(),Cr()}function Nn(e){Mn(Hf(wn.getState().activeModeIds,e,kn(),r.composer?.modeGroups))}let Pn=null,Fn=null,In=null,Ln=/* @__PURE__ */ new Map,Rn=null;function zn(e){wn.setQuote(e),Rn?.render(wn.getState().quote),Cr(),Qa()}let Bn=!1;function Vn(){let e=r.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?r.clientToken?`interrupt`:(!Bn&&r.debug===!0&&(Bn=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let Hn=null;function Un(e){wn.setPendingSubmission(e),Hn?.render(wn.getState().pendingSubmission),Cr()}let Wn=e=>{let t=Ln.get(e);if(t)return t;let n=Kf({groupId:e,getGroup:()=>r.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>kn().filter(t=>t.groupId===e),getActiveIds:()=>wn.getState().activeModeIds,onSelect:e=>Nn(e)});return Ln.set(e,n),n},Gn=()=>{let e=[],t=wn.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(kn().forEach((i,a)=>{if(Rf(i.groupId,r.composer?.modeGroups)){let t=i.groupId;if(n.has(t))return;n.add(t);let o=Wn(t);o.action.order=If(a),o.action.label=r.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:Ff(i.id),kind:`button`,placement:`start`,order:If(a),presentation:i.presentation??`auto`,label:i.label,shortLabel:i.shortLabel,iconName:i.iconName,pressed:t.includes(i.id),onSelect:()=>Nn(i.id)})}),r.composer?.models?.length&&!d.some(e=>e.renderComposer)){let t=r.composer?.modelPicker?.presentation??`native`;(!Pn||Fn!==t)&&(Fn=t,Pn=Nf({getModels:()=>r.composer?.models??[],getSelectedModelId:()=>wn.getState().selectedModelId,onSelect:e=>jn(e),presentation:t,getSuffix:()=>r.composer?.modelPicker?.suffix})),e.push(Pn.action)}return e},qn=null,Yn=d.find(e=>e.renderHeader);if(Yn?.renderHeader){let e=Yn.renderHeader({config:r,defaultRenderer:()=>{let e=hg({config:r,showClose:R()});return gg(K,e,r),e.header},onClose:()=>vs(!1,`user`)});if(e){let t=Tt;t&&(t.replaceWith(e),Tt=e,et.header.element=e)}}let Xn=()=>{Fe&&(q.style.display=`none`,Ot.parentNode?.insertBefore(Fe.element,Ot),Fe.update())},Zn=()=>{if(!Me){Ve();return}if(Ie=!0,Fe?Xn():Ay().then(e=>{!Fe&&Ie&&Me&&(Fe=e.createEventStreamView({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Qn(),config:r,plugins:d,getThroughput:()=>H?.getMetric()??{status:`idle`},renderIconByName:U}),Xn())}).catch(()=>{Qn()}),$n){$n.style.boxShadow=`inset 0 0 0 1.5px ${fg.actionIconColor}`;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&$n.classList.add(e))}let e=()=>{if(!Ie)return;let t=Date.now();t-Re>=200&&(Fe?.update(),Re=t),Le=requestAnimationFrame(e)};Re=0,Le=requestAnimationFrame(e),ho(),k.emit(`eventStream:opened`,{timestamp:Date.now()})},Qn=()=>{if(Ie){if(Ie=!1,Fe&&Fe.element.remove(),q.style.display=``,$n){$n.style.boxShadow=``;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&$n.classList.remove(e))}Le!==null&&(cancelAnimationFrame(Le),Le=null),ho(),k.emit(`eventStream:closed`,{timestamp:Date.now()})}},$n=null;if(Ee){let e=r.features?.eventStream?.classNames,t=`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`+(e?.toggleButton?` `+e.toggleButton:``);$n=B(`button`,t),$n.style.width=`28px`,$n.style.height=`28px`,$n.style.color=fg.actionIconColor,$n.type=`button`,$n.setAttribute(`aria-label`,`Event Stream`),$n.title=`Event Stream`;let n=j(u.Activity,`18px`,`currentColor`,1.5);n&&$n.appendChild(n);let i=nt.clearChatButtonWrapper,a=nt.closeButtonWrapper,o=i||a;o&&o.parentNode===Tt?Tt.insertBefore($n,o):Tt.appendChild($n),$n.addEventListener(`click`,()=>{Ie?Qn():Zn()})}let er=e=>{let t=r.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=B(`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 t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=B(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??Va).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},tr=!1,nr=e=>{let t=d.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=r.composer,i=m?$.isStreaming():!1;return t.renderComposer({config:r,defaultRenderer:e,requestRender:()=>qu(),storage:h(t.id),onSubmit:e=>{$&&!$.isStreaming()&&wl(e.trim(),{consumeDraft:!1})},streaming:i,disabled:i,openAttachmentPicker:()=>{bs()||zt?.click()},models:n?.models,selectedModelId:wn.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>jn(e),onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{qn?.()}:void 0})},rr=nr(()=>Ag({config:r}).footer);rr&&(et.replaceComposer(rr),Ot=et.composer.footer,tr=!0);let ir=null,ar=e=>{ut=e.form,Y=e.input,Nt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(X=e.sendButton),e.micButton&&(Z=e.micButton,It=e.micButton.parentElement),e.found.status&&(pt=e.found.status),e.found.suggestions&&(at=e.found.suggestions),e.attachmentButton&&(Lt=e.attachmentButton,Rt=e.attachmentButton.parentElement),zt=e.attachmentInput??null,Bt=e.attachmentPreviews??null,e.found.actionsRow&&(At=e.found.actionsRow),jt=e.found.actionsStart,Mt=e.found.actionsEnd};function or(){let e=Y;if(!e)return;let t=r.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;$o(e,t),n&&e.setAttribute(`aria-label`,n),Qo(e,{submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:Jo(e)}),qo(e,Ko(r.composer?.maxLines,L()?5:3))}let sr=e=>{ir=af(e,{debug:r.debug===!0}),ir&&ar(ir),or()};er(Ot),sr(Ot),Tn();let cr=em(r,L());cr&&(J.style.maxWidth=cr,J.style.marginLeft=`auto`,J.style.marginRight=`auto`,J.style.width=`100%`,_t.style.maxWidth=cr,_t.style.marginLeft=`auto`,_t.style.marginRight=`auto`,_t.style.width=`100%`,rt.style.maxWidth=cr,it.style.maxWidth=cr,it.style.marginLeft=`auto`,it.style.marginRight=`auto`,it.style.width=`100%`);let lr=()=>{let e=em(r,L());if(e&&!L())for(let t of[ut,at,Bt,pt])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};lr();let ur=()=>{r.attachments?.enabled&&zt&&Bt&&(Sn?Sn.remountPreviews(Bt):(Sn=Qd.fromConfig(r.attachments,On),Sn.setPreviewsContainer(Bt)),ir?.addListener(zt,`change`,e=>{let t=e.target;Sn?.handleFileSelect(t.files),t.value=``}),K.querySelector(`.persona-attachment-drop-overlay`)||K.appendChild(Yw(r.attachments.dropOverlay)))};ur();let dr=()=>Cn?.prefetch(),fr=()=>{if(!r.contextMentions?.enabled||!Y)return;let e=ml();if(!e){let e=Y;pl().then(()=>{!Cn&&Y===e&&e.isConnected&&(fr(),pr?.resolve())},()=>{});return}let t=ir?.header??null,n=t?Ss(t):void 0;if(Cn=e.createContextMentionOrchestrator({deps:{loadContextMentions:pc,loadContextMentionsInline:el,renderLucideIcon:U,createMentionButton:ps},config:r,textarea:Y,anchor:ut??Y,getMessages:()=>$.getMessages(),liveRegionHost:K,chipRow:n}),Cn&&!n){let e=Y;e.parentElement?.insertBefore(Cn.contextRow,e)}};fr();let pr=null,mr={getState:()=>wn.getState(),getValue:()=>Y?.value??``,setValue:e=>{Y&&(Y.value=e,Y.dispatchEvent(new Event(`input`,{bubbles:!0})),Tn())},submit:()=>{tc(ir?.form??null)},openAttachmentPicker:()=>{bs()||zt?.click()},toggleVoice:()=>{qn?.()},requestRender:()=>pr?.resolve()},hr=()=>{let e=[];return(Cn?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:ff.mention+n,element:t,managed:!0})}),Rt&&e.push({id:`core:attachment`,placement:`start`,order:ff.attachment,element:Rt}),It&&e.push({id:`core:mic`,placement:`end`,order:ff.mic,element:It}),Nt&&e.push({id:`core:send`,placement:`end`,order:ff.send,element:Nt}),e},gr=()=>{pr?.destroy(),pr=Af({getBindings:()=>ir,collect:()=>({builtIns:hr(),configActions:[...Gn(),...r.composer?.actions??[]],plugins:d,contributionContext:{config:r,getState:()=>wn.getState(),requestRender:()=>pr?.resolve()},debug:r.debug===!0}),actionContext:mr,getState:()=>wn.getState(),getOverflow:()=>r.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),pr.resolve()};gr();let _r=()=>{if(In?.destroy(),In=null,!An().length)return;let e=ir?.header;e&&(In=Pf({row:Ss(e),onRemove:e=>Nn(e),initialIds:wn.getState().activeModeIds}),In.render(wn.getState().activeModeIds,An()))};_r();let vr=()=>{Rn?.destroy(),Rn=null,Hn?.destroy(),Hn=null;let e=ir?.header;e&&(Rn=qf({onDismiss:()=>zn(void 0)}),e.appendChild(Rn.element),Rn.render(wn.getState().quote),Vn()===`defer-one`&&(Hn=Jf({onEdit:()=>dl(),onRemove:()=>Un(void 0)}),e.appendChild(Hn.element),Hn.render(wn.getState().pendingSubmission)))};vr();let yr=ep(),Sr=()=>{let e=ir?.header?.querySelector(Cs);if(e)return e.childElementCount>0;let t=wn.getState();return t.mentionRefs.length>0||Uf(t.activeModeIds,An()).length>0};function Cr(){let e=wn.getState(),t=yr.observe(tp(Y),e.text);Ot.toggleAttribute(`data-persona-composer-compact`,$f({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:Sr(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function wr(){r.composer?.layout===`single-row`&&!L()?Ot.setAttribute(`data-persona-composer-layout`,`single-row`):Ot.removeAttribute(`data-persona-composer-layout`)}wr(),wn.subscribe(()=>{pr?.sync(),Es(),Ds(),Cr(),Qa()}),Ds();let Tr=!1,Er=e=>{if(Tr||r.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(Tr=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.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 e=r.layout?.slots??{};Er(e);let t=e=>{switch(e){case`body-top`:return q.querySelector(`[data-persona-intro-card]`);case`messages`:return J;case`footer-top`:return at;case`composer`:return ut;case`footer-bottom`:return pt;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)Tt.insertBefore(t,Tt.firstChild);else if(e===`header-right`)Tt.appendChild(t);else{let e=Tt.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):Tt.appendChild(t)}break;case`body-top`:{let e=q.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):q.insertBefore(t,q.firstChild);break}case`body-bottom`:q.appendChild(t);break;case`footer-top`:at.replaceWith(t);break;case`footer-bottom`:pt.replaceWith(t)}};for(let[i,a]of Object.entries(e))if(a)try{let e=a({config:r,defaultContent:()=>t(i)});e&&n(i,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${i}":`,e)}})(),J.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),iv(n))});let Dr=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let c=n.getAttribute(`data-message-id`);if(!c)return;Ea(),go();let l=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){o.manual(c);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&o.manual(e.dataset.messageId)}if(l===`reasoning`)a.has(c)?a.delete(c):a.add(c),Q_(c,n,a);else if(l===`tool`)i.has(c)?i.delete(c):i.add(c),lv(c,n,i,r);else if(l===`approval`&&g){let e=((r.approval===!1?void 0:r.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=s.get(c)??e;s.set(c,!t),g.updateApprovalDetailsUI(c,n,r,s)}na.delete(c)};J.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),Dr(e))}),J.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&Dr(e)}),J.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),Dr(e))}),J.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=J.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=vm(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let Or=/* @__PURE__ */ new Map,kr=null,jr=`idle`,Nr={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},Pr=(e,t)=>{let{icon:n,label:r}=Nr[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=U(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},Ir=()=>{J.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;Pr(e,t&&t===kr?jr:`idle`)})};J.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let i=n.getAttribute(`data-actions-for`);if(!i)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=$.getMessages().find(e=>e.id===i);if(e&&Ze.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=j(u.Check,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=j(u.Copy,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),Ze.onCopy(e)}}else if(a===`read-aloud`)$.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(Or.get(i)??null)===a,r=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){Or.delete(i),t.classList.remove(`persona-message-action-active`);let e=U(r,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=U(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}Or.set(i,a),t.classList.add(`persona-message-action-active`);let s=U(r,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=$.getMessages().find(e=>e.id===i);c&&Ze.onFeedback&&Ze.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)Lr?.regenerate(i);else if(a===`edit`)Lr?.edit(i);else if(a===`quote`)Lr?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=r.messageActions?.custom?.find(t=>t.id===e),n=$.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Lr=null;J.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=$.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),D(o.approval)?$.resolveWebMcpApproval(r,a):$.resolveApproval(o.approval,a)});let Rr=null,zr=!1,Br=null,Hr=()=>{},Ur=`none`,Wr=null,Gr={artifacts:[],selectedId:null},Kr=!1,qr=!1,Jr=!1,Yr=!1,Xr=()=>Yr||Gr.artifacts.some(e=>nn(r.features?.artifacts,e)===`panel`),Zr=()=>Gr.artifacts.length>0&&!Kr&&Xr(),Qr={current:null},$r=(e,t)=>{let n=$.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=$.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};J.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||r.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:i,title:a,file:o}=$r(t,n);if(!i)return;let s=kx();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:i,file:o}))}),J.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let i=t.closest(`[data-artifact-inline]`),a=i?null:t.closest(`[data-open-artifact]`),o=i?i.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(i?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=$r(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),J.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=$.getArtifactById(n),i=kx();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=$r(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=j(u.Check,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=j(u.Copy,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),J.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Kr=!1,Yr=!0,qr=!0,Jr=!0,$.selectArtifact(n),Si())}),J.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let i=n.getAttribute(`data-open-artifact`);i&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:i})!==!0&&(e.preventDefault(),e.stopPropagation(),Kr=!1,Yr=!0,$.selectArtifact(i),Si())}),J.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let ei=nt.composerOverlay,ti=e=>{pl().catch(()=>{}),br(e,r,ei)},ni=null,ri={mount:e,overlay:ei,sessionRef:Qr,config:()=>r},ii=!1,oi=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{ni??=n.createAskUserSheetHandlers(ri),ni[e](t)},a=ml();a?i(a):ii||(ii=!0,pl().then(e=>{ii=!1,r.isConnected&&i(e)},()=>{ii=!1}))};ei.addEventListener(`click`,oi(`click`)),ei.addEventListener(`keydown`,oi(`keydown`));let si=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=ei.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,si);let ci=null,li=null,ui=null,di=null,fi=()=>{},pi=!1,mi=``,hi=``;function gi(){di?.(),di=null}let _i=()=>{let e=jc?.railShell?jc.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},vi=()=>{if(!ci||!li)return;let t=e.classList.contains(`persona-artifact-welded-split`),n=e.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!t||e.classList.contains(`persona-artifact-narrow-host`)||r){li.style.removeProperty(`position`),li.style.removeProperty(`left`),li.style.removeProperty(`top`),li.style.removeProperty(`bottom`),li.style.removeProperty(`width`),li.style.removeProperty(`z-index`);return}let i=ci.firstElementChild;if(!i||i===li)return;li.style.position=`absolute`,li.style.top=`0`,li.style.bottom=`0`,li.style.width=`10px`,li.style.zIndex=`5`;let a=pS(ci,n),o=i.offsetWidth+a/2-5;li.style.left=`${Math.max(0,o)}px`},yi=()=>{},bi=()=>{let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;return!n||t.innerWidth>i?!1:I||Yh(r)},xi=()=>!jx(r)||!Zr()||e.classList.contains(`persona-artifact-narrow-host`)||bi()||(e.ownerDocument.defaultView??window).innerWidth<641?`none`:Ix(r)?`detached`:`welded`,Si=()=>{if(!Rr||!jx(r))return;Lx(e,r),Rx(e,r),yi();let t=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=G.getBoundingClientRect().width||0;e.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=t);let i=Zr();Rr.setVisible(i),Rr.update(Gr),Kr?(Rr.setMobileOpen(!1),Rr.element.classList.add(`persona-hidden`),Rr.backdrop?.classList.add(`persona-hidden`),qr=!1,Jr=!1):Gr.artifacts.length>0&&Xr()?(Rr.element.classList.remove(`persona-hidden`),Rr.setMobileOpen(!0)):(Rr.setMobileOpen(!1),Rr.element.classList.add(`persona-hidden`),Rr.backdrop?.classList.add(`persona-hidden`),qr=!1,Jr=!1);let a=r.features?.artifacts?.layout?.showExpandToggle===!0;if(Rr.setExpandToggleVisible(a),Rr.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),Rr.setRefreshButtonVisible(typeof r.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),Rr.setCustomActions(r.features?.artifacts?.toolbarActions??[]),Rr.setTabFade(r.features?.artifacts?.layout?.tabFade),Rr.setRenderTabBar(r.features?.artifacts?.renderTabBar),!a&&!Jr&&(qr=!1),qr!==pi){let e=Rr.element;qr?(mi=e.style.width,hi=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(mi&&(e.style.width=mi),hi&&(e.style.maxWidth=hi),mi=``,hi=``),pi=qr}e.classList.toggle(`persona-artifact-expanded`,qr),Rr.setExpanded(qr);let o=xi();o!==Ur&&(Ur=o,Hr()),fi()};if(jx(r)){G.style.position=`relative`;let t=B(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=B(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);t.appendChild(K),ci=n,n.appendChild(t),G.appendChild(n);let i=e=>{zr||Rr||(Rr=e.createArtifactPane(r,{onSelect:e=>Qr.current?.selectArtifact(e),onDismiss:()=>{Kr=!0,Si()},onToggleExpand:()=>{let e=!qr,t=Gr.selectedId??Gr.artifacts[Gr.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(qr=e,e||(Jr=!1),Si())}}),Rr.element.classList.add(`persona-hidden`),n.appendChild(Rr.element),Rr.backdrop&&G.appendChild(Rr.backdrop),fi(),Si())},a=kx();a?i(a):(Ax(()=>{let e=kx();e&&i(e)}),Ox().catch(()=>{})),fi=()=>{if(ci&&Rr){if(r.features?.artifacts?.layout?.resizable!==!0)ui?.(),ui=null,gi(),li&&=(li.remove(),null),Rr.element.style.removeProperty(`width`),Rr.element.style.removeProperty(`maxWidth`);else{if(!li){let t=B(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,`Resize artifacts panel`),t.tabIndex=0;let n=e.ownerDocument,i=n.defaultView??window,a=a=>{if(!Rr||a.button!==0||e.classList.contains(`persona-artifact-narrow-host`)||e.classList.contains(`persona-artifact-expanded`)||i.innerWidth<=640)return;a.preventDefault(),gi();let o=a.clientX,s=Rr.element.getBoundingClientRect().width,c=r.features?.artifacts?.layout,l=n=>{let r=ci.getBoundingClientRect().width,a=e.classList.contains(`persona-artifact-welded-split`),l=pS(ci,i),u=a?0:t.getBoundingClientRect().width||6,d=mS(s-(n.clientX-o),r,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,_i());Rr.element.style.width=`${d}px`,Rr.element.style.maxWidth=`none`,vi()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),di=null;try{t.releasePointerCapture(a.pointerId)}catch{}};di=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener(`pointerdown`,a),li=t,ci.insertBefore(t,Rr.element),ui=()=>{t.removeEventListener(`pointerdown`,a)}}if(li){let e=Zr();li.classList.toggle(`persona-hidden`,!e),vi()}}}},yi=()=>{if(!I||!Rr||(r.launcher?.sidebarMode??!1)||Yh(r)&&Zh(r).reveal===`emerge`)return;let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;if(n&&t.innerWidth<=i||!zx(r,I))return;let a=D_(r).width,o=r.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Zr()?(G.style.width=o,G.style.maxWidth=o):(G.style.width=a,G.style.maxWidth=a)},typeof ResizeObserver<`u`&&(Br=new ResizeObserver(()=>{Si()}),Br.observe(G))}else G.appendChild(K);L()&&tt&&(nt.peekBanner&&tt.appendChild(nt.peekBanner),tt.appendChild(Ot)),e.appendChild(W),tt&&e.appendChild(tt);let Ci=()=>{let t=bi()||L()&&r.launcher?.composerBar?.expandedSize===`fullscreen`||r.launcher?.fullHeight===!0&&!r.launcher?.sidebarMode&&!Yh(r);if(J.style.gap=t?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,J.style.setProperty(`--persona-transcript-gap`,J.style.gap),L()){G.style.width=`100%`,G.style.maxWidth=`100%`;let e=r.launcher?.composerBar??{},t=W.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){K.style.background=``,K.style.border=``,K.style.borderRadius=``,K.style.overflow=``,K.style.boxShadow=``;return}let i=r.theme?.components?.panel,a=Xp(r),o=(e,t)=>e==null||e===``?t:wp(a,e)??e;K.style.background=`var(--persona-surface, #ffffff)`,K.style.border=o(i?.border,`1px solid var(--persona-border)`),K.style.borderRadius=o(i?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),K.style.boxShadow=o(i?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),K.style.overflow=`hidden`;return}let n=Yh(r),i=r.launcher?.sidebarMode??!1,a=n||i||(r.launcher?.fullHeight??!1),o=r.launcher?.enabled===!1,s=r.launcher?.detachedPanel===!0,c=r.theme?.components?.panel,l=r.darkTheme?.components?.panel,u=qp(r)===`dark`?M(c??{},l??{}):c,d=Xp(r),f=(e,t)=>e==null||e===``?t:wp(d,e)??e,p=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,h=r.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&I,v=n&&m&&g,y=r.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=r.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),D=s&&!_&&!v,O=_||v?`mobile`:D?`floating`:n?`docked`:i?`sidebar`:o?`inline`:`floating`,k=u?.modes?.[O];D?e.setAttribute(`data-persona-panel-detached`,`true`):e.removeAttribute(`data-persona-panel-detached`);let A=D?w:i||_?`none`:w,j=D?T:_?`none`:i?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!D&&(j=`none`,A=`none`);let ee=D?E:i||_?`0`:E,N=f(k?.border??u?.border,S(O,`border`,A)),P=f(k?.shadow??u?.shadow,S(O,`shadow`,j)),te=f(k?.borderRadius??u?.borderRadius,S(O,`borderRadius`,ee)),ne=xi(),re=ne===`detached`,F=ne===`welded`;e.classList.toggle(`persona-artifact-detached-split`,re),e.classList.toggle(`persona-artifact-welded-split`,F);let ie=`var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))`,ae=(r.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&jx(r)&&Ix(r)&&o&&!n;e.classList.toggle(`persona-artifact-chat-flush`,ae);let oe=re||ae?`none`:P,se=re?w:F?`none`:N,ce=re?E:te;ae&&(se=`none`,ce=`0`);let le=k?.borderRadius!=null&&k.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,ue=ae&&!le?`0`:te,de=q.scrollTop;e.style.cssText=``,W.style.cssText=``,G.style.cssText=``,K.style.cssText=``,q.style.cssText=``,tr||(Ot.style.cssText=``),Ie&&(q.style.display=`none`),(a||o)&&(e.style.minWidth=`0`);let fe=()=>{de<=0||(q.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(q.scrollTop===de)return;let e=q.scrollHeight-q.clientHeight;e<=0||(q.scrollTop=Math.min(de,e))})};if(_){W.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`),W.style.cssText=`
|
|
1166
1166
|
position: fixed !important;
|
|
1167
1167
|
inset: 0 !important;
|
|
1168
1168
|
width: 100% !important;
|
|
@@ -1172,9 +1172,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1172
1172
|
padding: 0 !important;
|
|
1173
1173
|
display: flex !important;
|
|
1174
1174
|
flex-direction: column !important;
|
|
1175
|
-
z-index: ${
|
|
1175
|
+
z-index: ${x} !important;
|
|
1176
1176
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
1177
|
-
`,
|
|
1177
|
+
`,G.style.cssText=`
|
|
1178
1178
|
position: relative !important;
|
|
1179
1179
|
display: flex !important;
|
|
1180
1180
|
flex-direction: column !important;
|
|
@@ -1187,7 +1187,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1187
1187
|
padding: 0 !important;
|
|
1188
1188
|
box-shadow: none !important;
|
|
1189
1189
|
border-radius: 0 !important;
|
|
1190
|
-
`,
|
|
1190
|
+
`,K.style.cssText=`
|
|
1191
1191
|
display: flex !important;
|
|
1192
1192
|
flex-direction: column !important;
|
|
1193
1193
|
flex: 1 1 0% !important;
|
|
@@ -1198,7 +1198,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1198
1198
|
overflow: hidden !important;
|
|
1199
1199
|
border-radius: 0 !important;
|
|
1200
1200
|
border: none !important;
|
|
1201
|
-
`,
|
|
1201
|
+
`,q.style.flex=`1 1 0%`,q.style.minHeight=`0`,q.style.overflowY=`auto`,Ot.style.flexShrink=`0`,yn(),ve=!0,fe();return}let me=D_(r);if(!i&&!n)o&&a?(G.style.width=`100%`,G.style.maxWidth=`100%`):(G.style.width=me.width,G.style.maxWidth=me.maxWidth);else if(n){if(Zh(r).reveal===`emerge`&&!s){let e=Zh(r).width;G.style.width=e,G.style.maxWidth=e}else G.style.width=`100%`,G.style.maxWidth=`100%`}if(yi(),G.style.boxShadow=oe,G.style.borderRadius=ue,re?G.style.border=`none`:F&&(G.style.border=N),K.style.border=se,K.style.borderRadius=ce,K.style.boxShadow=re&&!ae?ie:``,ae&&(K.style.background=`transparent`,q.style.background=`transparent`,Ot.style.background=`transparent`,Ot.style.borderTop=`none`),F){let e=r.features?.artifacts?.layout;Wr=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||te}else Wr=null;let he=k?.border!=null||u?.border!=null;if(n&&!_&&!D&&!re&&!F&&!he&&(K.style.border=`none`,Zh(r).side===`right`?K.style.borderLeft=`1px solid var(--persona-border)`:K.style.borderRight=`1px solid var(--persona-border)`),n&&!_&&F&&!he&&(Zh(r).side===`right`?G.style.borderLeft=`1px solid var(--persona-border)`:G.style.borderRight=`1px solid var(--persona-border)`),a&&(e.style.display=`flex`,e.style.flexDirection=`column`,e.style.height=`100%`,e.style.minHeight=`0`,o&&(e.style.width=`100%`),W.style.display=`flex`,W.style.flexDirection=`column`,W.style.flex=`1 1 0%`,W.style.minHeight=`0`,W.style.maxHeight=`100%`,W.style.height=`100%`,o&&(W.style.overflow=`hidden`),G.style.display=`flex`,G.style.flexDirection=`column`,G.style.flex=`1 1 0%`,G.style.minHeight=`0`,G.style.maxHeight=`100%`,G.style.height=`100%`,re||(G.style.overflow=`hidden`),K.style.display=`flex`,K.style.flexDirection=`column`,K.style.flex=`1 1 0%`,K.style.minHeight=`0`,K.style.maxHeight=`100%`,K.style.overflow=`hidden`,q.style.flex=`1 1 0%`,q.style.minHeight=`0`,q.style.overflowY=`auto`,Ot.style.flexShrink=`0`),o&&(D||re||ae)&&!n&&(ae||(W.style.padding=`var(--persona-panel-inset)`),W.style.background=`var(--persona-panel-canvas-bg)`),W.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`),!i&&!o&&!n&&(ag[y]??ag[`bottom-right`]).split(` `).forEach(e=>W.classList.add(e)),i){let e=pe(r).sidebarWidth?r.launcher?.sidebarWidth??`420px`:wp(Xp(r),`components.panel.width`)??`420px`;s?W.style.cssText=`
|
|
1202
1202
|
position: fixed !important;
|
|
1203
1203
|
top: var(--persona-panel-inset) !important;
|
|
1204
1204
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -1209,9 +1209,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1209
1209
|
padding: 0 !important;
|
|
1210
1210
|
display: flex !important;
|
|
1211
1211
|
flex-direction: column !important;
|
|
1212
|
-
z-index: ${
|
|
1213
|
-
${
|
|
1214
|
-
`:
|
|
1212
|
+
z-index: ${x} !important;
|
|
1213
|
+
${b?`left: var(--persona-panel-inset) !important; right: auto !important;`:`left: auto !important; right: var(--persona-panel-inset) !important;`}
|
|
1214
|
+
`:W.style.cssText=`
|
|
1215
1215
|
position: fixed !important;
|
|
1216
1216
|
top: 0 !important;
|
|
1217
1217
|
bottom: 0 !important;
|
|
@@ -1222,9 +1222,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1222
1222
|
padding: 0 !important;
|
|
1223
1223
|
display: flex !important;
|
|
1224
1224
|
flex-direction: column !important;
|
|
1225
|
-
z-index: ${
|
|
1226
|
-
${
|
|
1227
|
-
`,
|
|
1225
|
+
z-index: ${x} !important;
|
|
1226
|
+
${b?`left: 0 !important; right: auto !important;`:`left: auto !important; right: 0 !important;`}
|
|
1227
|
+
`,G.style.cssText=`
|
|
1228
1228
|
position: relative !important;
|
|
1229
1229
|
display: flex !important;
|
|
1230
1230
|
flex-direction: column !important;
|
|
@@ -1236,9 +1236,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1236
1236
|
margin: 0 !important;
|
|
1237
1237
|
padding: 0 !important;
|
|
1238
1238
|
box-shadow: ${oe} !important;
|
|
1239
|
-
border-radius: ${
|
|
1240
|
-
${
|
|
1241
|
-
`,
|
|
1239
|
+
border-radius: ${ue} !important;
|
|
1240
|
+
${re?`border: none !important;`:F?`border: ${N} !important;`:``}
|
|
1241
|
+
`,G.style.setProperty(`width`,`100%`,`important`),G.style.setProperty(`max-width`,`100%`,`important`),K.style.cssText=`
|
|
1242
1242
|
display: flex !important;
|
|
1243
1243
|
flex-direction: column !important;
|
|
1244
1244
|
flex: 1 1 0% !important;
|
|
@@ -1249,14 +1249,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1249
1249
|
overflow: hidden !important;
|
|
1250
1250
|
border-radius: ${ce} !important;
|
|
1251
1251
|
border: ${se} !important;
|
|
1252
|
-
${
|
|
1252
|
+
${re&&!ae?`box-shadow: ${ie} !important;`:``}
|
|
1253
1253
|
${ae?`background: transparent !important;`:``}
|
|
1254
|
-
`,
|
|
1254
|
+
`,tr||(Ot.style.cssText=`
|
|
1255
1255
|
flex-shrink: 0 !important;
|
|
1256
1256
|
border-top: none !important;
|
|
1257
1257
|
padding: 8px 16px 12px 16px !important;
|
|
1258
1258
|
${ae?`background: transparent !important;`:``}
|
|
1259
|
-
`)}if(!o&&!n){let e=i?``:`padding-top: 1.25em !important;`,t=i?``:`z-index: ${r.launcher?.zIndex??1e5} !important;`;at.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}yn(),de()},Ci=()=>{e.style.setProperty(`--persona-content-max-width`,Wp(r,ge()))},wi=!1;function Ti(){r.layout?.topFade&&K.scrollTop>1?K.setAttribute(`data-persona-top-fade`,`true`):K.removeAttribute(`data-persona-top-fade`)}let Ei=()=>{Ti();let t=Gp(r,ge());ge()&&r.composer?.placement&&r.debug===!0&&!wi&&(wi=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=mn();e.setAttribute(`data-persona-composer-placement`,t),e.setAttribute(`data-persona-conversation-state`,hn),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),e.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),bn()},Di=()=>{if(ge())return;let t=zh(r),n=r.launcher?.sidebarMode??!1;if(t||n||(r.launcher?.fullHeight??!1)||!R)return;let i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640;if(a&&i.innerWidth<=o)return;let s=__(r);W.style.height=s.height,W.style.maxHeight=s.maxHeight};Si(),Hp(e,r),Dx(e,r),Ox(e,r),Ci(),Ei(),Vr=()=>{Si(),Di(),Hp(e,r),Dx(e,r),Ox(e,r),Ci(),Ei(),Ur?e.style.setProperty(`--persona-artifact-welded-outer-radius`,Ur):e.style.removeProperty(`--persona-artifact-welded-outer-radius`),We(),Ue()};let Q=[];Q.push(()=>{zr=!0}),Q.push(()=>{p.forEach(e=>e()),f.destroy()}),Q.push(()=>{document.removeEventListener(`keydown`,oi)}),Q.push(()=>{ln!==null&&clearTimeout(ln)});let Oi=null,ki=null;Q.push(()=>{Oi?.(),Oi=null,ki?.(),ki=null}),Br&&Q.push(()=>{Br?.disconnect(),Br=null}),Q.push(()=>{li?.(),li=null,hi(),ci&&=(ci.remove(),null),Rr?.element.style.removeProperty(`width`),Rr?.element.style.removeProperty(`maxWidth`),Rr?.destroy()}),Se&&Q.push(()=>{Me=!0,je=null,Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),Ne?.destroy(),Ne=null,ke?.destroy(),ke=null,De=null});let Ai=null,ji=()=>{Ai&&=(Ai(),null),r.colorScheme===`auto`&&(Ai=Up(()=>{Hp(e,r)}))};ji(),Q.push(()=>{Ai&&=(Ai(),null)}),Q.push(()=>{x=!0,b?.()}),Q.push(()=>{T=!0});let Mi=!1;Q.push(()=>{Mi=!0});let Ni=(t,n)=>{let r=Nm(t,n);return r||!jm.includes(t)?r:(Nh().then(r=>{if(Mi)return;Mm(r.wipe),Mm(r.glyphCycle);let i=Nm(t,n);i&&Ym(i,e)}).catch(()=>{}),null)},Pi=r.features?.streamAnimation;if(Pi?.type&&Pi.type!==`none`){let t=Ni(Pi.type,Pi.plugins);t&&Ym(t,e),Q.push(()=>Jm(e))}let Fi=Jh(dt),Ii=Jh(lt),Li=Jh(ut),Ri=[Fi,Ii,Li];Q.push(()=>{Ri.forEach(e=>e.destroy())});let zi=null,$,Bi=null,Vi=!1,Hi=0,Ui=null,Wi=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),Gi=e=>{for(let t=e.length-1;t>=0;t--)if(Er(e[t]))return e[t].id??null;return null},Ki=!1,qi=()=>{Ki||r.debug!==!0||(Ki=!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".`))},Ji=!1,Yi=!1,Xi=(e,t)=>{Ji||r.debug!==!0||t.enabled&&!t.expose&&(Vi||Yi&&($.isStreaming()||e.some(Er)||(Ji=!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.`))))},Zi=e=>{if(!$)return;let t=e??$.getMessages(),n=e=>{e.render([],$,J,t)},i=e=>{Ri.forEach(t=>{t!==e&&n(t)})};Bi&&(Wi(t)>Hi||Gi(t)!==Ui)&&(Bi=null);let a=jr(r);Xi(t,a);let o=a.enabled?Or(t):null,s=Bi??o,c=Bi?`host`:`agent`;if(s){let e=r.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?ge()?`composer`:`after-message`:n)===`after-message`?Li:Fi;i(a),a.render(s,$,J,t,r.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:r,plugins:d,submitPrompt:Sl});return}if(t.some(e=>e.role===`user`)){Ri.forEach(n);return}let l=r.future?.v5Defaults===!0,u=pn(),f=r.suggestions?.starters??(l?{}:void 0);if(f){let e=h_(mn(),t),a=f.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){qi(),Ri.forEach(n);return}let s=o===`welcome`?Ii:Fi;i(s),s.render(f.items??r.suggestionChips,$,J,t,r.suggestionChipsConfig,{surface:`starter`,variant:f.variant??(l&&!u?`chip`:`card`),behavior:f.behavior??`send`,overflow:f.overflow??`wrap`,maxItems:f.maxItems??(l&&!u?3:4),config:r,plugins:d,submitPrompt:Sl})}else i(Fi),Fi.render(r.suggestionChips,$,J,t,r.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:r,plugins:d,submitPrompt:Sl})},Qi=()=>{Bi&&(Bi=null,Zi())},$i=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){Qi();return}let n=$?$.getMessages():[];Bi=t,Vi=!0,Hi=Wi(n),Ui=Gi(n),Zi(n)},ea=!1,ta=fm(),na=/* @__PURE__ */ new Map,ra=/* @__PURE__ */ new Map,ia=/* @__PURE__ */ new Map,aa=null,oa=null;function sa(){if(!aa)return;let e=aa;aa=null,oa?.destroy(),oa=null,ta.delete(e),G.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),$&&rs(q,$.getMessages(),ye)}let ca=0,la=mt()!==null,ua=_m(),da=0,fa=null,pa=!1,ma=!1,ha=0,ga=null,_a=null,va=!1,ya=!1,ba=null,xa=!0,Sa=!1,Ca=null,Ta=!1,Ea=()=>{Ta=!0,Aa()},Da=null,Oa=null,ka=()=>{e.setAttribute(`data-persona-scrollbar`,en()),en()!==`on-scroll`&&(Oa!==null&&clearTimeout(Oa),Oa=null,K.removeAttribute(`data-persona-scrollbar-visible`))},Aa=()=>{en()===`on-scroll`&&(K.setAttribute(`data-persona-scrollbar-visible`,``),Oa!==null&&clearTimeout(Oa),Oa=setTimeout(()=>{Oa=null,ym(K,24)&&K.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};ka(),Q.push(()=>{Oa!==null&&clearTimeout(Oa)});let ja=/* @__PURE__ */ new Map,Ma=!1,Na=null,Pa={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Sr();let Fa=r.voiceRecognition?.autoResume??!1,La=()=>$.isVoiceActive()||$.isBargeInActive(),Ra=!1,za=e=>{k.emit(`voice:state`,{active:Pa.active,source:e,timestamp:Date.now()})},Ba=()=>{se(e=>({...e,voiceState:{active:Pa.active,timestamp:Date.now(),manuallyDeactivated:Pa.manuallyDeactivated}}))},Va=()=>{if(r.voiceRecognition?.enabled===!1)return;let e=Fw(M.voiceState),t=!!e.active,n=Number(e.timestamp??0);Pa.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{Pa.active||(Pa.manuallyDeactivated=!1,ot(r.voiceRecognition?.provider)?$.toggleVoice().then(()=>{Pa.active=La(),za(`restore`),Pa.active?ou():(Ba(),dl(`Tap the mic to resume your voice call`,1e4))}):nu(`restore`))},ot(r.voiceRecognition?.provider)?0:1e3)},Ha=e=>{Ra=!e.persisted,Pa.active&&Ba()};typeof window<`u`&&(window.addEventListener(`pagehide`,Ha),Q.push(()=>window.removeEventListener(`pagehide`,Ha)));let Ua=()=>$?Iw($.getMessages()).filter(e=>!e.__skipPersist):[],Wa=null,Ga=(e,t)=>{typeof console<`u`&&console.error(e,t)},Ka=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Ga(t,e)})}catch(e){return Ga(t,e),null}},r=Wa,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{Wa===a&&(Wa=null)});Wa=a};function qa(e){if(!A?.save)return;let t=e?Iw(e):$?Ua():[],n=j&&$?.getResumableHandle();n&&(M={...M,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:M,artifacts:Wr.artifacts,selectedArtifactId:Wr.selectedId,...Ya?{draft:Ya}:{}};Ka(()=>A.save(r),`[AgentWidget] Failed to persist state:`)}let Ya,Xa=()=>!A?.save||r.persistState===!1?!1:typeof r.persistState!=`object`||r.persistState.persist?.draft!==!1,Za=Hf({write:()=>{if(!Xa())return;let e=Z.getState(),t=Bf({text:e.text,mentionRefs:e.mentionRefs,contentSegments:il(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Ya)&&(Ya=t,qa())}});function Qa(){Xa()&&Za.schedule()}function $a(){Za.flush()}function eo(e){if(!Xa())return;let t=Vf(e,{mentionSourceIds:(r.contextMentions?.sources??[]).map(e=>e.id),modelIds:(r.composer?.models??[]).map(e=>e.id),modes:r.composer?.modes??[]});t&&(Ya=e,J&&!J.value&&(J.value=t.text,J.dispatchEvent(new Event(`input`,{bubbles:!0})),wn()),t.selectedModelId&&(Z.setSelectedModelId(t.selectedModelId),Nn?.repaint()),jn(t.activeModeIds??[]),t.quote&&Rn(t.quote),Za.cancel())}function to(){Za.cancel(),Ya&&(Ya=void 0,Xa()&&qa())}let no=null,io=()=>at.querySelector(`#persona-scroll-container`)||K,ao=()=>{no!==null&&(cancelAnimationFrame(no),no=null),pa=!1},oo=()=>{fa!==null&&(cancelAnimationFrame(fa),fa=null),ma=!1,ao()},so=()=>ea&&fo()&&(Kt()!==`anchor-top`||Zt()),co=()=>{let e=Ht()||`Jump to latest`,t=so();tn.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),ha>0?(an.textContent=String(ha),an.style.display=``,tn.setAttribute(`aria-label`,`${e} (${ha} new)`)):(an.textContent=``,an.style.display=`none`,tn.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},lo=()=>{ha!==0&&(ha=0,co())},uo=()=>{let e=ga?.spacerHeight??0;return e<=0?ym(K,24):Oo(e)-K.scrollTop-K.clientHeight<=24},fo=()=>qt()?!ua.isFollowing():!uo(),po=()=>!!$&&$.getMessages().length>0,mo=()=>{if(!Gt()||Je()){tn.parentNode&&tn.remove(),tn.style.display=`none`;return}tn.parentNode!==G&&G.appendChild(tn),vn();let e=vm(K)>0&&fo()&&po();e?co():lo(),tn.style.display=e?``:`none`},ho=()=>{ua.pause()&&(oo(),mo())},go=()=>{ua.resume(),lo(),mo()},vo=(e=!1)=>{qt()&&po()&&ua.isFollowing()&&(e||ea)&&(fa!==null&&(cancelAnimationFrame(fa),fa=null),ma=!0,fa=requestAnimationFrame(()=>{fa=null,ma=!1,ua.isFollowing()&&xo(io(),e?220:140)}))},bo=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(ao(),Math.abs(o)<1){pa=!0,e.scrollTop=a,da=e.scrollTop,pa=!1;return}let s=performance.now();pa=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){ao();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,da=e.scrollTop,p<1?no=requestAnimationFrame(l):(e.scrollTop=a,da=e.scrollTop,no=null,pa=!1)};no=requestAnimationFrame(l)},xo=(e,t=500)=>{let n=vm(e)-e.scrollTop;Math.abs(n)<1?da=e.scrollTop:Math.abs(n)>=80?(ao(),pa=!0,e.scrollTop=vm(e),da=e.scrollTop,pa=!1):bo(e,()=>vm(e),t,()=>ua.isFollowing())},So=()=>{if(!po()){mo();return}let e=io();pa=!0,e.scrollTop=vm(e),da=e.scrollTop,pa=!1,mo()},Co=e=>{let t=0,n=e;for(;n&&n!==K;)t+=n.offsetTop,n=n.offsetParent;return t},wo=()=>{let e=K.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??K.ownerDocument.getSelection()},To=()=>Sm(wo(),K),Eo=()=>{if(Yt()!==`last-user-turn`)return!1;let e=$?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=K.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,Co(r)-Jt()),vm(K));return pa=!0,K.scrollTop=i,da=K.scrollTop,pa=!1,Kt()===`follow`&&!ym(K,24)&&ua.pause(),mo(),!0},Do=e=>{let t=Math.max(0,Math.round(e));on.style.height=`${t}px`,on.style.display=t>0?``:`none`,ga&&(ga.spacerHeight=Math.max(0,e))},Oo=e=>{let t=parseFloat(getComputedStyle(K).paddingBottom)||0,n=0;for(let e of Array.from(K.children)){if(e===on||e.offsetHeight===0)continue;let t=Co(e)+e.offsetHeight;t>n&&(n=t)}let r=K.scrollHeight-e;return n>0?Math.min(n+t,r):r},ko=()=>{if(!ga||ga.spacerHeight<=0)return;let e=Oo(ga.spacerHeight),t=Math.max(0,Math.round(K.scrollTop)+K.clientHeight-e+24);t<ga.spacerHeight&&(Do(t),mo())},Ao=()=>{_a!==null&&(cancelAnimationFrame(_a),_a=null),ao(),ga=null,on.style.height=`0px`,on.style.display=`none`},jo=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),Mo=e=>K.querySelector(`[data-message-id="${jo(e)}"]`),No=e=>{_a!==null&&cancelAnimationFrame(_a),_a=requestAnimationFrame(()=>{_a=null;let t=jo(e),n=K.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=Co(n),i=ga?.spacerHeight??0,a=Oo(i),{targetScrollTop:o,spacerHeight:s}=Cm({anchorOffsetTop:r,topOffset:Jt(),viewportHeight:K.clientHeight,contentHeight:a,slack:24});ga={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},Do(s),bo(K,()=>n.isConnected?Math.max(0,Co(n)-Jt()):o,220)})},Po=()=>{if(Kt()!==`anchor-top`||!ga||!Ca)return;let e=Mo(Ca);if(!e)return;ao();let t=ga.spacerHeight,n=Oo(t),{targetScrollTop:r,spacerHeight:i}=Cm({anchorOffsetTop:Co(e),topOffset:Jt(),viewportHeight:K.clientHeight,contentHeight:n,slack:24});ga={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},Do(i),pa=!0,K.scrollTop=r,da=K.scrollTop,pa=!1,mo()},Fo=()=>{if(qt()){if(!ua.isFollowing()||ym(K,1))return;vo(!ea)}else{if(ga&&ga.initialSpacerHeight>0){let e=K.scrollHeight-ga.spacerHeight,t=wm({initialSpacerHeight:ga.initialSpacerHeight,contentHeightAtAnchor:ga.contentHeightAtAnchor,currentContentHeight:e});t!==ga.spacerHeight&&Do(t)}mo()}},Io=e=>{let t=Kt();t===`follow`?(go(),vo(!0)):t===`anchor-top`&&(xa=!1,Sa=!0,Ta=!1,Ca=e,No(e))},Lo=()=>{Kt()===`anchor-top`&&(Sa?xa=!1:(xa=!0,Ao(),go(),vo(!0)))},Vo=e=>{if(ba===null)return!0;let t=Mo(ba),n=Mo(e);if(!t||!n)return!0;let r=Co(n)-Co(t);return Jt()+r>K.clientHeight-96},Uo=e=>{if(Kt()!==`anchor-top`||!Sa||Ta||To())return;let t=ba===null;for(let n of e)if(!t)n.id===ba&&(t=!0);else if(gm(n)){if(n.id===Ca||!Vo(n.id))return;Ca=n.id,No(n.id);return}},qo=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=ja.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(k.emit(`assistant:message`,e),!ya&&(Kt()!==`anchor-top`||Zt())&&fo()&&(ha+=1,co(),mo(),fn(ha===1?`1 new message below.`:`${ha} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&k.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&k.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):k.emit(`approval:requested`,{approval:e.approval,message:e}))}),ja.clear(),t.forEach((e,t)=>{ja.set(t,e)})},Xo=(e,t)=>{let n=t===`user`?`user`:`assistant`,i=r.layout?.messages?.[n],a=i?.width??`content`,o=i?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},Zo=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Xo(n,t),n},$o=(e,t,n)=>{let c=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||Xe(r,t)!==`row`)continue;let n=t===`tool`?r.features?.toolCallDisplay:r.features?.reasoningDisplay;n?.expandable!==!1&&(c.add(e.id),o.observe(e,t,t===`tool`?i:a,n))}let l=document.createElement(`div`),u=(()=>{let e=d.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),f=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Set,g=d.some(e=>e.renderAskUserQuestion),_=[],v=[],b=r.enableComponentStreaming!==!1,x=r.approval!==!1,S=[],C=r.messageActions,T=C?.showRegenerate===!0&&C.enabled!==!1&&Zr.current?.isStreaming()!==!0?Ml(t):null,E=C?.showEdit===!0&&C.enabled!==!1,D=C?.showQuote===!0&&C.enabled!==!1,k=null,A=r.features?.reasoningDisplay?.completedVisibility,j=e=>A===`removed`||A===`removed-when-short`&&sn(e,r.features?.reasoningDisplay?.shortThinkThreshold),M=r.features?.toolCallDisplay?.completedVisibility===`removed`,ee=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?j(e.reasoning):M&&e.variant===`tool`&&e.toolCall?.status===`complete`;if(t.forEach(t=>{if(ee(t))return;if(p.add(t.id),m.set(t.id,t.role),aa===t.id&&oa){let e=Zo(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),k={messageId:t.id,element:oa.element};return}let o=g&&Hn(t),c=x&&t.variant===`approval`&&!!t.approval,f=!o&&t.role===`assistant`&&!t.variant&&b&&Sw(t);!c&&ia.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ia.delete(t.id)),!f&&ra.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ra.delete(t.id));let C=Hn(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,A={canRegenerate:T===t.id,canEdit:E&&Nl(t),canQuote:D&&!t.variant&&(t.content?.trim().length??0)>0},j=`${A.canRegenerate?`r`:``}${A.canEdit?`e`:``}${A.canQuote?`q`:``}`,M=dm(t,ca)+C+`:${j}`,N=o||c||f?null:pm(ta,t.id,M);if(N){l.appendChild(N.cloneNode(!0)),Hn(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),ei(t));return}let P=null,F=d.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),te=r.layout?.messages;if(Hn(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){na.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(Er(t)&&jr(r).enabled)return;if(Hn(t)&&r.features?.askUserQuestion?.enabled!==!1){let e=d.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Zr.current){let n=na.get(t.id),i=n!==M,a=null;if(i){let{payload:n,complete:i}=Wn(t),o=t.id,s=()=>Zr.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:i,resolve:e=>{let t=s();t&&Zr.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Zr.current?.markAskUserQuestionResolved(e),Zr.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:r})}if(i&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),ei(t));return}let o=Zo(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(o),_.push({messageId:t.id,fingerprint:M,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),ei(t));return}if(c){let n=w();if(!n){l.appendChild(Zo(t.id,t.role));return}let i=d.find(e=>typeof e.renderApproval==`function`)??y,a=ia.get(t.id)!==M,o=null;if(a&&i?.renderApproval){let e=t.id,a=(t,n)=>{let r=Zr.current?.getMessages().find(t=>t.id===e);r?.approval&&(r.approval.toolType===`webmcp`?Zr.current?.resolveWebMcpApproval(r.id,t):Zr.current?.resolveApproval(r.approval,t,n))};o=i.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,r,s),config:r,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ia.delete(t.id),P=n.createApprovalBubble(t,r,s);else{let e=Zo(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),S.push({messageId:t.id,fingerprint:M,bubble:o});return}}else if(F){if(t.variant===`reasoning`&&t.reasoning&&F.renderReasoning){if(!be)return;P=F.renderReasoning({message:t,defaultRenderer:()=>U_(t,r,a),config:r})}else if(t.variant===`tool`&&t.toolCall&&F.renderToolCall){if(!xe)return;P=F.renderToolCall({message:t,defaultRenderer:()=>ev(t,r,i),config:r})}else F.renderMessage&&(P=F.renderMessage({message:t,defaultRenderer:()=>{let e=Yg(t,n,te,r.messageActions,Ye,{loadingIndicatorRenderer:u,widgetConfig:r,actionEligibility:A});return t.role!==`user`&&O(e,t,r,$),e},config:r}))}if(!P&&f){let i=Cw(t);if(i){let a=ra.get(t.id),o=a!==M,s=r.wrapComponentDirectiveInBubble!==!1&&Sy.getOptions(i.component)?.bubbleChrome!==!1,c=null;if(o){let a=bw(i,{config:r,message:t,transform:n});if(a&&i.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&yx()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=Zo(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),v.push({messageId:t.id,fingerprint:M,bubble:c});return}}}if(!P){if(t.variant===`reasoning`&&t.reasoning){if(!be)return;P=U_(t,r,a)}else if(t.variant===`tool`&&t.toolCall){if(!xe)return;P=ev(t,r,i)}else if(t.variant===`approval`&&t.approval){if(r.approval===!1)return;let e=w();if(!e)return;P=e.createApprovalBubble(t,r,s)}else{let e=r.layout?.messages;P=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:r,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:r,streaming:!!t.streaming}):Yg(t,n,e,r.messageActions,Ye,{loadingIndicatorRenderer:u,widgetConfig:r,actionEligibility:A}),t.role!==`user`&&P&&O(P,t,r,$)}}let ne=Zo(t.id,t.role);ne.appendChild(P),mm(ta,t.id,M,ne),l.appendChild(ne)}),ct.composerOverlay&&ct.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!h.has(t)&&_r(ct.composerOverlay,t)}),r.features?.toolCallDisplay?.grouped){let e=[],n=[],a=r.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&xe){if(M&&t.toolCall.status===`complete`)return;n.push(t)}else(t.variant!==`reasoning`||be&&(t.reasoning?.status!==`complete`||!j(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(l.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=Zo(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),r.features?.toolCallDisplay?.groupedMode===`collapsible`){let a=`tool-group-${e[0].id}`,s=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:s?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1)}};c.add(a),o.observe(l,`tool`,i,r.features.toolCallDisplay);let u=`${s?`Using`:`Used`} ${e.length} tools`,d=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:r}),f=et(l,r,i.has(a),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let u=document.createElement(`div`);u.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,u.id=`tool-group-summary-${e[0].id}`;let d=`Called ${e.length} ${e.length===1?`tool`:`tools`}`,p=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:d,config:r});f(u,p)||(u.textContent=d);let m=document.createElement(`div`);m.className=`persona-tool-group-stack persona-flex persona-flex-col`,m.id=`tool-group-stack-${e[0].id}`,m.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(u),a||s.appendChild(m),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),m.appendChild(r)})})}o.prune(c),hm(ta,p);let N=e=>e.variant===`tool`&&!xe||e.variant===`reasoning`&&!be||ee(e),P=t.some(e=>e.role===`assistant`&&e.streaming&&!N(e)),F=t.length-1;for(;F>=0&&N(t[F]);)F--;let te=F>=0?t[F]:void 0,ne=F<t.length-1,I=te?.role===`assistant`&&!te.streaming&&te.variant!==`approval`&&!ne;if(ea&&t.some(e=>e.role===`user`)&&!P&&!I){let e={config:r,streaming:!0,location:`standalone`,defaultRenderer:zg},t=d.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&r.loadingIndicator?.render&&(n=r.loadingIndicator.render(e)),n===null&&(n=zg()),n){let e=document.createElement(`div`),t=r.loadingIndicator?.showBubble!==!1,i=r.layout?.messages?.layout??`bubble`;e.className=t?Ug(`assistant`,i).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,i!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Zo(`typing-indicator`,`assistant`);a.appendChild(e),l.appendChild(a)}}if(!ea&&t.length>0){let e=t[t.length-1],n={config:r,lastMessage:e,messageCount:t.length},i=d.find(e=>e.renderIdleIndicator),a=null;if(i?.renderIdleIndicator&&(a=i.renderIdleIndicator(n)),a===null&&r.loadingIndicator?.renderIdle&&(a=r.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=r.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`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(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Zo(`idle-indicator`,`assistant`);t.appendChild(e),l.appendChild(t)}}if(Ft(l),sm(e,l),It(e),k){let{messageId:t,element:n}=k,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Xo(r,m.get(t)??`user`),r.replaceChildren(n))}if(_.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of _){let i=e.querySelector(`#wrapper-${t}`);i&&(Xo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),na.set(t,n)))}if(na.size>0)for(let e of na.keys())p.has(e)||na.delete(e);if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(Xo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ra.set(t,n)))}if(ra.size>0)for(let e of ra.keys())p.has(e)||ra.delete(e);if(S.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of S){let i=e.querySelector(`#wrapper-${t}`);i&&(Xo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ia.set(t,n)))}if(ia.size>0)for(let e of ia.keys())p.has(e)||ia.delete(e)},ts=!1,ns=()=>{ts||(ts=!0,ti().catch(()=>{}),ft().catch(()=>{ts=!1}))},rs=(e,t,n)=>{t.length>0&&ns(),$o(e,t,n),Fr()},is=null,os=()=>{if(is)return;let t=e=>{let t=e.composedPath();t.includes(at)||st&&t.includes(st)||ys(!1,`user`)};is=t,(e.ownerDocument??document).addEventListener(`pointerdown`,t,!0)},ss=()=>{is&&=((e.ownerDocument??document).removeEventListener(`pointerdown`,is,!0),null)};Q.push(()=>ss());let cs=null,ls=()=>{if(cs)return;let t=e=>{e.key===`Escape`&&(e.isComposing||ys(!1,`user`))};cs=t,(e.ownerDocument??document).addEventListener(`keydown`,t,!0)},us=()=>{cs&&=((e.ownerDocument??document).removeEventListener(`keydown`,cs,!0),null)};Q.push(()=>us());let ds=!1,fs=/* @__PURE__ */ new Set,ps=()=>r.launcher?.composerBar?.peek?.streamAnimation||r.features?.streamAnimation,gs=()=>{if(!ge())return;let t=ct.peekBanner,n=ct.peekTextNode;if(!t||!n)return;if(V){t.classList.remove(`persona-pill-peek--visible`);return}let r=$?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){t.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=ps(),c=Om(s),l=c.type===`none`?null:Ni(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!fs.has(l.name)&&(Ym(l,e),fs.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?Pm(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=Um();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),sm(n,e)}else{let e=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=yt(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=Vm(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:e}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=Hm(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}sm(n,s),l.onAfterRender?.({container:n,bubble:t,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=ea||ds;t.classList.toggle(`persona-pill-peek--visible`,h)};if(ge()){let e=ct.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),ys(!0,`user`)};e.addEventListener(`pointerdown`,t),Q.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{ds||(ds=!0,gs())},n=()=>{ds&&(ds=!1,gs())};W.addEventListener(`pointerenter`,t),W.addEventListener(`pointerleave`,n),Q.push(()=>{W.removeEventListener(`pointerenter`,t),W.removeEventListener(`pointerleave`,n)}),st&&(st.addEventListener(`pointerenter`,t),st.addEventListener(`pointerleave`,n),Q.push(()=>{st.removeEventListener(`pointerenter`,t),st.removeEventListener(`pointerleave`,n)}))}let _s=e=>{let t=r.launcher?.composerBar??{},n=t.expandedSize??`anchored`,i=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=at.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,st){let e=st.style;e.bottom=i,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${i} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},vs=()=>{if(V&&ns(),!B())return;if(ge()){let e=(r.launcher?.composerBar??{}).expandedSize??`anchored`,t=V?`expanded`:`collapsed`;at.dataset.state=t,at.dataset.expandedSize=e,st&&(st.dataset.state=t,st.dataset.expandedSize=e),at.style.removeProperty(`display`),at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),W.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),_s(V),G.style.display=V?`flex`:`none`,Vr(),V?(os(),ls()):(ss(),us()),gs();return}let t=zh(r),n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileBreakpoint??640,a=r.launcher?.mobileFullscreen??!0,o=n.innerWidth<=i,s=a&&o&&R,c=Vh(r).reveal;V?(at.style.removeProperty(`display`),at.style.display=t?`flex`:``,at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),W.classList.remove(`persona-scale-95`,`persona-opacity-0`),W.classList.add(`persona-scale-100`,`persona-opacity-100`),wu?(wu.setPanelOpen(!0),wu.element.style.display=`none`):Tu&&(Tu.style.display=`none`)):(t?t&&(c===`overlay`||c===`push`)&&!s?(at.style.removeProperty(`display`),at.style.display=`flex`,at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),W.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(at.style.setProperty(`display`,`none`,`important`),at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),W.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(at.style.display=``,at.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),W.classList.remove(`persona-scale-100`,`persona-opacity-100`),W.classList.add(`persona-scale-95`,`persona-opacity-0`)),wu?(wu.setPanelOpen(!1),wu.element.style.display=t?`none`:``):Tu&&(Tu.style.display=t?`none`:``))},ys=(t,n=`user`)=>{if(!B()||V===t)return;let i=V;V=t,vs();let a=(()=>{let t=r.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileFullscreen??!0,a=r.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=zh(r)&&i&&o,c=ge()&&(r.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return t||i&&o&&R||s||c})();if(V&&a){if(!Oi){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&(Oi=Ph(n,r.launcher?.zIndex??1e5))}ki||=Lh(e.ownerDocument)}else V||(Oi?.(),Oi=null,ki?.(),ki=null);V&&(ku(),Eo()||(Kt()===`follow`?vo(!0):So()));let o={open:V,source:n,timestamp:Date.now()};V&&!i?k.emit(`widget:opened`,o):!V&&i&&k.emit(`widget:closed`,o),k.emit(`widget:state`,{open:V,launcherEnabled:R,voiceActive:Pa.active,streaming:$.isStreaming()})},bs={inputDisabled:!1,sendDisabled:!1},xs=()=>bs.inputDisabled,Ss=()=>ot(r.voiceRecognition?.provider)&&!!$&&($.isBargeInActive()||[`listening`,`processing`,`speaking`].includes($.getVoiceStatus())),Cs=()=>bs.inputDisabled||bs.sendDisabled,ws=()=>(bs.inputDisabled?bs.inputReason:void 0)??(bs.sendDisabled?bs.sendReason:void 0);function Ts(){if(!Y)return;if(Z.getState().phase===`streaming`){Y.disabled=!1;return}let e=Sn?!Sn.isReady():!1;Y.disabled=Cs()||e}function Es(){if(!Nt)return;let e=Z.getState(),t=r.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Nt.toggleAttribute(`data-persona-send-hidden`,t)}function Ds(){let e=ws();if(ge()){let t=ht??kt;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),kt.toggleAttribute(Ow,!!e)}else if(e)gt.setAttribute(`role`,`status`),gt.setAttribute(`aria-live`,`polite`),gt.setAttribute(Ow,``),gt.removeAttribute(kw),gt.textContent=e,nt(gt,r.statusIndicator??{},`idle`);else if(gt.hasAttribute(Ow)&&(gt.removeAttribute(`role`),gt.removeAttribute(`aria-live`),gt.removeAttribute(Ow),m)){let e=$.getStatus();tt(gt,Qe(e),r.statusIndicator??{},e)}}function Os(){let e=Ko(r.composer?.inputDisabled),t=Ko(r.composer?.sendDisabled);bs={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Z.setInputDisabled(e.disabled),Z.setSendDisabled(t.disabled);let n=Z.getState().phase===`streaming`,i=e.disabled,a=n||i;J&&(J instanceof HTMLTextAreaElement?J.disabled=i:J.setAttribute(`contenteditable`,i?`false`:`true`),J.setAttribute(`aria-disabled`,i?`true`:`false`)),Rt&&(Rt.disabled=i),Bt&&(Bt.disabled=i);for(let e of Cn?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=i});X&&(X.disabled=i||n&&!Ss()),Ri.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),Gs.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),kt.dataset.personaComposerStreaming=n?`true`:`false`,kt.dataset.personaComposerInputDisabled=i?`true`:`false`,kt.dataset.personaComposerSendDisabled=Cs()?`true`:`false`,kt.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),Ts(),Ds()}let ks=e=>{Z.setStreaming(e),Pt(e?`stop`:`send`),Os()},As=()=>{Pa.active||J&&J.focus()};k.on(`widget:opened`,()=>{r.autoFocusInput&&setTimeout(()=>As(),200)});let js=null,Ms=!1,Ns=!_t.hidden,Ps=null,Fs=!ee,Is=null;Q.push(()=>{Is?.cancel(),Is=null});let Ls=t=>{let n=m_(t);if(n===hn)return;hn=n,e.setAttribute(`data-persona-conversation-state`,n);let r=_n();bn(),Fs&&(Is?.cancel(),Is=l_(kt,n===`active`?r:_n(),n===`active`?`drop`:`rise`,mn().layout===`centered`?320:260)),Po()},Rs=null,zs,Bs=null,Vs=null,Hs=!1,Us=e=>{let t=mn(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==Rs||t.icon!==zs)&&(Rs=n,zs=t.icon,$g({host:_t,iconHolder:vt,kicker:xt,title:St,subtitle:Ct,starterSuggestions:lt},t));let i=t.message===void 0?null:`${r.layout?.messages?.layout??`bubble`}|${t.message}`;i!==Bs&&(Bs=i,o_(bt,t.message,r));let a=e??($?$.getMessages():r.initialMessages);Ls(a);let o=Ms,s=!o&&h_(t,a),c=s!==Ns;if(Ns=s,Vs){Ps?.cancel(),Ps=null,o!==Hs&&(Hs=o,o?i_(K,_t,null):r_(K,_t,Vs)),Qg(K,_t,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Fs){Ps=c_(_t,e=>{Ps===e&&(Ps=null),!Ns&&!Vs&&(Qg(K,_t,!1),Po()),e?.cancel()});return}if(Ps){if(!s&&!o)return;Ps.cancel(),Ps=null}let l=!_t.hidden;Qg(K,_t,s),!s&&l&&Po()},Ws=[],Gs=[],Ks=!1,Js=null,Ys,Xs=()=>{Gs.length=0;let e=Ws.splice(0,Ws.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Q.push(Xs);let Zs=(e,t)=>{let n=Uh(e,t);if(!n)return r.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),z(`span`);let i=r.suggestions?.starters,a=qh({item:{...n,behavior:n.behavior??i?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:i?.variant??`card`,streaming:m?$.isStreaming():!1,config:r,plugins:d,chipsConfig:r.suggestionChipsConfig,session:$,getTextarea:()=>J,eventTarget:_t,submitPrompt:Sl});return Gs.push(a),a},Qs=()=>{if(Ks)return;Ks=!0;let e=mn();Js=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,Ys=e.icon;try{Xs(),i_(K,_t,Vs),Vs=null,Hs=!1;let t=$?$.getMessages():r.initialMessages,n=h_(e,t),i=0,a=null;for(let t of d)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>_t,sendMessage:e=>{if(!$||$.isStreaming())return;let t=e.trim();t&&$.sendMessage(t)},requestRender:()=>Qs(),renderStarter:e=>Zs(e,i++),storage:g(t.id),onCleanup:e=>{Ws.push(e)}}),a))break;a&&a!==_t&&(Vs=a,r_(K,_t,a))}finally{Ks=!1}Us()},$s=()=>{let e=mn();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==Js||e.icon!==Ys)&&Qs()},ec=()=>{Us(),er||(J.placeholder=Ff(Z.getState().activeModeIds,r.composer?.modes)??r.copy?.inputPlaceholder??`How can I help...`,!(r.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(Y.textContent=r.copy?.sendButtonLabel??`Send`)),J.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,J.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},tc=!!r.setStoredConversationId,nc=e=>se(t=>{let n={...t};return delete n[e],n}),rc=e=>{let t=M[e];return typeof t==`string`?t:null},ic=()=>{let e=M.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};r.clientToken&&(r={...r,getStoredSessionId:()=>rc(`sessionId`),setStoredSessionId:e=>{se(t=>({...t,sessionId:e}))},clearStoredSessionId:r.clearStoredSessionId??(()=>nc(`sessionId`)),getStoredConversationId:r.getStoredConversationId??(()=>rc(`conversationId`)),setStoredConversationId:r.setStoredConversationId??(e=>{se(t=>({...t,conversationId:e}))}),clearStoredConversationId:r.clearStoredConversationId??(()=>nc(`conversationId`))});let oc=()=>r.clientToken??null,sc=e=>IS(e,Te(),r.persistState===!1),cc=oc(),lc=cc?sc(cc):null,uc=()=>{let e=M.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},dc={...lc?{visitorStore:lc}:{},historyBootstrapReady:r.features?.history?.enabled===!0&&!vw()?Promise.all([F,ne]).then(()=>{}):F,getStoredMessageCursor:()=>rc(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?nc(`historyMessageCursor`):se(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:uc,setPendingDisplayProjections:e=>{e?se(t=>({...t,pendingDisplayProjections:e})):nc(`pendingDisplayProjections`)},getStoredResumableHandle:ic,setStoredResumableHandle:e=>{e?se(t=>({...t,durableResume:e})):nc(`durableResume`)},shouldResumeDurableConversation:()=>j&&ic()!==null,...tc?{}:{getStoredConversationRevision:()=>rc(`conversationRevision`),setStoredConversationRevision:e=>{e===null?nc(`conversationRevision`):se(t=>({...t,conversationRevision:e}))}}};if(j){let t=r.onExecutionState,n=e.ownerDocument.defaultView,i=!1,a=()=>i=!0,o=()=>i=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Q.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),r={...r,reconnectStream:r.reconnectStream??(e=>$.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!i)&&dc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let fc=()=>{let e=oc();if(e&&lc?.matches(e,Te(),r.persistState===!1)||!e&&!lc)return;lc?.destroy(),lc=e?sc(e):null;let t={...dc};lc?t.visitorStore=lc:delete t.visitorStore,dc=t,$.setHistoryInternals(dc)},pc=null,mc=()=>{pc??=setInterval(()=>{let e=q.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(pc),pc=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?Ze(t-n):un(t-n))})},100)},hc=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>hc(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&hc(n[e],r[e]))},gc=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},_c=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!Sw(e),vc=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&_c(r)&&_c(i)&&hc(gc(r),gc(i))},yc=null,bc=null,xc=null,Sc=null,Cc=null,wc=e=>{if(!j)return qa(e);Cc=e,queueMicrotask(()=>{Cc===e&&(Cc=null,qa(e))})},Tc=e=>{yc=e;let t,n;bc=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!bc&&_c(i)&&(bc={index:r,id:i.id}),t&&n&&bc)break}rs(q,e,ye),yx()?.updateInlineArtifactBlocks(q,Wr.artifacts,{suppressTransition:ea}),mc(),Us(e),Zi(e),vo(!ea),qo(e),e.length===0&&(Ao(),xa=!0,Sa=!1,Ca=null,Ta=!1),!va||ya?(va=!0,ba=t?.id??null,Da=n?.id??null):t&&t.id!==ba?(ba=t.id,Io(t.id)):n&&n.id!==Da&&Lo(),n&&(Da=n.id),Uo(e);let r=Pa.lastUserMessageId;t&&t.id!==r&&(Pa.lastUserMessageId=t.id,k.emit(`user:message`,t)),Pa.lastUserMessageWasVoice=!!t?.viaVoice,wc(e),gs()},Ec=()=>{Sc!==null&&(cancelAnimationFrame(Sc),Sc=null);let e=xc;xc=null,e&&Tc(e)},Dc=()=>{Sc!==null&&cancelAnimationFrame(Sc),Sc=null,xc=null},Oc=e=>{let t=xc??yc;ea&&t&&bc&&vc(t,e,bc)?(xc=e,Sc===null&&(Sc=requestAnimationFrame(()=>{Sc=null;let e=xc;xc=null,e&&Tc(e)}))):e.length===0?(Dc(),Tc(e)):(Ec(),Tc(e))};$=new Id(r,{onMessagesChanged(e){Oc(e)},onStatusChanged(e){let t=r.statusIndicator??{};tt(gt,(e=>e===`idle`?t.idleText??Lr.idle:e===`connecting`?t.connectingText??Lr.connecting:e===`connected`?t.connectedText??Lr.connected:e===`error`?t.errorText??Lr.error:e===`paused`?t.pausedText??Lr.paused:e===`resuming`?t.resumingText??Lr.resuming:Lr[e])(e),t,e),qe()},onStreamingChanged(e){e||($?.getMessages().length===0?Dc():Ec()),ea=e,ks(e),qe(),$&&rs(q,$.getMessages(),ye),e||(vo(!0),ko(),Yi=!0,$&&Xi($.getMessages(),jr(r))),mo(),fn(e?`Responding…`:`Response complete.`),gs()},onVoiceStatusChanged(e){if(k.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!ot(r.voiceRecognition?.provider))return;let t=$.getVoiceNotice();switch(t&&dl(t,1e4),e){case`listening`:if(!Ma){let e=$.getVoiceDisclosure();e&&(Ma=!0,ge()?(Na=J.placeholder,J.placeholder=e,fn(e)):dl(e,1e4))}lu(),ou();break;case`processing`:lu(),su();break;case`speaking`:lu(),cu();break;default:e===`idle`&&$.isBargeInActive()?(lu(),ou(),X?.setAttribute(`aria-label`,`End voice session`)):(Pa.active=!1,Ma=!1,Na!==null&&(J.placeholder=Na,Na=null),lu(),za(`system`),Ra||Ba())}},onArtifactsState(e){Wr=e,e.artifacts.length===0&&(Jr=!1),yx()?.updateInlineArtifactBlocks(q,e.artifacts,{suppressTransition:ea}),xi(),qa()},onHistoryStateChanged(e){Ge(e)},onHistoryNotice(e){Ke(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?k.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?k.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):k.emit(`stream:resumed`,{executionId:t,after:n})}},dc),Zr.current=$,Q.push(()=>$.cancel()),Q.push(()=>{$.destroy(),lc?.destroy(),lc=null});let kc=null;if($.onReadAloudChange((e,t)=>{Ar=e,Mr=t,Fr();let n=e??kc;e&&(kc=e);let r=n?$.getMessages().find(e=>e.id===n)??null:null;k.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(kc=null)}),m=!0,va=!0,r.voiceRecognition?.enabled===!0&&ot(r.voiceRecognition.provider))try{$.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Ac=null,jc=null,Mc=!1,Nc=$.getHistoryState(),Pc=()=>r.features?.history?.enabled===!0,Fc=e=>{e&&(cn.textContent=``,cn.textContent=e)},Ic=()=>{p.forEach(e=>e()),p=[];let t=Ac,n=t?.railCollapseShortcut();t&&n&&p.push(f.register({id:`history-rail-collapse`,combo:n.combo,scope:r.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>Ve&&He===`rail`&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of r.layout?.header?.trailingActions??[])t.shortcut&&p.push(f.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let n=e.querySelector(`[data-persona-header-action="${t.id}"]`);n?n.click():r.layout?.header?.onAction?.(t.id)}}));for(let e of d)for(let t of e.shortcuts??[])p.push(f.register({...t,id:`${e.id}:${t.id}`}))};Ic();let Lc=null,Rc=!1,zc=()=>{if(!Et)return;let e=r.layout?.header?.titleSource===`conversation`,t=e&&Lc?.trim()||null;Et.textContent=t??r.launcher?.title??`Chat Assistant`;let n=Et.closest(`.persona-combo-btn`);if(!n)return;let i=!e||$.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,i?`false`:`true`),n.setAttribute(`aria-haspopup`,i?`true`:`false`),i||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=i?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=i?``:`none`)},Bc=e=>{e!==Lc&&(Lc=e,zc())},Vc=e=>{Rc=e?.starred===!0,Bc(e&&e.title.trim()||null),zc()};zc(),G.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=$.getActiveConversationId();n&&(t===`delete`?Gc(e=>e.requestDeleteConversation(n)):t===`star`&&$.canUpdateConversations()&&Gc(e=>e.updateHistoryConversation(n,{starred:!Rc})).catch(()=>{}))}),Ge=e=>{Nc=e,Ac?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),ks(e.sendBlocked||ea),Ac?.syncEarlierMessagesPill()},Ke=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(ta.clear(),Ao(),go()),Fc(e.message),Ac?.historySurface?.view.refresh()};let Hc={get actionManager(){return L},get activeConversationTitle(){return Lc},announceHistory:Fc,get applyRailChrome(){return We},set applyRailChrome(e){We=e},get artifactSplitRoot(){return si},get body(){return K},get config(){return r},get container(){return G},get conversationOpenPendingEl(){return js},set conversationOpenPendingEl(e){js=e},get conversationOpenTakeover(){return Ms},set conversationOpenTakeover(e){Ms=e},currentKeyPrefix:Te,destroyCallbacks:Q,eventBus:k,get footer(){return kt},get header(){return Ot},get historyChromeSync(){return qe},set historyChromeSync(e){qe=e},historyFeatureEnabled:Pc,get historyInternals(){return dc},set historyInternals(e){dc=e},get historyPresentation(){return He},set historyPresentation(e){He=e},get historySessionState(){return Nc},get historyVisible(){return Ve},set historyVisible(e){Ve=e},get isStreaming(){return ea},jumpToBottomInstant:So,get lastAppliedMessages(){return yc},set lastAppliedMessages(e){yc=e},get launcherEnabled(){return R},get launcherSurfaceInstance(){return wu},maybeFocusInput:As,messageCache:ta,get messagesWrapper(){return q},mount:e,get open(){return V},panel:W,panelElements:ct,get persistentMetadata(){return M},set persistentMetadata(e){M=e},plugins:d,get reapplyHistoryHostChrome(){return Ue},set reapplyHistoryHostChrome(e){Ue=e},repinAnchoredMessage:Po,resetAnchorState:Ao,restoreScrollPosition:Eo,resumeAutoScroll:go,runStorageMutation:Ka,get session(){return $},setActiveConversationSummary:Vc,storageAdapter:A,get suppressScrollSend(){return ya},set suppressScrollSend(e){ya=e},syncScrollToBottomButton:mo,updateWelcome:Us,getHistoryProviderFactory:yw,historyErrors:{HistoryClientError:Ja,HistoryProviderError:ro},isDockedMountMode:zh,renderLucideIcon:U,loadHistoryView:ZC,createHeaderIconButton:$h,attachTooltip:yo},Uc=e=>(!Ac&&!Mc&&(Ac=e.createHistoryShell(Hc),Ac.railCollapseShortcut()&&Ic()),Ac),Wc=()=>{if(Ac)return Promise.resolve(Ac);let e=vw();return e?Promise.resolve(Uc(e)):(jc??=_w().then(Uc,e=>{throw jc=null,e}),jc)},Gc=e=>{let t=vw(),n=Ac??(t?Uc(t):null);return n?e(n):Wc().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},qc=()=>{Ac?.syncHistoryPresentation()};Q.push(()=>{Mc=!0}),Pc()&&Wc().catch(()=>{}).finally(te),r.clientToken&&(r.features?.history?.enabled===!0||r.sessionInit===`mount`)&&$.initClientSession().then(()=>{let e=Ac;if(e?.historyAvailable())return $.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Ac?.syncEarlierMessagesPill()}).catch(e=>{r.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Jc=()=>$.warmClientSession(),Yc=e=>{let t=r.sessionInit??`input`,n=rr?.input??J,i=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&i===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?i===n&&e.key===`Tab`:(rr?.form??ht)?.contains(i)))&&Jc()},Xc=[`input`,`pointerdown`,`keyup`];Xc.forEach(t=>e.addEventListener(t,Yc));let Zc,Qc,$c=()=>{let e=Qc;Qc=void 0;try{typeof e==`function`&&e()}catch{}},el=()=>{let t=r.clientToken&&typeof r.sessionInit==`function`?r.sessionInit:void 0;if(t!==Zc){$c(),Zc=t;try{Qc=t?.({warm:Jc,mount:e})}catch{}}};el(),Q.push(()=>{Xc.forEach(t=>e.removeEventListener(t,Yc)),$c()}),(Se||r.onSSEEvent)&&$.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),ze(e,t)});let tl=()=>{let e=r.resume??(j?dc.getStoredResumableHandle?.():null);e&&typeof r.reconnectStream==`function`&&$.resumeFromHandle(e)};ee?ee.then(e=>{if(e){if(e.metadata&&(M=Fw(e.metadata),L.syncFromMetadata()),e.messages?.length){ya=!0;try{$.hydrateMessages(e.messages)}finally{ya=!1}ns()}e.artifacts?.length&&$.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),eo(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Fs=!0,P(),tl()}):(eo(I),tl());let nl=()=>{ge()&&(V||(r.launcher?.composerBar?.expandOnSubmit??!0)&&ys(!0,`auto`))},rl=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Bw(i)}}:e:t,il=()=>{let e=J.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},sl=!1,cl=null,ll=()=>{J.value=``,J.style.height=`auto`,wn(),Ol()},ul=null;function dl(e,t=4e3){fn(e),!ge()&>&&(gt.hasAttribute(Ow)||(gt.setAttribute(kw,``),gt.setAttribute(`role`,`status`),gt.setAttribute(`aria-live`,`polite`),gt.textContent=e,nt(gt,r.statusIndicator??{},`idle`),ul&&clearTimeout(ul),ul=setTimeout(()=>{if(ul=null,gt?.hasAttribute(kw)&&(gt.removeAttribute(kw),gt.removeAttribute(`role`),gt.removeAttribute(`aria-live`),m)){let e=$.getStatus();tt(gt,Qe(e),r.statusIndicator??{},e)}},t)))}function fl(){let e=Z.getState().pendingSubmission;e&&(Un(void 0),J&&(J.value=e.text,J.dispatchEvent(new Event(`input`,{bubbles:!0})),wn()),e.options.selectedModelId&&(Z.setSelectedModelId(e.options.selectedModelId),Nn?.repaint()),e.options.activeModeIds?.length&&jn(e.options.activeModeIds),e.options.quote&&Rn(e.options.quote),J?.focus())}let pl=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},ml=(e={})=>{let t=(e.overrideText??J?.value??``).trim();return e.resolveInlineCommand&&t?(Cn?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>hl(e,t,n)):hl(e,t,null)},hl=(e,t,n)=>{if(n?.kind===`action`){ll(),Cn?.clear(),Tn();return}let i=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!qf({text:a,hasAttachments:(Sn?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:Sn?.isReady()??!0,hasMentions:Cn?.hasMentions()??!1,hasServerMentions:!!i,inputDisabled:xs(),sendDisabled:Cs()}))return;let s=$.isStreaming()?Bn():`block`;if(s===`defer-one`&&!e.pending){if(Z.getState().pendingSubmission){dl(`One message is already queued. Edit or remove it first.`);return}gl({intent:e,sendText:a,serverMentions:i});return}let c={text:a,mentionRefs:[...Cn?.getMentionRefs()??[],...i?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:il(),options:{...Z.getState().selectedModelId&&{selectedModelId:Z.getState().selectedModelId},...Z.getState().activeModeIds.length>0&&{activeModeIds:[...Z.getState().activeModeIds]},...Z.getState().quote&&{quote:{...Z.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!Sn?.hasAttachments())return;let e=[...Sn.getContentParts()];return c.text&&e.push(wa(c.text)),e};c.contentParts=l();let u=()=>{sa(),nl();let t=Cn?.collectForSubmit()??null,n=rl(t,i),a=l();e.consumeDraft!==!1&&ll();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&$.cancel(),$.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),Sn?.hasAttachments()&&Sn.clearAttachments(),t&&Cn?.clear(),Tn();let d=Z.getState().activeModeIds,f=Pf(d,r.composer?.modes);f.length!==d.length&&jn(f),Z.getState().quote&&Rn(void 0),to(),br.release(),Sr()},d=r.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;cl=f;let p=e=>{cl=null,e.status===`error`?pl(e.error):e.status===`proceed`&&u()},m=Xf(d,c,f.signal);if(!(m instanceof Promise))p(m);else return Z.setPreparing(!0),m.then(p).finally(()=>Z.setPreparing(!1))};function gl(e){let t=Z.getState(),n=Sn?.hasAttachments()??!1,r=n?[...Sn.getContentParts()]:[];n&&e.sendText&&r.push(wa(e.sendText)),Un(Kf({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...Cn?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:il(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&ll(),n&&Sn.clearAttachments(),Cn?.clear(),Tn(),t.quote&&Rn(void 0),to(),br.release(),Sr(),fn(`Message queued. It sends when the response finishes.`)}function _l(){let e=Z.getState().pendingSubmission;e&&(Un(void 0),Cl(e.text,{consumeDraft:!1,pending:e}))}function vl(e){if(r.messageActions?.showEdit!==!0)return;let t=$.getMessages().find(t=>t.id===e);t&&Nl(t)&&aa!==e&&(sa(),aa=e,oa=zf({messageId:e,initialText:t.content,onSave:t=>yl(e,t),onCancel:()=>sa()}),ta.delete(e),rs(q,$.getMessages(),ye),oa.focus())}function yl(e,t){let n=oa;aa=null,oa=null,n?.destroy(),ta.delete(e),$.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Po():rs(q,$.getMessages(),ye)}function bl(e){if($.isStreaming())return;let t=jl($.getMessages(),e);t&&(sa(),$.resubmitFrom(t,{reason:`retry`})&&Po())}Ir={regenerate:bl,edit:vl,quote:e=>{let t=$.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Rn({text:t,messageId:e}),J?.focus())}};let xl=async e=>{if(!sl){sl=!0;try{await ml({resolveInlineCommand:!0,...e})}finally{sl=!1}}};function Sl(e){Cs()||(ll(),Cl(e,{consumeDraft:!1}))}let Cl=(e,t)=>{if(sl)return;sl=!0;let n=()=>{sl=!1};try{let r=ml({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},wl=e=>{e.preventDefault(),$.isStreaming()?($.cancel(),Ae?.reset(),Ne?.update()):sl||xl()},Tl=()=>r.features?.composerHistory!==!1,El={...lm},Dl=!1,Ol=()=>{El={...lm}},kl=()=>$.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Al=e=>{if(!J)return;Dl=!0,J.value=e,J.dispatchEvent(new Event(`input`,{bubbles:!0})),Dl=!1;let t=J.value.length;J.setSelectionRange(t,t)},Pl=e=>{Dl||(e.isComposing||Cn?.handleInput(e.inputType??void 0),Ol())},Fl=()=>({submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:Bo(J)}),Il=e=>{if(J&&!xs()&&(e.isComposing||!Cn?.handleKeydown(e))){if(Tl()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=J.selectionStart===0&&J.selectionEnd===0,n=um({direction:e.key===`ArrowUp`?`up`:`down`,history:kl(),currentValue:J.value,atStart:t,state:El});if(El=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Al(n.value);return}}if(Ho(e,Fl())){if($.isStreaming()){if(e.preventDefault(),Bn()===`block`||sl||Cs())return;Ol(),xl()}else sl||Cs()?e.preventDefault():(Ol(),e.preventDefault(),Y.click())}}},Ll=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(G)&&(cl?(cl.abort(),cl=null,e.preventDefault(),e.stopImmediatePropagation()):$.isStreaming()&&($.cancel(),Ae?.reset(),Ne?.update(),Ol(),e.preventDefault(),e.stopImmediatePropagation()))},Rl=async e=>{if(r.attachments?.enabled!==!0||!Sn||xs())return;let t=jw(e.clipboardData);t.length!==0&&(e.preventDefault(),await Sn.handleFiles(t))},zl=null,Bl=!1,Vl=null,Hl=null,Ul=()=>r.voiceRecognition?.completionBehavior===`review`;function Wl(e){X?.setAttribute(`data-state`,e),e===`recording`?$l():eu()}let Gl=`--persona-voice-level`,Kl=.5,ql=null,Jl=-1,Yl=0,Xl=()=>{let e=[],t=Lt??X?.parentElement??null;return t&&e.push(t),kt&&e.push(kt),e},Zl=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Jl){Jl=t;for(let e of Xl())e.style.setProperty(Gl,String(t))}},Ql=()=>{Jl=-1,Yl=0;for(let e of Xl())e.style.removeProperty(Gl)};function $l(){if(ql!==null)return;if(typeof requestAnimationFrame!=`function`){Zl(m?$.getVoiceLevel()??Kl:Kl);return}let e=()=>{ql=requestAnimationFrame(e);let t=m?$.getVoiceLevel():null;t===null?Zl(Kl):(Yl+=(t-Yl)*.3,Zl(Yl))};ql=requestAnimationFrame(e)}function eu(){ql!==null&&(cancelAnimationFrame(ql),ql=null),Ql()}let tu=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,nu=(e=`user`)=>{if(Bl||$.isStreaming())return;let t=tu();if(!t)return;zl=new t;let n=r.voiceRecognition??{},i=n.pauseDuration??2e3;zl.continuous=n.provider?.browser?.continuous??!0,zl.interimResults=!0,zl.lang=n.provider?.browser?.language??`en-US`;let a=J.value;zl.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let r=a+t+n;J.value=r,wn(),Vl&&clearTimeout(Vl),(t||n)&&(Vl=window.setTimeout(()=>{if(J.value.trim()&&zl&&Bl){if(ru(),Ul())return;xl({viaVoice:!0})}},i))},zl.onerror=e=>{e.error!==`no-speech`&&ru()},zl.onend=()=>{if(Bl){let e=J.value.trim();!Ul()&&e&&e!==a.trim()&&xl({viaVoice:!0}),ru()}};try{if(zl.start(),Bl=!0,Pa.active=!0,e!==`system`&&(Pa.manuallyDeactivated=!1),za(e),Ba(),Sr(),X){let e=r.voiceRecognition??{};Hl={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,i=e.recordingBorderColor;if(X.classList.add(`persona-voice-recording`),Wl(`recording`),X.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,X.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=X.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}i&&(X.style.borderColor=i),X.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{ru(`system`)}},ru=(e=`user`)=>{if(Bl){if(Bl=!1,Vl&&=(clearTimeout(Vl),null),zl){try{zl.stop()}catch{}zl=null}if(Pa.active=!1,za(e),Ba(),Sr(),X){if(X.classList.remove(`persona-voice-recording`),Wl(`idle`),Hl){X.style.backgroundColor=Hl.backgroundColor,X.style.color=Hl.color,X.style.borderColor=Hl.borderColor;let e=X.querySelector(`svg`);e&&e.setAttribute(`stroke`,Hl.color||`currentColor`),Hl=null}X.setAttribute(`aria-label`,`Start voice recognition`)}}},iu=null,au=e=>{let t=t=>{iu??=t.createMicStateStyles({mic:()=>X,config:()=>r,session:()=>$,get original(){return Hl},set original(e){Hl=e},setMicState:Wl,renderIcon:U,iconFallbackPx:24}),e(iu)},n=dd();n?t(n):ud().then(t,()=>{})},ou=()=>au(e=>e.recording()),su=()=>au(e=>e.processing()),cu=()=>au(e=>e.speaking()),lu=()=>au(e=>e.reset()),uu=()=>{if(!xs()){if(ot(r.voiceRecognition?.provider)){let e=$.getVoiceStatus(),t=$.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Pa.active=!1,Pa.manuallyDeactivated=!0,Ba(),za(`user`),lu()});return}$.toggleVoice().then(()=>{Pa.active=La(),Pa.manuallyDeactivated=!Pa.active,Ba(),za(`user`),Pa.active?ou():lu()})}else if(Bl){let e=J.value.trim();Pa.manuallyDeactivated=!0,Ba(),ru(`user`),e&&!Ul()&&xl()}else Pa.manuallyDeactivated=!1,Ba(),nu(`user`)}};qn=uu;let du=()=>$.prewarmVoice(),fu=()=>{let e=r.voiceRecognition;return e?.enabled===!0?e.prewarm??(r.clientToken?`hover`:!1):!1},pu=e=>{fu()===`hover`&&X?.contains(e.target)&&du()},mu=[`pointerover`,`pointerdown`,`focusin`];mu.forEach(t=>e.addEventListener(t,pu));let hu,gu=null,_u,vu=()=>{let e=_u;_u=void 0;try{typeof e==`function`&&e()}catch{}},yu=()=>{let t=fu(),n=typeof t==`function`&&X?t:void 0,r=n?X:null;if((n!==hu||r!==gu)&&(vu(),hu=n,gu=r,n&&r))try{_u=n({warm:du,micButton:r,mount:e})}catch{}};yu(),Q.push(()=>{mu.forEach(t=>e.removeEventListener(t,pu)),vu()}),X&&Q.push(()=>{ot(r.voiceRecognition?.provider)?($.isVoiceActive()&&$.toggleVoice(),lu()):ru(`system`)});let bu=k.on(`assistant:complete`,()=>{Z.getState().pendingSubmission&&setTimeout(()=>{$.isStreaming()||_l()},0)});Q.push(bu);let xu=k.on(`assistant:complete`,()=>{Fa&&(Pa.active||Pa.manuallyDeactivated||(Fa!==`assistant`||Pa.lastUserMessageWasVoice)&&setTimeout(()=>{!Pa.active&&!Pa.manuallyDeactivated&&(ot(r.voiceRecognition?.provider)?$.toggleVoice().then(()=>{Pa.active=$.isVoiceActive(),za(`auto`),$.isVoiceActive()&&ou()}):nu(`auto`))},600))});Q.push(xu);let Su=k.on(`action:resubmit`,()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Q.push(Su);let Cu=()=>{ys(!V,`user`)},wu=null,Tu=null;if(R&&!ge()){let{instance:e,element:t}=F_({config:r,plugins:d,onToggle:Cu});wu=e,e||(Tu=t)}wu?e.appendChild(wu.element):Tu&&e.appendChild(Tu),vs(),Zi(),ec(),Qs(),ks($.isStreaming()),Eo()||(Kt()===`follow`?vo(!0):So()),Va(),de&&(!R||ge()?setTimeout(()=>As(),0):V&&setTimeout(()=>As(),200));let Eu=null,Du=()=>{Eu&&(Eu.disconnect(),Eu.observe(kt),Eu.observe(G),Eu.observe(_t))},Ou=pn(),ku=()=>{if(ge()){vn(),vs();return}let t=zh(r),n=r.launcher?.sidebarMode??!1,i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640,s=i.innerWidth<=o,c=a&&s&&R;try{if(c){Vr(),Hr=bi();return}let e=!1;he&&(he=!1,Vr(),e=!0);let i=bi();if(!e&&i!==Hr&&(Vr(),e=!0),Hr=i,e&&di(),!R&&!t){W.style.height=``,W.style.width=``;return}if(!n&&!t){let e=__(r);W.style.width=e.width,W.style.maxWidth=e.maxWidth}vi(),Di()}finally{vn(),bn();let t=pn();if(t!==Ou&&(Ou=t,Us(),Zi()),vs(),V&&R){let t=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),n=r.launcher?.sidebarMode??!1,i=r.launcher?.mobileFullscreen??!0,a=zh(r)&&i&&t,o=n||i&&t&&R||a;if(o&&!ki){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&!Oi&&(Oi=Ph(n,r.launcher?.zIndex??1e5)),ki=Lh(e.ownerDocument)}else o||(Oi?.(),Oi=null,ki?.(),ki=null)}}};ku();let Au=e.ownerDocument.defaultView??window;if(Au.addEventListener(`resize`,ku),Q.push(()=>Au.removeEventListener(`resize`,ku)),typeof ResizeObserver<`u`){Eu=new ResizeObserver(()=>{bn()}),Du(),Q.push(()=>{Eu?.disconnect(),Eu=null});let e=new ResizeObserver(()=>{qc()});e.observe(G),Q.push(()=>e.disconnect())}Au.addEventListener(`resize`,qc),Q.push(()=>Au.removeEventListener(`resize`,qc)),da=K.scrollTop;let ju=vm(K),Mu=()=>{Ti();let e=K.scrollTop,t=vm(K),n=t<ju;if(ju=t,!qt()){da=e,mo();return}let{action:r,nextLastScrollTop:i}=bm({following:ua.isFollowing(),currentScrollTop:e,lastScrollTop:da,nearBottom:ym(K,24),userScrollThreshold:4,isAutoScrolling:pa||ma||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});da=i,r===`resume`?To()||go():r===`pause`&&ho()};if(K.addEventListener(`scroll`,Mu,{passive:!0}),Q.push(()=>K.removeEventListener(`scroll`,Mu)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Fo(),It(q)});e.observe(q),e.observe(K),Q.push(()=>e.disconnect())}let Nu=()=>{qt()&&ua.isFollowing()&&To()&&ho()},Pu=K.ownerDocument;Pu.addEventListener(`selectionchange`,Nu),Q.push(()=>{Pu.removeEventListener(`selectionchange`,Nu)});let Fu=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Iu=e=>{Fu.has(e.key)&&(Ea(),Xt()&&qt()&&ua.isFollowing()&&ho())},Lu=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(Ea(),Xt()&&qt()&&ua.isFollowing()&&ho())};K.addEventListener(`keydown`,Iu),K.addEventListener(`focusin`,Lu),Q.push(()=>{K.removeEventListener(`keydown`,Iu),K.removeEventListener(`focusin`,Lu)});let Ru=e=>{if(e.deltaY!==0&&Ea(),!qt())return;let t=xm({following:ua.isFollowing(),deltaY:e.deltaY,nearBottom:ym(K,24),resumeWhenNearBottom:!0});t===`pause`?ho():t===`resume`&&!To()&&go()};K.addEventListener(`wheel`,Ru,{passive:!0}),K.addEventListener(`touchmove`,Ea,{passive:!0}),K.addEventListener(`pointerdown`,Ea,{passive:!0}),Q.push(()=>{K.removeEventListener(`touchmove`,Ea),K.removeEventListener(`pointerdown`,Ea)}),Q.push(()=>K.removeEventListener(`wheel`,Ru)),tn.addEventListener(`click`,()=>{Ao(),K.scrollTop=K.scrollHeight,da=K.scrollTop,go(),vo(!0),mo()}),Q.push(()=>tn.remove()),Q.push(()=>{oo(),Ao()});let zu=()=>{wt&&(zi&&=(wt.removeEventListener(`click`,zi),null),B()?(wt.style.display=``,zi=()=>{ys(!1,`user`)},wt.addEventListener(`click`,zi)):wt.style.display=`none`)};zu(),(()=>{let{clearChatButton:e}=ct;e&&e.addEventListener(`click`,()=>{let e=Ac;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{r.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}$.clearMessages(),r.layout?.topFade&&(K.scrollTop=0),K.removeAttribute(`data-persona-top-fade`),ta.clear(),go(),_r(ct.composerOverlay);try{localStorage.removeItem(Dw),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Dw}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Dw)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),A?.clear&&Ka(()=>A.clear(),`[AgentWidget] Failed to clear storage adapter:`),M={},L.syncFromMetadata(),Sn?.clearAttachments(),to(),Un(void 0),Rn(void 0),sa(),ke?.clear(),Ae?.reset(),Ne?.update()})})();let Bu=[[`keydown`,Il],[`input`,Pl],[`input`,wn],[`input`,Tn],[`keyup`,Tn],[`paste`,Rl],[`focus`,ur]],Vu=e=>{if(e)for(let[t,n]of Bu)rr?.addListener(e,t,n)},Hu=e=>{if(e)for(let[t,n]of Bu)rr?.removeListener(e,t,n)},Uu=()=>{rr&&(rr.addListener(rr.form,`submit`,wl),rr.addListener(rr.footer,`click`,Tn),Vu(J),X&&rr.addListener(X,`click`,uu),yu())};Uu();let Wu=()=>{Cn?.onComposerSwap((e,t)=>{Hu(t),J=e,rr&&(rr.input=e),Vu(e),ar(),Os(),wn()})};Wu();let Gu=!1;function Ku(){if(!Gu){Gu=!0;try{let e=J?.value??``,t=kt.ownerDocument??document,n=J?t.activeElement===J:!1;eu(),rr?.destroy(),rr=null,Cn?.destroy(),Cn=null;let i=null,a=()=>(i=ge()?Sg({config:r}):bg({config:r}),i.footer),o=tr(a)??a();it.replaceComposer(o),kt=it.composer.footer;let s=i!==null&&o===i.footer;er=!s,Pt=s?i.setSendButtonMode:()=>{},$n(kt),or(kt),cr(),lr(),dr(),Wu(),hr(),vr(),yr(),Uu();let c=Ri.indexOf(Fi);if(Fi.destroy(),Fi=Jh(dt),c>=0&&(Ri[c]=Fi),J&&(J.value=e),wn(),Tn(),ec(),Zi(),ks($.isStreaming()),r.statusIndicator?.mode===`transient`&&!ge()){let e=$.getStatus();tt(gt,Qe(e),r.statusIndicator,e)}Pa.active&&Wl(`recording`),Vr(),Du(),vn(),Sr(),Es(),n&&J?.focus()}finally{Gu=!1}}}let qu=e.ownerDocument??document;qu.addEventListener(`keydown`,Ll,!0);let Ju=()=>{$a()},Yu=()=>{qu.visibilityState===`hidden`&&$a()};typeof window<`u`&&(window.addEventListener(`pagehide`,Ju),qu.addEventListener(`visibilitychange`,Yu),Q.push(()=>{window.removeEventListener(`pagehide`,Ju),qu.removeEventListener(`visibilitychange`,Yu)}));let Xu=`persona-attachment-drop-active`,Zu=0,Qu=()=>{Zu=0,G.classList.remove(Xu)},$u=()=>r.attachments?.enabled===!0&&Sn!==null&&!xs(),ed=e=>{Mw(e.dataTransfer)&&$u()&&(Zu++,Zu===1&&G.classList.add(Xu))},td=e=>{Mw(e.dataTransfer)&&$u()&&(Zu--,Zu<=0&&Qu())},nd=e=>{Mw(e.dataTransfer)&&$u()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},rd=e=>{if(!Mw(e.dataTransfer)||!$u())return;e.preventDefault(),e.stopPropagation(),Qu();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&Sn.handleFiles(t)};G.addEventListener(`dragenter`,ed,!0),G.addEventListener(`dragleave`,td,!0),e.addEventListener(`dragover`,nd,!0),e.addEventListener(`drop`,rd,!0);let id=e.ownerDocument,ad=e=>{$u()&&e.preventDefault()},od=e=>{$u()&&e.preventDefault()};id.addEventListener(`dragover`,ad),id.addEventListener(`drop`,od),Q.push(()=>{rr?.destroy(),rr=null,eu(),fr?.destroy(),fr=null,Fn?.destroy(),Fn=null,Ln?.destroy(),Ln=null,Vn?.destroy(),Vn=null,Nn=null,Pn=null,$a(),Za.destroy(),ul&&clearTimeout(ul),sa(),cl?.abort(),cl=null,Sn?.destroy(),Sn=null,Z.destroy(),qu.removeEventListener(`keydown`,Ll,!0),Cn?.destroy()}),Q.push(()=>{G.removeEventListener(`dragenter`,ed,!0),G.removeEventListener(`dragleave`,td,!0),e.removeEventListener(`dragover`,nd,!0),e.removeEventListener(`drop`,rd,!0),id.removeEventListener(`dragover`,ad),id.removeEventListener(`drop`,od),Qu()}),Q.push(()=>{$.cancel()}),wu?Q.push(()=>{wu?.destroy()}):Tu&&Q.push(()=>{Tu?.remove()});let sd={update(t){let n=r.future?.v5Defaults===!0,i=r.toolCall,a=r.messageActions,o=r.layout?.messages,s=r.colorScheme,f=r.loadingIndicator,p=r.iterationDisplay,m=r.features?.showReasoning,g=r.features?.showToolCalls,_=r.features?.toolCallDisplay,v=r.features?.reasoningDisplay,y=r.features?.streamAnimation?.type,b=r.features?.history?.enabled===!0,x=r.features?.history?.provider,S=r.getIdentityProof,C=r.clientToken,w=r.contextMentions;r=bS({...r,features:l},t),l=r.features,r=Qx(r),c(),Si(),Hp(e,r),Dx(e,r),Ox(e,r),We(),xi(),r.colorScheme!==s&&ji();let T=gS.getForInstance(r.plugins);d.length=0,d.push(...T),Ic(),R=r.launcher?.enabled??!0,ue=r.launcher?.autoExpand??!1,be=r.features?.showReasoning??!0,xe=r.features?.showToolCalls??!0,Ce=r.features?.scrollToBottom??{};let E=Kt();we=r.features?.scrollBehavior??{},E!==Kt()&&(Ao(),go()),ka(),xn(),mo();let D=Se;if(Se=r.features?.showEventStreamToggle??!1,Se&&!D){if(ke||(Be(),$.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),ze(e,t)})),!Qn&&Ot){let e=r.features?.eventStream?.classNames,t=`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`+(e?.toggleButton?` `+e.toggleButton:``);Qn=z(`button`,t),Qn.style.width=`28px`,Qn.style.height=`28px`,Qn.style.color=ng.actionIconColor,Qn.type=`button`,Qn.setAttribute(`aria-label`,`Event Stream`),Qn.title=`Event Stream`;let n=h(u.Activity,`18px`,`currentColor`,1.5);n&&Qn.appendChild(n);let i=ct.clearChatButtonWrapper,a=ct.closeButtonWrapper,o=i||a;o&&o.parentNode===Ot?Ot.insertBefore(Qn,o):Ot.appendChild(Qn),Qn.addEventListener(`click`,()=>{Fe?Zn():Xn()})}}else!Se&&D&&(Zn(),Qn&&=(Qn.remove(),null),ke?.clear(),De?.destroy(),ke=null,De=null,Ae?.reset(),Ae=null,je=null);if(r.launcher?.enabled===!1&&wu&&(wu.destroy(),wu=null),r.launcher?.enabled===!1&&Tu&&(Tu.remove(),Tu=null),r.launcher?.enabled!==!1&&!wu&&!Tu){let{instance:t,element:n}=F_({config:r,plugins:d,onToggle:Cu});wu=t,t||(Tu=n),e.appendChild(n)}wu&&wu.update(r),zc(),Dt&&r.launcher?.subtitle!==void 0&&(Dt.textContent=r.launcher.subtitle);let O=r.layout?.header;if(O?.layout!==me&&Ot){let e=O?yg(r,O,{showClose:B(),onClose:()=>ys(!1,`user`)}):ag({config:r,showClose:B(),onClose:()=>ys(!1,`user`)});it.replaceHeader(e),Ot=it.header.element,Tt=it.header.iconHolder,Et=it.header.headerTitle,Dt=it.header.headerSubtitle,wt=it.header.closeButton,me=O?.layout,zc()}else if(O){if(Tt&&(Tt.style.display=O.showIcon===!1?`none`:``),Et&&(Et.style.display=O.showTitle===!1?`none`:``),Dt&&(Dt.style.display=O.showSubtitle===!1?`none`:``),wt){let e=B()&&O.showCloseButton!==!1;wt.style.display=e?``:`none`}if(ct.clearChatButtonWrapper){let e=O.showClearChat;if(e!==void 0){ct.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=ct;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let A=r.layout?.showHeader!==!1;Ot&&(Ot.style.display=A?``:`none`);let j=r.layout?.showFooter!==!1;kt&&(kt.style.display=j?``:`none`),vn(),mo(),R===pe?ue!==fe&&ys(ue,`auto`):R?ys(ue,`auto`):(V=!0,vs()),fe=ue,pe=R,ku(),zu();let M=JSON.stringify(r.toolCall)!==JSON.stringify(i),ee=JSON.stringify(r.messageActions)!==JSON.stringify(a),N=JSON.stringify(r.layout?.messages)!==JSON.stringify(o),P=r.loadingIndicator?.render!==f?.render||r.loadingIndicator?.renderIdle!==f?.renderIdle||r.loadingIndicator?.showBubble!==f?.showBubble,F=r.iterationDisplay!==p,te=(r.features?.showReasoning??!0)!==(m??!0)||(r.features?.showToolCalls??!0)!==(g??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(_)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(v);(r.future?.v5Defaults===!0!==n||M||ee||N||P||F||te)&&$&&(ca++,rs(q,$.getMessages(),ye));let ne=r.features?.streamAnimation?.type;if(ne!==y&&ne&&ne!==`none`){let t=Ni(ne,r.features?.streamAnimation?.plugins);t&&Ym(t,e)}let I=r.launcher??{},re=I.headerIconHidden??!1,ie=r.layout?.header?.showIcon,oe=re||ie===!1,ce=I.headerIconName,le=I.headerIconSize??`40px`;if(Tt){let e=Ot,t=e?.querySelector(`.persona-flex-col`);if(oe)Tt.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Tt.style.display=``,Tt.style.height=le,Tt.style.width=le,e&&t&&(e.contains(Tt)?Tt.nextSibling!==t&&(Tt.remove(),e.insertBefore(Tt,t)):e.insertBefore(Tt,t)),ce){let e=parseFloat(le)||24,t=U(ce,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,Tt.replaceChildren(t)):Tt.textContent=I.agentIconText??`💬`}else if(I.iconUrl){let e=Tt.querySelector(`img`);if(e)e.src=I.iconUrl,e.style.height=le,e.style.width=le;else{let e=document.createElement(`img`);e.src=I.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=le,e.style.width=le,Tt.replaceChildren(e)}}else{let e=Tt.querySelector(`svg`),t=Tt.querySelector(`img`);(e||t)&&Tt.replaceChildren(),Tt.textContent=I.agentIconText??`💬`}let n=Tt.querySelector(`img`);n&&(n.style.height=le,n.style.width=le)}}let de=r.layout?.header?.showTitle,he=r.layout?.header?.showSubtitle;if(Et&&(Et.style.display=de===!1?`none`:``),Dt&&(Dt.style.display=he===!1?`none`:``),wt){let e=B()&&r.layout?.header?.showCloseButton!==!1;if(wt.style.display=e?``:`none`,!ge()){let e=I.closeButtonSize??``;wt.style.height=e,wt.style.width=e,wt.style.minWidth=e,wt.style.minHeight=e}let t=I.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=ct,i=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&i!==a){if(n.remove(),i){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Ac?.railColumn??G;e.style.position=`relative`,e.appendChild(n)}else{let e=I.clearChat?.placement??`inline`;n.className=(I.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,Ot&&Ot.appendChild(n)}}if(wt.style.color=I.closeButtonColor||ng.actionIconColor,I.closeButtonBackgroundColor?(wt.style.backgroundColor=I.closeButtonBackgroundColor,wt.classList.remove(`hover:persona-bg-gray-100`)):(wt.style.backgroundColor=``,wt.classList.add(`hover:persona-bg-gray-100`)),I.closeButtonBorderWidth||I.closeButtonBorderColor){let e=I.closeButtonBorderWidth||`0px`,t=I.closeButtonBorderColor||`transparent`;wt.style.border=`${e} solid ${t}`,wt.classList.remove(`persona-border-none`)}else wt.style.border=``,wt.classList.add(`persona-border-none`);I.closeButtonBorderRadius?(wt.style.borderRadius=I.closeButtonBorderRadius,wt.classList.remove(`persona-rounded-full`)):(wt.style.borderRadius=``,wt.classList.add(`persona-rounded-full`)),I.closeButtonPaddingX?(wt.style.paddingLeft=I.closeButtonPaddingX,wt.style.paddingRight=I.closeButtonPaddingX):(wt.style.paddingLeft=``,wt.style.paddingRight=``),I.closeButtonPaddingY?(wt.style.paddingTop=I.closeButtonPaddingY,wt.style.paddingBottom=I.closeButtonPaddingY):(wt.style.paddingTop=``,wt.style.paddingBottom=``),Qh(wt,I.closeButtonIconName??`x`,{iconSize:ge()?y_:void 0,iconText:I.closeButtonIconText??`×`});let o=I.closeButtonTooltipText??`Close chat`,s=I.closeButtonShowTooltip??!0;wt.setAttribute(`aria-label`,o),n&&yo({anchor:wt,trigger:n,text:()=>wt?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:H,clearChatButtonWrapper:_e}=ct;if(H){let e=I.clearChat??{},t=e.enabled??!0,n=r.layout?.header?.showClearChat,i=n===void 0?t:n,a=e.placement??`inline`;if(_e){_e.style.display=i?``:`none`;let{closeButtonWrapper:e}=ct;!ge()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=_e.classList.contains(`persona-absolute`);if(!ge()&&t!==n&&i){if(_e.remove(),t){_e.className=`persona-absolute persona-top-4 persona-z-50`,_e.style.right=`48px`;let e=Ac?.railColumn??G;e.style.position=`relative`,e.appendChild(_e)}else{_e.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,_e.style.right=``;let e=ct.closeButtonWrapper;Ot&&e&&e.parentElement===Ot?Ot.insertBefore(_e,e):Ot&&Ot.appendChild(_e)}let e=ct.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!ge()){let t=e.size??``;H.style.height=t,H.style.width=t,H.style.minWidth=t,H.style.minHeight=t}let t=e.iconColor??``;if(H.style.color=t||ng.actionIconColor,Qh(H,e.iconName??`refresh-cw`,{iconSize:ge()?b_:void 0}),e.backgroundColor?(H.style.backgroundColor=e.backgroundColor,H.classList.remove(`hover:persona-bg-gray-100`)):(H.style.backgroundColor=``,H.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;H.style.border=`${t} solid ${n}`,H.classList.remove(`persona-border-none`)}else H.style.border=``,H.classList.add(`persona-border-none`);e.borderRadius?(H.style.borderRadius=e.borderRadius,H.classList.remove(`persona-rounded-full`)):(H.style.borderRadius=``,H.classList.add(`persona-rounded-full`)),e.paddingX?(H.style.paddingLeft=e.paddingX,H.style.paddingRight=e.paddingX):(H.style.paddingLeft=``,H.style.paddingRight=``),e.paddingY?(H.style.paddingTop=e.paddingY,H.style.paddingBottom=e.paddingY):(H.style.paddingTop=``,H.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;H.setAttribute(`aria-label`,n),_e&&yo({anchor:H,trigger:_e,text:()=>H?.getAttribute(`aria-label`)??n,enabled:r})}}let Te=r.actionParsers&&r.actionParsers.length?r.actionParsers:[wS],Ee=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ES.message,ES.messageAndClick];L=OS({parsers:Te,handlers:Ee,getSessionMetadata:ae,updateSessionMetadata:se,emit:k.emit,documentRef:typeof document<`u`?document:null}),ye=Lw(r,L,ve),fc(),$.updateConfig(r),el(),(r.features?.history?.enabled===!0!==b||r.features?.history?.provider!==x||r.getIdentityProof!==S||r.clientToken!==C)&&(Ac?.closeHistory({restoreFocus:!1}),Ac?.installHistoryProvider()),Ac?.syncHistoryChromeImpl(),qc(),Pc()&&!Ac&&Wc().catch(()=>{}),rs(q,$.getMessages(),ye),Zi(),ec(),$s(),ks($.isStreaming()),w!==r.contextMentions&&Ku();let Oe=r.voiceRecognition?.enabled===!0,Me=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Ne=ot(r.voiceRecognition?.provider);if(Oe&&(Me||Ne)){if(!X||!Lt){let e=es(r);if(e){X=e.button,Lt=e.wrapper;let t=Nt&&Nt.parentElement===Mt?Nt:null;Mt?Mt.insertBefore(Lt,t):ht?.appendChild(Lt),rr&&(rr.micButton=X),rr?.addListener(X,`click`,uu),X.disabled=xs()||$.isStreaming()&&!Ss()}}else{let e=r.voiceRecognition??{},t=r.sendButton??{},n=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;X.classList.add(Jo),X.classList.toggle(Yo,!i),X.style.width=i??``,X.style.height=i??``,X.style.minWidth=i??``,X.style.minHeight=i??``;let o=e.iconColor??t.textColor;X.innerHTML=``;let s=U(n,a,o||`currentColor`,1.5);s?X.appendChild(s):X.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?X.style.backgroundColor=c:X.style.backgroundColor=``,o?X.style.color=o:X.style.color=`var(--persona-text, #111827)`,e.borderWidth?(X.style.borderWidth=e.borderWidth,X.style.borderStyle=`solid`):(X.style.borderWidth=``,X.style.borderStyle=``),e.borderColor?X.style.borderColor=e.borderColor:X.style.borderColor=``,e.paddingX?(X.style.paddingLeft=e.paddingX,X.style.paddingRight=e.paddingX):(X.style.paddingLeft=``,X.style.paddingRight=``),e.paddingY?(X.style.paddingTop=e.paddingY,X.style.paddingBottom=e.paddingY):(X.style.paddingTop=``,X.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;X.setAttribute(`aria-label`,l),Lt&&yo({anchor:X,trigger:Lt,text:()=>X?.getAttribute(`aria-label`)??l,enabled:u}),Lt.style.display=``,X.disabled=xs()||$.isStreaming()&&!Ss()}}else X&&Lt&&(Lt.style.display=`none`,ot(r.voiceRecognition?.provider)?$.isVoiceActive()&&$.toggleVoice():Bl&&ru());if(yu(),r.attachments?.enabled===!0){if(!zt||!Rt){let e=r.attachments??{};Vt||(Vt=z(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Vt.style.display=`none`,(J.parentElement??ht).insertBefore(Vt,J)),Bt||(Bt=document.createElement(`input`),Bt.type=`file`,Bt.accept=(e.allowedTypes??Ia).join(`,`),Bt.multiple=(e.maxFiles??4)>1,Bt.style.display=`none`,Bt.setAttribute(`aria-label`,`Attach files`),(J.parentElement??ht).insertBefore(Bt,J)),zt=z(`div`,`persona-send-button-wrapper`),Rt=z(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Jo} ${Yo}`),Rt.type=`button`,Rt.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Rt.style.fontSize=`18px`,Rt.style.lineHeight=`1`;let n=U(t,24,`currentColor`,1.5);n?Rt.appendChild(n):Rt.textContent=`📎`,Rt.addEventListener(`click`,e=>{e.preventDefault(),Bt?.click()}),zt.appendChild(Rt);let i=e.buttonTooltipText??`Attach file`;yo({anchor:Rt,trigger:zt,text:()=>Rt?.getAttribute(`aria-label`)??i}),jt?jt.append(zt):ht.appendChild(zt),rr&&(rr.attachmentButton=Rt,rr.attachmentInput=Bt??void 0,rr.attachmentPreviews=Vt??void 0),!Sn&&Bt&&Vt&&(Sn=Hd.fromConfig(e,Dn),Sn.setPreviewsContainer(Vt),rr?.addListener(Bt,`change`,async()=>{Sn&&Bt?.files&&(await Sn.handleFileSelect(Bt.files),Bt.value=``)}))}else{zt.style.display=``;let e=r.attachments??{};Bt&&(Bt.accept=(e.allowedTypes??Ia).join(`,`),Bt.multiple=(e.maxFiles??4)>1),Sn&&Sn.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(G.querySelector(`.persona-attachment-drop-overlay`)?.remove(),G.appendChild(Rw(r.attachments?.dropOverlay)),Rt){let e=r.attachments??{},t=e.buttonTooltipText??`Attach file`;Rt.setAttribute(`aria-label`,t),Rt.textContent=``;let n=U(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?Rt.appendChild(n):Rt.textContent=`📎`,zt&&yo({anchor:Rt,trigger:zt,text:()=>Rt?.getAttribute(`aria-label`)??t})}}else zt&&(zt.style.display=`none`),Sn&&Sn.clearAttachments(),G.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Pe=r.sendButton??{},Ie=Pe.useIcon??!1,Le=Pe.iconText??`↑`,Re=Pe.iconName,Ve=Pe.tooltipText??`Send message`,He=Pe.showTooltip??!1,Ge=Pe.size,Ke=parseFloat(Ge??``)||40,qe=Pe.backgroundColor,Je=Pe.textColor;if(Ie){if(Y.style.width=Ge??``,Y.style.height=Ge??``,Y.style.minWidth=Ge??``,Y.style.minHeight=Ge??``,Y.style.fontSize=`18px`,Y.style.lineHeight=`1`,Je?Y.style.color=Je:Y.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!$.isStreaming()){if(Y.innerHTML=``,Re){let e=parseFloat(Pe.iconSize??``)||Math.round(Ke*.5),t=Je?.trim()||`currentColor`,n=Pe.iconStrokeWidth??2,r=U(Re,e,t,n),i=U(Pe.stopIconName??`square`,e,t,n);r&&i?Y.appendChild(Qo(r,i)):r?Y.appendChild(r):Y.textContent=Le}else Y.textContent=Le}Y.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Jo}`,qe?(Y.style.backgroundColor=qe,Y.classList.remove(`persona-bg-persona-primary`)):(Y.style.backgroundColor=``,Y.classList.add(`persona-bg-persona-primary`))}else Y.textContent=r.copy?.sendButtonLabel??`Send`,Y.style.width=``,Y.style.height=``,Y.style.minWidth=``,Y.style.minHeight=``,Y.style.fontSize=``,Y.style.lineHeight=``,Y.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`,qe?(Y.style.backgroundColor=qe,Y.classList.remove(`persona-bg-persona-accent`)):Y.classList.add(`persona-bg-persona-accent`),Je?Y.style.color=Je:Y.classList.add(`persona-text-white`);Pe.borderWidth?(Y.style.borderWidth=Pe.borderWidth,Y.style.borderStyle=`solid`):(Y.style.borderWidth=``,Y.style.borderStyle=``),Pe.borderColor?Y.style.borderColor=Pe.borderColor:Y.style.borderColor=``,Pe.paddingX?(Y.style.paddingLeft=Pe.paddingX,Y.style.paddingRight=Pe.paddingX):(Y.style.paddingLeft=``,Y.style.paddingRight=``),Pe.paddingY?(Y.style.paddingTop=Pe.paddingY,Y.style.paddingBottom=Pe.paddingY):(Y.style.paddingTop=``,Y.style.paddingBottom=``),$.isStreaming()||Y.setAttribute(`aria-label`,Ve),Es(),Nt&&yo({anchor:Y,trigger:Nt,text:()=>Y.getAttribute(`aria-label`)??Ve,enabled:He}),Cr(),Ei();let Ye=Nf(Z.getState().activeModeIds,r.composer?.modes);Z.setActiveModeIds(Ye),kn().length>0!=!!Fn&&vr(),Fn?.render(Ye,kn());for(let e of[...In.keys()])Of(e,r.composer?.modeGroups)||In.delete(e);In.forEach(e=>e.repaint()),Nn?.repaint(),fr?.resolve();let Xe=Wp(r,ge());if(Ci(),Xe){q.style.maxWidth=Xe,q.style.marginLeft=`auto`,q.style.marginRight=`auto`,q.style.width=`100%`,bt.style.maxWidth=Xe,bt.style.marginLeft=`auto`,bt.style.marginRight=`auto`,bt.style.width=`100%`;for(let e of[ht,dt,Vt,gt])e&&(e.style.maxWidth=Xe,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{q.style.maxWidth=``,q.style.marginLeft=``,q.style.marginRight=``,q.style.width=``,bt.style.maxWidth=``,bt.style.marginLeft=``,bt.style.marginRight=``,bt.style.width=``;for(let e of[ht,dt,Vt,gt])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let Ze=r.statusIndicator??{};if(rt(gt,ht,Ze),nt(gt,Ze,$?.getStatus()??`idle`),$){let e=$.getStatus();tt(gt,(e=>e===`idle`?Ze.idleText??Lr.idle:e===`connecting`?Ze.connectingText??Lr.connecting:e===`connected`?Ze.connectedText??Lr.connected:e===`error`?Ze.errorText??Lr.error:e===`paused`?Ze.pausedText??Lr.paused:e===`resuming`?Ze.resumingText??Lr.resuming:Lr[e])(e),Ze,e)}gt.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let Qe=Ze.align===`left`?`persona-text-left`:Ze.align===`center`?`persona-text-center`:`persona-text-right`;gt.classList.add(Qe),ar(),Os(),Sr(),Ue()},open(){B()&&ys(!0,`api`)},close(){B()&&ys(!1,`api`)},toggle(){B()&&ys(!V,`api`)},reconnect(){$.reconnectNow()},clearChat(){Gr=!1,o.clear(),i.clear(),a.clear(),s.clear(),$.clearMessages(),r.layout?.topFade&&(K.scrollTop=0),K.removeAttribute(`data-persona-top-fade`),ta.clear(),go();try{localStorage.removeItem(Dw),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Dw}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Dw)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),A?.clear&&Ka(()=>A.clear(),`[AgentWidget] Failed to clear storage adapter:`),M={},L.syncFromMetadata(),Sn?.clearAttachments(),to(),Un(void 0),Rn(void 0),sa(),ke?.clear(),Ae?.reset(),Ne?.update()},setMessage(e){return!J||$.isStreaming()||xs()?!1:(!V&&B()&&ys(!0,`system`),J.value=e,J.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if($.isStreaming()||Cs())return!1;let t=e?.trim()||J.value.trim();return t?(!V&&B()&&ys(!0,`system`),J.value=``,J.style.height=`auto`,wn(),Cl(t,{consumeDraft:!1}),!0):!1},getComposerState(){return Z.getState()},setQuote(e){let t=e?.text?.trim();t&&Rn({...e,text:t})},clearQuote(){Rn(void 0)},startVoiceRecognition(){return $.isStreaming()?!1:ot(r.voiceRecognition?.provider)?($.isVoiceActive()||$.isBargeInActive()||(!V&&B()&&ys(!0,`system`),Pa.manuallyDeactivated=!1,Ba(),$.toggleVoice().then(()=>{Pa.active=La(),Ba(),za(`user`),Pa.active&&ou()})),!0):Bl?!0:tu()?(!V&&B()&&ys(!0,`system`),Pa.manuallyDeactivated=!1,Ba(),nu(`user`),!0):!1},stopVoiceRecognition(){return ot(r.voiceRecognition?.provider)?!$.isVoiceActive()&&!$.isBargeInActive()?!1:(($.isBargeInActive()?$.deactivateBargeIn():$.toggleVoice()).then(()=>{Pa.active=!1,Pa.manuallyDeactivated=!0,Ba(),za(`user`),lu()}),!0):Bl?(Pa.manuallyDeactivated=!0,Ba(),ru(`user`),!0):!1},injectMessage(e){return!V&&B()&&ys(!0,`system`),$.injectMessage(e)},injectAssistantMessage(e){!V&&B()&&ys(!0,`system`);let t=$.injectAssistantMessage(e);return H&&(H=!1,_e&&=(clearTimeout(_e),null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),t},injectUserMessage(e){return!V&&B()&&ys(!0,`system`),$.injectUserMessage(e)},injectSystemMessage(e){return!V&&B()&&ys(!0,`system`),$.injectSystemMessage(e)},injectMessageBatch(e){return!V&&B()&&ys(!0,`system`),$.injectMessageBatch(e)},injectComponentDirective(e){return!V&&B()&&ys(!0,`system`),$.injectComponentDirective(e)},injectTestMessage(e){!V&&B()&&ys(!0,`system`),$.injectTestEvent(e)},async connectStream(e,t){return $.connectStream(e,t)},__pushEventStreamEvent(e){Se&&(Be(),ze(e.type,e.payload))},showEventStream(){Se&&Xn()},hideEventStream(){Fe&&Zn()},isEventStreamVisible(){return Fe},listConversations(e){return $.listConversations(e)},getActiveConversationId(){return $.getActiveConversationId()},openConversation(e,t){return Gc(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Gc(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Jc()},deleteConversation(e){return Gc(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Gc(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Gc(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Gc(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Gc(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=lc;if(!e)return null;let t=await e.get();return e===lc?t:null},getHistoryIdentityStatus(){let e=Ac?.historyProvider;return e?e.getIdentityStatus():Pc()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Pc()?Gc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Ac?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return Ve},showArtifacts(){xx(r)&&(Gr=!1,Jr=!0,xi(),Rr?.setMobileOpen(!0))},hideArtifacts(){xx(r)&&(Gr=!0,xi())},upsertArtifact(e){return xx(r)?($t(r.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Gr=!1,Jr=!0),$.upsertArtifact(e)):null},selectArtifact(e){xx(r)&&$.selectArtifact(e)},clearArtifacts(){xx(r)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return R&&!V&&!ge()||!J?!1:(J.focus(),!0)},async resolveApproval(e,t,n){let r=$.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(r.approval.toolType===`webmcp`)$.resolveWebMcpApproval(r.id,t);else return $.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){$i(e)},clearFollowUpSuggestions(){Qi()},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...M}},updatePersistentMetadata(e){se(e)},on(e,t){return k.on(e,t)},off(e,t){k.off(e,t)},isOpen(){return B()&&V},isVoiceActive(){return Pa.active},toggleReadAloud(e){$.toggleReadAloud(e)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(e){return $.getReadAloudState(e)},onReadAloudChange(e){return $.onReadAloudChange(e)},getState(){return{open:B()&&V,launcherEnabled:R,voiceActive:Pa.active,streaming:$.isStreaming()}},showCSATFeedback(e){!V&&B()&&ys(!0,`system`);let t=q.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Tw({onSubmit:async(t,n)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});q.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!V&&B()&&ys(!0,`system`);let t=q.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Ew({onSubmit:async(t,n)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});q.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return $.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return $.submitNPSFeedback(e,t)},destroy(){Ec(),pc!=null&&(clearInterval(pc),pc=null),o.clear(),i.clear(),a.clear(),s.clear(),Q.forEach(e=>e()),at.remove(),st?.remove(),wu?.destroy(),Tu?.remove(),zi&&wt.removeEventListener(`click`,zi)}};if(((n?.debugTools??!1)||r.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:sd,getMessages:sd.getMessages,getStatus:sd.getStatus,getMetadata:sd.getPersistentMetadata,updateMetadata:sd.updatePersistentMetadata,clearHistory:()=>sd.clearChat(),setVoiceActive:e=>e?sd.startVoiceRecognition():sd.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Q.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let t=e.getAttribute(`data-persona-instance`)||e.id||`persona-`+Math.random().toString(36).slice(2,8),n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Q.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),Se){let e=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.showEventStream()},n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.hideEventStream()};window.addEventListener(`persona:showEventStream`,e),window.addEventListener(`persona:hideEventStream`,n),Q.push(()=>{window.removeEventListener(`persona:showEventStream`,e),window.removeEventListener(`persona:hideEventStream`,n)})}let r=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.showHistory()},i=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Q.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.showArtifacts()},o=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.hideArtifacts()},s=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||n?.artifact&&sd.upsertArtifact(n.artifact)},c=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||typeof n?.id==`string`&&sd.selectArtifact(n.id)},l=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&sd.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Q.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let cd=Nw(r.persistState);if(cd&&B()){let t=Pw(cd.storage),n=`${cd.keyPrefix}widget-open`,r=`${cd.keyPrefix}widget-voice`,i=`${cd.keyPrefix}widget-voice-mode`;if(t){let a=cd.persist?.openState&&t.getItem(n)===`true`,o=cd.persist?.voiceState&&t.getItem(r)===`true`,s=cd.persist?.voiceState&&t.getItem(i)===`true`;if(a&&(wu?.setPanelOpen(!0,`auto`),setTimeout(()=>{sd.open(),setTimeout(()=>{if(o||s)sd.startVoiceRecognition();else if(cd.persist?.focusInput){let t=e.querySelector(`textarea`);t&&t.focus()}},100)},0)),cd.persist?.openState&&(k.on(`widget:opened`,()=>{t.setItem(n,`true`)}),k.on(`widget:closed`,()=>{t.setItem(n,`false`)})),cd.persist?.voiceState&&(k.on(`voice:state`,e=>{t.setItem(r,e.active?`true`:`false`)}),k.on(`user:message`,e=>{t.setItem(i,e.viaVoice?`true`:`false`)})),cd.clearOnChatClear){let e=()=>{t.removeItem(n),t.removeItem(r),t.removeItem(i)},a=()=>e();window.addEventListener(`persona:clear-chat`,a),Q.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(re&&B()&&(wu?.setPanelOpen(!0,`auto`),setTimeout(()=>{sd.open()},0)),gs(),!la){let e=pt(()=>{$&&(ca++,ta.clear(),rs(q,$.getMessages(),ye))});Q.push(e)}S=()=>{$&&(ca++,ta.clear(),rs(q,$.getMessages(),ye))},$.getMessages().length>0&&ns(),D=()=>{$&&(ca++,ta.clear(),rs(q,$.getMessages(),ye))};let ld=Pe(()=>{$&&(ca++,ta.clear(),rs(q,$.getMessages(),ye))});Q.push(ld);let fd=bx(()=>{$&&(ca++,ta.clear(),rs(q,$.getMessages(),ye),yx()?.updateInlineArtifactBlocks(q,Wr.artifacts,{suppressTransition:!0}),xi())});return Q.push(fd),sd};Br();const Hw=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},Uw=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Ww=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},Gw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&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.")},Kw=(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`},qw=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=``},Jw=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,qw(e)},Yw=e=>{e.style.transition=``},Xw=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=``},Zw=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},Qw=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},$w=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},eT=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},tT=e=>{let t=Bp(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:mp(t,e)??e;return{inset:r(n?.inset,$f),canvasBackground:r(n?.canvasBackground,ep)}},nT=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},rT=(e,t,n,r,i,a,o,s)=>{let c=Vh(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;$w(e,t,n,r,l),eT(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`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`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),Xw(t),Yw(r),Jw(r),Zw(n),Qw(i,r),nT(r,!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`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(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`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),Jw(r),Uw(r,c.maxHeight),nT(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,Xw(t),Yw(r),Zw(n),Qw(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.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`,Yw(r),qw(r),Qw(i,r);let a=Hw(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;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=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,Xw(t),qw(r),Zw(n),Qw(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,Ww(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${Hw(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},iT=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return Kw(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){Kw(n,e)},destroy(){n.remove()}}},aT=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?tT(t):null};h();let g=()=>{rT(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Up(()=>{h(),g()}))},y=()=>{p(),Vh(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,Gw(o,Vh(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Vh(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},oT=(e,t)=>zh(t)?aT(e,t):iT(e,t);he();const sT={desktop:{w:1280,h:800},mobile:{w:390,h:844}},cT=`persona-preview-shell-theme`,lT={load:()=>null,save:()=>{},clear:()=>{}},uT=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function dT(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function fT(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 pT(e){let t=fT(e);return`* { box-sizing: border-box; }
|
|
1259
|
+
`)}if(!o&&!n){let e=i?``:`padding-top: 1.25em !important;`,t=i?``:`z-index: ${r.launcher?.zIndex??1e5} !important;`;W.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}yn(),fe()},wi=()=>{e.style.setProperty(`--persona-content-max-width`,em(r,L()))},Ti=!1;function Ei(){r.layout?.topFade&&q.scrollTop>1?q.setAttribute(`data-persona-top-fade`,`true`):q.removeAttribute(`data-persona-top-fade`)}let Di=()=>{Ei();let t=tm(r,L());L()&&r.composer?.placement&&r.debug===!0&&!Ti&&(Ti=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=mn();e.setAttribute(`data-persona-composer-placement`,t),e.setAttribute(`data-persona-conversation-state`,hn),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),e.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),bn()},Oi=()=>{if(L())return;let t=Yh(r),n=r.launcher?.sidebarMode??!1;if(t||n||(r.launcher?.fullHeight??!1)||!I)return;let i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640;if(a&&i.innerWidth<=o)return;let s=D_(r);G.style.height=s.height,G.style.maxHeight=s.maxHeight};Ci(),Qp(e,r),Lx(e,r),Rx(e,r),wi(),Di(),Hr=()=>{Ci(),Oi(),Qp(e,r),Lx(e,r),Rx(e,r),wi(),Di(),Wr?e.style.setProperty(`--persona-artifact-welded-outer-radius`,Wr):e.style.removeProperty(`--persona-artifact-welded-outer-radius`),Ge(),We()};let Q=[];Q.push(()=>{zr=!0}),Q.push(()=>{p.forEach(e=>e()),f.destroy()}),Q.push(()=>{document.removeEventListener(`keydown`,si)}),Q.push(()=>{cn!==null&&clearTimeout(cn)});let ki=null,Ai=null;Q.push(()=>{ki?.(),ki=null,Ai?.(),Ai=null}),Br&&Q.push(()=>{Br?.disconnect(),Br=null}),Q.push(()=>{ui?.(),ui=null,gi(),li&&=(li.remove(),null),Rr?.element.style.removeProperty(`width`),Rr?.element.style.removeProperty(`maxWidth`),Rr?.destroy()}),Ee&&Q.push(()=>{Pe=!0,Ne=null,Le!==null&&(cancelAnimationFrame(Le),Le=null),Fe?.destroy(),Fe=null,Me?.destroy(),Me=null,je=null});let ji=null,Mi=()=>{ji&&=(ji(),null),r.colorScheme===`auto`&&(ji=$p(()=>{Qp(e,r)}))};Mi(),Q.push(()=>{ji&&=(ji(),null)}),Q.push(()=>{y=!0,v?.()}),Q.push(()=>{w=!0});let Ni=!1;Q.push(()=>{Ni=!0});let Pi=(t,n)=>{let r=Um(t,n);return r||!Vm.includes(t)?r:(Uh().then(r=>{if(Ni)return;Hm(r.wipe),Hm(r.glyphCycle);let i=Um(t,n);i&&ah(i,e)}).catch(()=>{}),null)},Fi=r.features?.streamAnimation;if(Fi?.type&&Fi.type!==`none`){let t=Pi(Fi.type,Fi.plugins);t&&ah(t,e),Q.push(()=>ih(e))}let Ii=ig(at),Li=ig(rt),Ri=ig(it),zi=[Ii,Li,Ri];Q.push(()=>{zi.forEach(e=>e.destroy())});let Bi=null,$,Vi=null,Hi=!1,Ui=0,Wi=null,Gi=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),Ki=e=>{for(let t=e.length-1;t>=0;t--)if(Ar(e[t]))return e[t].id??null;return null},qi=!1,Ji=()=>{qi||r.debug!==!0||(qi=!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".`))},Yi=!1,Xi=!1,Zi=(e,t)=>{Yi||r.debug!==!0||t.enabled&&!t.expose&&(Hi||Xi&&($.isStreaming()||e.some(Ar)||(Yi=!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.`))))},Qi=e=>{if(!$)return;let t=e??$.getMessages(),n=e=>{e.render([],$,Y,t)},i=e=>{zi.forEach(t=>{t!==e&&n(t)})};Vi&&(Gi(t)>Ui||Ki(t)!==Wi)&&(Vi=null);let a=Fr(r);Zi(t,a);let o=a.enabled?Mr(t):null,s=Vi??o,c=Vi?`host`:`agent`;if(s){let e=r.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?L()?`composer`:`after-message`:n)===`after-message`?Ri:Ii;i(a),a.render(s,$,Y,t,r.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:r,plugins:d,submitPrompt:Cl});return}if(t.some(e=>e.role===`user`)){zi.forEach(n);return}let l=r.future?.v5Defaults===!0,u=fn(),f=r.suggestions?.starters??(l?{}:void 0);if(f){let e=T_(mn(),t),a=f.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){Ji(),zi.forEach(n);return}let s=o===`welcome`?Li:Ii;i(s),s.render(f.items??r.suggestionChips,$,Y,t,r.suggestionChipsConfig,{surface:`starter`,variant:f.variant??(l&&!u?`chip`:`card`),behavior:f.behavior??`send`,overflow:f.overflow??`wrap`,maxItems:f.maxItems??(l&&!u?3:4),config:r,plugins:d,submitPrompt:Cl})}else i(Ii),Ii.render(r.suggestionChips,$,Y,t,r.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:r,plugins:d,submitPrompt:Cl})},$i=()=>{Vi&&(Vi=null,Qi())},ea=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){$i();return}let n=$?$.getMessages():[];Vi=t,Hi=!0,Ui=Gi(n),Wi=Ki(n),Qi(n)},ta=!1,na=Sm(),ra=/* @__PURE__ */ new Map,ia=/* @__PURE__ */ new Map,aa=/* @__PURE__ */ new Map,oa=null,sa=null;function ca(){if(!oa)return;let e=oa;oa=null,sa?.destroy(),sa=null,na.delete(e),K.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),$&&Zo(J,$.getMessages(),Ce)}let la=0,ua=kt()!==null,da=Dm(),fa=0,pa=null,ma=!1,ha=!1,ga=0,_a=null,va=null,ya=!1,ba=!1,xa=null,Sa=!0,Ca=!1,wa=null,Ta=!1,Ea=()=>{Ta=!0,ja()},Da=null,Oa=null,Aa=()=>{e.setAttribute(`data-persona-scrollbar`,$t()),$t()!==`on-scroll`&&(Oa!==null&&clearTimeout(Oa),Oa=null,q.removeAttribute(`data-persona-scrollbar-visible`))},ja=()=>{$t()===`on-scroll`&&(q.setAttribute(`data-persona-scrollbar-visible`,``),Oa!==null&&clearTimeout(Oa),Oa=setTimeout(()=>{Oa=null,km(q,24)&&q.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};Aa(),Q.push(()=>{Oa!==null&&clearTimeout(Oa)});let Ma=/* @__PURE__ */ new Map,Na=!1,Pa=null,Fa={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Cr();let Ia=r.voiceRecognition?.autoResume??!1,La=()=>$.isVoiceActive()||$.isBargeInActive(),Ra=!1,za=e=>{k.emit(`voice:state`,{active:Fa.active,source:e,timestamp:Date.now()})},Ba=()=>{ce(e=>({...e,voiceState:{active:Fa.active,timestamp:Date.now(),manuallyDeactivated:Fa.manuallyDeactivated}}))},Ha=()=>{if(r.voiceRecognition?.enabled===!1)return;let e=Kw(N.voiceState),t=!!e.active,n=Number(e.timestamp??0);Fa.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{Fa.active||(Fa.manuallyDeactivated=!1,ht(r.voiceRecognition?.provider)?$.toggleVoice().then(()=>{Fa.active=La(),za(`restore`),Fa.active?su():(Ba(),ul(`Tap the mic to resume your voice call`,1e4))}):ru(`restore`))},ht(r.voiceRecognition?.provider)?0:1e3)},Ua=e=>{Ra=!e.persisted,Fa.active&&Ba()};typeof window<`u`&&(window.addEventListener(`pagehide`,Ua),Q.push(()=>window.removeEventListener(`pagehide`,Ua)));let Wa=()=>$?qw($.getMessages()).filter(e=>!e.__skipPersist):[],Ga=null,Ka=(e,t)=>{typeof console<`u`&&console.error(e,t)},qa=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Ka(t,e)})}catch(e){return Ka(t,e),null}},r=Ga,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{Ga===a&&(Ga=null)});Ga=a};function Ja(e){if(!A?.save)return;let t=e?qw(e):$?Wa():[],n=ee&&$?.getResumableHandle();n&&(N={...N,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:N,artifacts:Gr.artifacts,selectedArtifactId:Gr.selectedId,...Ya?{draft:Ya}:{}};qa(()=>A.save(r),`[AgentWidget] Failed to persist state:`)}let Ya,Xa=()=>!A?.save||r.persistState===!1?!1:typeof r.persistState!=`object`||r.persistState.persist?.draft!==!1,Za=Qf({write:()=>{if(!Xa())return;let e=wn.getState(),t=Xf({text:e.text,mentionRefs:e.mentionRefs,contentSegments:al(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Ya)&&(Ya=t,Ja())}});function Qa(){Xa()&&Za.schedule()}function $a(){Za.flush()}function eo(e){if(!Xa())return;let t=Zf(e,{mentionSourceIds:(r.contextMentions?.sources??[]).map(e=>e.id),modelIds:(r.composer?.models??[]).map(e=>e.id),modes:r.composer?.modes??[]});t&&(Ya=e,Y&&!Y.value&&(Y.value=t.text,Y.dispatchEvent(new Event(`input`,{bubbles:!0})),Tn()),t.selectedModelId&&(wn.setSelectedModelId(t.selectedModelId),Pn?.repaint()),Mn(t.activeModeIds??[]),t.quote&&zn(t.quote),Za.cancel())}function to(){Za.cancel(),Ya&&(Ya=void 0,Xa()&&Ja())}let ro=null,io=()=>W.querySelector(`#persona-scroll-container`)||q,ao=()=>{ro!==null&&(cancelAnimationFrame(ro),ro=null),ma=!1},oo=()=>{pa!==null&&(cancelAnimationFrame(pa),pa=null),ha=!1,ao()},so=()=>ta&&po()&&(Wt()!==`anchor-top`||Xt()),co=()=>{let e=Vt()||`Jump to latest`,t=so();en.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),ga>0?(an.textContent=String(ga),an.style.display=``,en.setAttribute(`aria-label`,`${e} (${ga} new)`)):(an.textContent=``,an.style.display=`none`,en.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},lo=()=>{ga!==0&&(ga=0,co())},uo=()=>{let e=_a?.spacerHeight??0;return e<=0?km(q,24):ko(e)-q.scrollTop-q.clientHeight<=24},po=()=>Gt()?!da.isFollowing():!uo(),mo=()=>!!$&&$.getMessages().length>0,ho=()=>{if(!Ut()||Ye()){en.parentNode&&en.remove(),en.style.display=`none`;return}en.parentNode!==K&&K.appendChild(en),vn();let e=Om(q)>0&&po()&&mo();e?co():lo(),en.style.display=e?``:`none`},go=()=>{da.pause()&&(oo(),ho())},_o=()=>{da.resume(),lo(),ho()},vo=(e=!1)=>{Gt()&&mo()&&da.isFollowing()&&(e||ta)&&(pa!==null&&(cancelAnimationFrame(pa),pa=null),ha=!0,pa=requestAnimationFrame(()=>{pa=null,ha=!1,da.isFollowing()&&bo(io(),e?220:140)}))},yo=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(ao(),Math.abs(o)<1){ma=!0,e.scrollTop=a,fa=e.scrollTop,ma=!1;return}let s=performance.now();ma=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){ao();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,fa=e.scrollTop,p<1?ro=requestAnimationFrame(l):(e.scrollTop=a,fa=e.scrollTop,ro=null,ma=!1)};ro=requestAnimationFrame(l)},bo=(e,t=500)=>{let n=Om(e)-e.scrollTop;Math.abs(n)<1?fa=e.scrollTop:Math.abs(n)>=80?(ao(),ma=!0,e.scrollTop=Om(e),fa=e.scrollTop,ma=!1):yo(e,()=>Om(e),t,()=>da.isFollowing())},xo=()=>{if(!mo()){ho();return}let e=io();ma=!0,e.scrollTop=Om(e),fa=e.scrollTop,ma=!1,ho()},So=e=>{let t=0,n=e;for(;n&&n!==q;)t+=n.offsetTop,n=n.offsetParent;return t},Co=()=>{let e=q.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??q.ownerDocument.getSelection()},wo=()=>Mm(Co(),q),Eo=()=>{if(qt()!==`last-user-turn`)return!1;let e=$?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=q.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,So(r)-Kt()),Om(q));return ma=!0,q.scrollTop=i,fa=q.scrollTop,ma=!1,Wt()===`follow`&&!km(q,24)&&da.pause(),ho(),!0},Oo=e=>{let t=Math.max(0,Math.round(e));on.style.height=`${t}px`,on.style.display=t>0?``:`none`,_a&&(_a.spacerHeight=Math.max(0,e))},ko=e=>{let t=parseFloat(getComputedStyle(q).paddingBottom)||0,n=0;for(let e of Array.from(q.children)){if(e===on||e.offsetHeight===0)continue;let t=So(e)+e.offsetHeight;t>n&&(n=t)}let r=q.scrollHeight-e;return n>0?Math.min(n+t,r):r},Ao=()=>{if(!_a||_a.spacerHeight<=0)return;let e=ko(_a.spacerHeight),t=Math.max(0,Math.round(q.scrollTop)+q.clientHeight-e+24);t<_a.spacerHeight&&(Oo(t),ho())},jo=()=>{va!==null&&(cancelAnimationFrame(va),va=null),ao(),_a=null,on.style.height=`0px`,on.style.display=`none`},Mo=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),No=e=>q.querySelector(`[data-message-id="${Mo(e)}"]`),Po=e=>{va!==null&&cancelAnimationFrame(va),va=requestAnimationFrame(()=>{va=null;let t=Mo(e),n=q.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=So(n),i=_a?.spacerHeight??0,a=ko(i),{targetScrollTop:o,spacerHeight:s}=Nm({anchorOffsetTop:r,topOffset:Kt(),viewportHeight:q.clientHeight,contentHeight:a,slack:24});_a={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},Oo(s),yo(q,()=>n.isConnected?Math.max(0,So(n)-Kt()):o,220)})},Fo=()=>{if(Wt()!==`anchor-top`||!_a||!wa)return;let e=No(wa);if(!e)return;ao();let t=_a.spacerHeight,n=ko(t),{targetScrollTop:r,spacerHeight:i}=Nm({anchorOffsetTop:So(e),topOffset:Kt(),viewportHeight:q.clientHeight,contentHeight:n,slack:24});_a={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},Oo(i),ma=!0,q.scrollTop=r,fa=q.scrollTop,ma=!1,ho()},Io=()=>{if(Gt()){if(!da.isFollowing()||km(q,1))return;vo(!ta)}else{if(_a&&_a.initialSpacerHeight>0){let e=q.scrollHeight-_a.spacerHeight,t=Pm({initialSpacerHeight:_a.initialSpacerHeight,contentHeightAtAnchor:_a.contentHeightAtAnchor,currentContentHeight:e});t!==_a.spacerHeight&&Oo(t)}ho()}},Lo=e=>{let t=Wt();t===`follow`?(_o(),vo(!0)):t===`anchor-top`&&(Sa=!1,Ca=!0,Ta=!1,wa=e,Po(e))},Ro=()=>{Wt()===`anchor-top`&&(Ca?Sa=!1:(Sa=!0,jo(),_o(),vo(!0)))},zo=e=>{if(xa===null)return!0;let t=No(xa),n=No(e);if(!t||!n)return!0;let r=So(n)-So(t);return Kt()+r>q.clientHeight-96},Bo=e=>{if(Wt()!==`anchor-top`||!Ca||Ta||wo())return;let t=xa===null;for(let n of e)if(!t)n.id===xa&&(t=!0);else if(Em(n)){if(n.id===wa||!zo(n.id))return;wa=n.id,Po(n.id);return}},Vo=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=Ma.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(k.emit(`assistant:message`,e),!ba&&(Wt()!==`anchor-top`||Xt())&&po()&&(ga+=1,co(),ho(),dn(ga===1?`1 new message below.`:`${ga} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&k.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&k.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):k.emit(`approval:requested`,{approval:e.approval,message:e}))}),Ma.clear(),t.forEach((e,t)=>{Ma.set(t,e)})},Ho=(e,t)=>{let n=t===`user`?`user`:`assistant`,i=r.layout?.messages?.[n],a=i?.width??`content`,o=i?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},Uo=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Ho(n,t),n},Wo=(e,t,n)=>{let c=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||ot(r,t)!==`row`)continue;let n=t===`tool`?r.features?.toolCallDisplay:r.features?.reasoningDisplay;n?.expandable!==!1&&(c.add(e.id),o.observe(e,t,t===`tool`?i:a,n))}let l=document.createElement(`div`),u=(()=>{let e=d.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),f=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Set,g=d.some(e=>e.renderAskUserQuestion),v=[],y=[],b=r.enableComponentStreaming!==!1,x=r.approval!==!1,S=[],w=r.messageActions,T=w?.showRegenerate===!0&&w.enabled!==!1&&Qr.current?.isStreaming()!==!0?Hl(t):null,E=w?.showEdit===!0&&w.enabled!==!1,k=w?.showQuote===!0&&w.enabled!==!1,A=null,j=r.features?.reasoningDisplay?.completedVisibility,ee=e=>j===`removed`||j===`removed-when-short`&&un(e,r.features?.reasoningDisplay?.shortThinkThreshold),M=r.features?.toolCallDisplay?.completedVisibility===`removed`,N=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?ee(e.reasoning):M&&e.variant===`tool`&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;if(t.forEach(t=>{if(N(t))return;if(p.add(t.id),m.set(t.id,t.role),oa===t.id&&sa){let e=Uo(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),A={messageId:t.id,element:sa.element};return}let o=g&&Kn(t),c=x&&t.variant===`approval`&&!!t.approval,f=!o&&t.role===`assistant`&&!t.variant&&b&&Nw(t);!c&&aa.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),aa.delete(t.id)),!f&&ia.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ia.delete(t.id));let w=Kn(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,j={canRegenerate:T===t.id,canEdit:E&&Ul(t),canQuote:k&&!t.variant&&(t.content?.trim().length??0)>0},ee=`${j.canRegenerate?`r`:``}${j.canEdit?`e`:``}${j.canQuote?`q`:``}`,M=xm(t,la)+w+`:${ee}`,P=o||c||f?null:Cm(na,t.id,M);if(P){l.appendChild(P.cloneNode(!0)),Kn(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),ti(t));return}let te=null,ne=d.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),re=r.layout?.messages;if(Kn(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){ra.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(Ar(t)&&Fr(r).enabled)return;if(Kn(t)&&r.features?.askUserQuestion?.enabled!==!1){let e=d.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Qr.current){let n=ra.get(t.id),i=n!==M,a=null;if(i){let{payload:n,complete:i}=Jn(t),o=t.id,s=()=>Qr.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:i,resolve:e=>{let t=s();t&&Qr.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Qr.current?.markAskUserQuestionResolved(e),Qr.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:r})}if(i&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),ti(t));return}let o=Uo(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(o),v.push({messageId:t.id,fingerprint:M,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),ti(t));return}if(c){let n=C();if(!n){l.appendChild(Uo(t.id,t.role));return}let i=d.find(e=>typeof e.renderApproval==`function`)??_,a=aa.get(t.id)!==M,o=null;if(a&&i?.renderApproval){let e=t.id,a=(t,n)=>{let r=Qr.current?.getMessages().find(t=>t.id===e);r?.approval&&(D(r.approval)?Qr.current?.resolveWebMcpApproval(r.id,t):Qr.current?.resolveApproval(r.approval,t,n))};o=i.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,r,s),config:r,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),aa.delete(t.id),te=n.createApprovalBubble(t,r,s);else{let e=Uo(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),S.push({messageId:t.id,fingerprint:M,bubble:o});return}}else if(ne){if(t.variant===`reasoning`&&t.reasoning&&ne.renderReasoning){if(!we)return;te=ne.renderReasoning({message:t,defaultRenderer:()=>$_(t,r,a),config:r})}else if(t.variant===`tool`&&t.toolCall&&ne.renderToolCall){if(!Te)return;te=ne.renderToolCall({message:t,defaultRenderer:()=>uv(t,r,i),config:r})}else ne.renderMessage&&(te=ne.renderMessage({message:t,defaultRenderer:()=>{let e=a_(t,n,re,r.messageActions,Ze,{loadingIndicatorRenderer:u,widgetConfig:r,actionEligibility:j});return t.role!==`user`&&O(e,t,r,$),e},config:r}))}if(!te&&f){let i=Pw(t);if(i){let a=ia.get(t.id),o=a!==M,s=r.wrapComponentDirectiveInBubble!==!1&&My.getOptions(i.component)?.bubbleChrome!==!1,c=null;if(o){let a=jw(i,{config:r,message:t,transform:n});if(a&&i.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&kx()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=Uo(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),y.push({messageId:t.id,fingerprint:M,bubble:c});return}}}if(!te){if(t.variant===`reasoning`&&t.reasoning){if(!we)return;te=$_(t,r,a)}else if(t.variant===`tool`&&t.toolCall){if(!Te)return;te=uv(t,r,i)}else if(t.variant===`approval`&&t.approval){if(r.approval===!1)return;let e=C();if(!e)return;te=e.createApprovalBubble(t,r,s)}else{let e=r.layout?.messages;te=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:r,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:r,streaming:!!t.streaming}):a_(t,n,e,r.messageActions,Ze,{loadingIndicatorRenderer:u,widgetConfig:r,actionEligibility:j}),t.role!==`user`&&te&&O(te,t,r,$)}}let F=Uo(t.id,t.role);F.appendChild(te),wm(na,t.id,M,F),l.appendChild(F)}),nt.composerOverlay&&nt.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!h.has(t)&&xr(nt.composerOverlay,t)}),r.features?.toolCallDisplay?.grouped){let e=[],n=[],a=r.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&Te){if(M&&t.toolCall.status===`complete`&&!t.toolCall.interrupted)return;n.push(t)}else(t.variant!==`reasoning`||we&&(t.reasoning?.status!==`complete`||!ee(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(l.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=Uo(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),r.features?.toolCallDisplay?.groupedMode===`collapsible`){let a=`tool-group-${e[0].id}`,s=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:s?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1),interrupted:!s&&e.some(e=>e.toolCall?.interrupted)}};c.add(a),o.observe(l,`tool`,i,r.features.toolCallDisplay);let u=l.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${s?`Using`:`Used`} ${e.length} tools`,d=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:r}),f=lt(l,r,i.has(a),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let u=document.createElement(`div`);u.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,u.id=`tool-group-summary-${e[0].id}`;let d=`${e.length} ${e.length===1?`tool`:`tools`}`,p=e.some(e=>e.toolCall?.interrupted)?`${d} · Interrupted`:`Called ${d}`,m=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:p,config:r});f(u,m)||(u.textContent=p);let h=document.createElement(`div`);h.className=`persona-tool-group-stack persona-flex persona-flex-col`,h.id=`tool-group-stack-${e[0].id}`,h.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(u),a||s.appendChild(h),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),h.appendChild(r)})})}o.prune(c),Tm(na,p);let P=e=>e.variant===`tool`&&!Te||e.variant===`reasoning`&&!we||N(e),te=t.some(e=>e.role===`assistant`&&e.streaming&&!P(e)),ne=t.length-1;for(;ne>=0&&P(t[ne]);)ne--;let re=ne>=0?t[ne]:void 0,F=ne<t.length-1,ie=re?.role===`assistant`&&!re.streaming&&re.variant!==`approval`&&!F;if(ta&&t.some(e=>e.role===`user`)&&!te&&!ie){let e={config:r,streaming:!0,location:`standalone`,defaultRenderer:Yg},t=d.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&r.loadingIndicator?.render&&(n=r.loadingIndicator.render(e)),n===null&&(n=Yg()),n){let e=document.createElement(`div`),t=r.loadingIndicator?.showBubble!==!1,i=r.layout?.messages?.layout??`bubble`;e.className=t?$g(`assistant`,i).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,i!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Uo(`typing-indicator`,`assistant`);a.appendChild(e),l.appendChild(a)}}if(!ta&&t.length>0){let e=t[t.length-1],n={config:r,lastMessage:e,messageCount:t.length},i=d.find(e=>e.renderIdleIndicator),a=null;if(i?.renderIdleIndicator&&(a=i.renderIdleIndicator(n)),a===null&&r.loadingIndicator?.renderIdle&&(a=r.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=r.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`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(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Uo(`idle-indicator`,`assistant`);t.appendChild(e),l.appendChild(t)}}if(Yt(l),_m(e,l),Zt(e),A){let{messageId:t,element:n}=A,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Ho(r,m.get(t)??`user`),r.replaceChildren(n))}if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(Ho(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ra.set(t,n)))}if(ra.size>0)for(let e of ra.keys())p.has(e)||ra.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of y){let i=e.querySelector(`#wrapper-${t}`);i&&(Ho(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ia.set(t,n)))}if(ia.size>0)for(let e of ia.keys())p.has(e)||ia.delete(e);if(S.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of S){let i=e.querySelector(`#wrapper-${t}`);i&&(Ho(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),aa.set(t,n)))}if(aa.size>0)for(let e of aa.keys())p.has(e)||aa.delete(e)},Go=!1,Yo=()=>{Go||(Go=!0,ai().catch(()=>{}),Et().catch(()=>{Go=!1}))},Zo=(e,t,n)=>{t.length>0&&Yo(),Wo(e,t,n),Ir()},ts=null,is=()=>{if(ts)return;let t=e=>{let t=e.composedPath();t.includes(W)||tt&&t.includes(tt)||vs(!1,`user`)};ts=t,(e.ownerDocument??document).addEventListener(`pointerdown`,t,!0)},as=()=>{ts&&=((e.ownerDocument??document).removeEventListener(`pointerdown`,ts,!0),null)};Q.push(()=>as());let ss=null,ls=()=>{if(ss)return;let t=e=>{e.key===`Escape`&&(e.isComposing||vs(!1,`user`))};ss=t,(e.ownerDocument??document).addEventListener(`keydown`,t,!0)},us=()=>{ss&&=((e.ownerDocument??document).removeEventListener(`keydown`,ss,!0),null)};Q.push(()=>us());let ds=!1,fs=/* @__PURE__ */ new Set,ms=()=>r.launcher?.composerBar?.peek?.streamAnimation||r.features?.streamAnimation,hs=()=>{if(!L())return;let t=nt.peekBanner,n=nt.peekTextNode;if(!t||!n)return;if(z){t.classList.remove(`persona-pill-peek--visible`);return}let r=$?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){t.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=ms(),c=Rm(s),l=c.type===`none`?null:Pi(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!fs.has(l.name)&&(ah(l,e),fs.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?Wm(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=$m();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),_m(n,e)}else{let e=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=Pt(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=Zm(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:e}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=Qm(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}_m(n,s),l.onAfterRender?.({container:n,bubble:t,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=ta||ds;t.classList.toggle(`persona-pill-peek--visible`,h)};if(L()){let e=nt.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),vs(!0,`user`)};e.addEventListener(`pointerdown`,t),Q.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{ds||(ds=!0,hs())},n=()=>{ds&&(ds=!1,hs())};G.addEventListener(`pointerenter`,t),G.addEventListener(`pointerleave`,n),Q.push(()=>{G.removeEventListener(`pointerenter`,t),G.removeEventListener(`pointerleave`,n)}),tt&&(tt.addEventListener(`pointerenter`,t),tt.addEventListener(`pointerleave`,n),Q.push(()=>{tt.removeEventListener(`pointerenter`,t),tt.removeEventListener(`pointerleave`,n)}))}let gs=e=>{let t=r.launcher?.composerBar??{},n=t.expandedSize??`anchored`,i=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=W.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,tt){let e=tt.style;e.bottom=i,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${i} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},_s=()=>{if(z&&Yo(),!R())return;if(L()){let e=(r.launcher?.composerBar??{}).expandedSize??`anchored`,t=z?`expanded`:`collapsed`;W.dataset.state=t,W.dataset.expandedSize=e,tt&&(tt.dataset.state=t,tt.dataset.expandedSize=e),W.style.removeProperty(`display`),W.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),G.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),gs(z),K.style.display=z?`flex`:`none`,Hr(),z?(is(),ls()):(as(),us()),hs();return}let t=Yh(r),n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileBreakpoint??640,a=r.launcher?.mobileFullscreen??!0,o=n.innerWidth<=i,s=a&&o&&I,c=Zh(r).reveal;z?(W.style.removeProperty(`display`),W.style.display=t?`flex`:``,W.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),G.classList.remove(`persona-scale-95`,`persona-opacity-0`),G.classList.add(`persona-scale-100`,`persona-opacity-100`),Tu?(Tu.setPanelOpen(!0),Tu.element.style.display=`none`):Eu&&(Eu.style.display=`none`)):(t?t&&(c===`overlay`||c===`push`)&&!s?(W.style.removeProperty(`display`),W.style.display=`flex`,W.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),G.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(W.style.setProperty(`display`,`none`,`important`),W.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),G.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(W.style.display=``,W.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),G.classList.remove(`persona-scale-100`,`persona-opacity-100`),G.classList.add(`persona-scale-95`,`persona-opacity-0`)),Tu?(Tu.setPanelOpen(!1),Tu.element.style.display=t?`none`:``):Eu&&(Eu.style.display=t?`none`:``))},vs=(t,n=`user`)=>{if(!R()||z===t)return;let i=z;z=t,_s();let a=(()=>{let t=r.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileFullscreen??!0,a=r.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=Yh(r)&&i&&o,c=L()&&(r.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return t||i&&o&&I||s||c})();if(z&&a){if(!ki){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&(ki=Wh(n,r.launcher?.zIndex??1e5))}Ai||=qh(e.ownerDocument)}else z||(ki?.(),ki=null,Ai?.(),Ai=null);z&&(Au(),Eo()||(Wt()===`follow`?vo(!0):xo()));let o={open:z,source:n,timestamp:Date.now()};z&&!i?k.emit(`widget:opened`,o):!z&&i&&k.emit(`widget:closed`,o),k.emit(`widget:state`,{open:z,launcherEnabled:I,voiceActive:Fa.active,streaming:$.isStreaming()})},ys={inputDisabled:!1,sendDisabled:!1},bs=()=>ys.inputDisabled,xs=()=>ht(r.voiceRecognition?.provider)&&!!$&&($.isBargeInActive()||[`listening`,`processing`,`speaking`].includes($.getVoiceStatus())),ws=()=>ys.inputDisabled||ys.sendDisabled,Ts=()=>(ys.inputDisabled?ys.inputReason:void 0)??(ys.sendDisabled?ys.sendReason:void 0);function Es(){if(!X)return;if(wn.getState().phase===`streaming`){X.disabled=!1;return}let e=Sn?!Sn.isReady():!1;X.disabled=ws()||e}function Ds(){if(!Nt)return;let e=wn.getState(),t=r.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Nt.toggleAttribute(`data-persona-send-hidden`,t)}function Os(){let e=Ts();if(L()){let t=ut??Ot;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),Ot.toggleAttribute(zw,!!e)}else if(e)pt.setAttribute(`role`,`status`),pt.setAttribute(`aria-live`,`polite`),pt.setAttribute(zw,``),pt.removeAttribute(Bw),pt.textContent=e,dt(pt,r.statusIndicator??{},`idle`);else if(pt.hasAttribute(zw)&&(pt.removeAttribute(`role`),pt.removeAttribute(`aria-live`),pt.removeAttribute(zw),m)){let e=$.getStatus();$e(pt,Qe(e),r.statusIndicator??{},e)}}function ks(){let e=es(r.composer?.inputDisabled),t=es(r.composer?.sendDisabled);ys={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},wn.setInputDisabled(e.disabled),wn.setSendDisabled(t.disabled);let n=wn.getState().phase===`streaming`,i=e.disabled,a=n||i;Y&&(Y instanceof HTMLTextAreaElement?Y.disabled=i:Y.setAttribute(`contenteditable`,i?`false`:`true`),Y.setAttribute(`aria-disabled`,i?`true`:`false`)),Lt&&(Lt.disabled=i),zt&&(zt.disabled=i);for(let e of Cn?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=i});Z&&(Z.disabled=i||n&&!xs()),zi.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),Ks.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),Ot.dataset.personaComposerStreaming=n?`true`:`false`,Ot.dataset.personaComposerInputDisabled=i?`true`:`false`,Ot.dataset.personaComposerSendDisabled=ws()?`true`:`false`,Ot.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),Es(),Os()}let As=e=>{wn.setStreaming(e),Ft(e?`stop`:`send`),ks()},js=()=>{Fa.active||Y&&Y.focus()};k.on(`widget:opened`,()=>{r.autoFocusInput&&setTimeout(()=>js(),200)});let Ms=null,Ns=!1,Ps=!mt.hidden,Fs=null,Is=!P,Ls=null;Q.push(()=>{Ls?.cancel(),Ls=null});let Rs=t=>{let n=w_(t);if(n===hn)return;hn=n,e.setAttribute(`data-persona-conversation-state`,n);let r=_n();bn(),Is&&(Ls?.cancel(),Ls=y_(Ot,n===`active`?r:_n(),n===`active`?`drop`:`rise`,mn().layout===`centered`?320:260)),Fo()},zs=null,Bs,Vs=null,Hs=null,Us=!1,Ws=e=>{let t=mn(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==zs||t.icon!==Bs)&&(zs=n,Bs=t.icon,l_({host:mt,iconHolder:gt,kicker:vt,title:yt,subtitle:bt,starterSuggestions:rt},t));let i=t.message===void 0?null:`${r.layout?.messages?.layout??`bubble`}|${t.message}`;i!==Vs&&(Vs=i,g_(_t,t.message,r));let a=e??($?$.getMessages():r.initialMessages);Rs(a);let o=Ns,s=!o&&T_(t,a),c=s!==Ps;if(Ps=s,Hs){Fs?.cancel(),Fs=null,o!==Us&&(Us=o,o?m_(q,mt,null):p_(q,mt,Hs)),c_(q,mt,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Is){Fs=v_(mt,e=>{Fs===e&&(Fs=null),!Ps&&!Hs&&(c_(q,mt,!1),Fo()),e?.cancel()});return}if(Fs){if(!s&&!o)return;Fs.cancel(),Fs=null}let l=!mt.hidden;c_(q,mt,s),!s&&l&&Fo()},Gs=[],Ks=[],qs=!1,Js=null,Ys,Xs=()=>{Ks.length=0;let e=Gs.splice(0,Gs.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Q.push(Xs);let Zs=(e,t)=>{let n=$h(e,t);if(!n)return r.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),B(`span`);let i=r.suggestions?.starters,a=rg({item:{...n,behavior:n.behavior??i?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:i?.variant??`card`,streaming:m?$.isStreaming():!1,config:r,plugins:d,chipsConfig:r.suggestionChipsConfig,session:$,getTextarea:()=>Y,eventTarget:mt,submitPrompt:Cl});return Ks.push(a),a},Qs=()=>{if(qs)return;qs=!0;let e=mn();Js=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,Ys=e.icon;try{Xs(),m_(q,mt,Hs),Hs=null,Us=!1;let t=$?$.getMessages():r.initialMessages,n=T_(e,t),i=0,a=null;for(let t of d)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>mt,sendMessage:e=>{if(!$||$.isStreaming())return;let t=e.trim();t&&$.sendMessage(t)},requestRender:()=>Qs(),renderStarter:e=>Zs(e,i++),storage:h(t.id),onCleanup:e=>{Gs.push(e)}}),a))break;a&&a!==mt&&(Hs=a,p_(q,mt,a))}finally{qs=!1}Ws()},$s=()=>{let e=mn();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==Js||e.icon!==Ys)&&Qs()},ec=()=>{Ws(),tr||(Y.placeholder=Gf(wn.getState().activeModeIds,r.composer?.modes)??r.copy?.inputPlaceholder??`How can I help...`,!(r.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(X.textContent=r.copy?.sendButtonLabel??`Send`)),Y.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,Y.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},nc=!!r.setStoredConversationId,rc=e=>ce(t=>{let n={...t};return delete n[e],n}),ic=e=>{let t=N[e];return typeof t==`string`?t:null},ac=()=>{let e=N.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};r.clientToken&&(r={...r,getStoredSessionId:()=>ic(`sessionId`),setStoredSessionId:e=>{ce(t=>({...t,sessionId:e}))},clearStoredSessionId:r.clearStoredSessionId??(()=>rc(`sessionId`)),getStoredConversationId:r.getStoredConversationId??(()=>ic(`conversationId`)),setStoredConversationId:r.setStoredConversationId??(e=>{ce(t=>({...t,conversationId:e}))}),clearStoredConversationId:r.clearStoredConversationId??(()=>rc(`conversationId`))});let oc=()=>r.clientToken??null,sc=e=>qS(e,ke(),r.persistState===!1),cc=oc(),lc=cc?sc(cc):null,uc=()=>{let e=N.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},dc={...lc?{visitorStore:lc}:{},historyBootstrapReady:r.features?.history?.enabled===!0&&!kw()?Promise.all([ne,F]).then(()=>{}):ne,getStoredMessageCursor:()=>ic(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?rc(`historyMessageCursor`):ce(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:uc,setPendingDisplayProjections:e=>{e?ce(t=>({...t,pendingDisplayProjections:e})):rc(`pendingDisplayProjections`)},getStoredResumableHandle:ac,setStoredResumableHandle:e=>{e?ce(t=>({...t,durableResume:e})):rc(`durableResume`)},shouldResumeDurableConversation:()=>ee&&ac()!==null,...nc?{}:{getStoredConversationRevision:()=>ic(`conversationRevision`),setStoredConversationRevision:e=>{e===null?rc(`conversationRevision`):ce(t=>({...t,conversationRevision:e}))}}};if(ee){let t=r.onExecutionState,n=e.ownerDocument.defaultView,i=!1,a=()=>i=!0,o=()=>i=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Q.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),r={...r,reconnectStream:r.reconnectStream??(e=>$.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!i)&&dc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let fc=()=>{let e=oc();if(e&&lc?.matches(e,ke(),r.persistState===!1)||!e&&!lc)return;lc?.destroy(),lc=e?sc(e):null;let t={...dc};lc?t.visitorStore=lc:delete t.visitorStore,dc=t,$.setHistoryInternals(dc)},mc=null,hc=()=>{mc??=setInterval(()=>{let e=J.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(mc),mc=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?st(t-n):pn(t-n))})},100)},gc=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>gc(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&gc(n[e],r[e]))},_c=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},vc=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!Nw(e),yc=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&vc(r)&&vc(i)&&gc(_c(r),_c(i))},bc=null,xc=null,Sc=null,Cc=null,wc=null,Tc=e=>{if(!ee)return Ja(e);wc=e,queueMicrotask(()=>{wc===e&&(wc=null,Ja(e))})},Ec=e=>{bc=e;let t,n;xc=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!xc&&vc(i)&&(xc={index:r,id:i.id}),t&&n&&xc)break}Zo(J,e,Ce),kx()?.updateInlineArtifactBlocks(J,Gr.artifacts,{suppressTransition:ta}),hc(),Ws(e),Qi(e),vo(!ta),Vo(e),e.length===0&&(jo(),Sa=!0,Ca=!1,wa=null,Ta=!1),!ya||ba?(ya=!0,xa=t?.id??null,Da=n?.id??null):t&&t.id!==xa?(xa=t.id,Lo(t.id)):n&&n.id!==Da&&Ro(),n&&(Da=n.id),Bo(e);let r=Fa.lastUserMessageId;t&&t.id!==r&&(Fa.lastUserMessageId=t.id,k.emit(`user:message`,t)),Fa.lastUserMessageWasVoice=!!t?.viaVoice,Tc(e),hs()},Dc=()=>{Cc!==null&&(cancelAnimationFrame(Cc),Cc=null);let e=Sc;Sc=null,e&&Ec(e)},Oc=()=>{Cc!==null&&cancelAnimationFrame(Cc),Cc=null,Sc=null},kc=e=>{let t=Sc??bc;ta&&t&&xc&&yc(t,e,xc)?(Sc=e,Cc===null&&(Cc=requestAnimationFrame(()=>{Cc=null;let e=Sc;Sc=null,e&&Ec(e)}))):e.length===0?(Oc(),Ec(e)):(Dc(),Ec(e))};$=new Kd(r,{onMessagesChanged(e){kc(e)},onStatusChanged(e){let t=r.statusIndicator??{};$e(pt,(e=>e===`idle`?t.idleText??Vr.idle:e===`connecting`?t.connectingText??Vr.connecting:e===`connected`?t.connectedText??Vr.connected:e===`error`?t.errorText??Vr.error:e===`paused`?t.pausedText??Vr.paused:e===`resuming`?t.resumingText??Vr.resuming:Vr[e])(e),t,e),Je()},onStreamingChanged(e){e||($?.getMessages().length===0?Oc():Dc()),ta=e,As(e),Je(),$&&Zo(J,$.getMessages(),Ce),e||(vo(!0),Ao(),Xi=!0,$&&Zi($.getMessages(),Fr(r))),ho(),dn(e?`Responding…`:`Response complete.`),hs()},onVoiceStatusChanged(e){if(k.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!ht(r.voiceRecognition?.provider))return;let t=$.getVoiceNotice();switch(t&&ul(t,1e4),e){case`listening`:if(!Na){let e=$.getVoiceDisclosure();e&&(Na=!0,L()?(Pa=Y.placeholder,Y.placeholder=e,dn(e)):ul(e,1e4))}uu(),su();break;case`processing`:uu(),cu();break;case`speaking`:uu(),lu();break;default:e===`idle`&&$.isBargeInActive()?(uu(),su(),Z?.setAttribute(`aria-label`,`End voice session`)):(Fa.active=!1,Na=!1,Pa!==null&&(Y.placeholder=Pa,Pa=null),uu(),za(`system`),Ra||Ba())}},onArtifactsState(e){Gr=e,e.artifacts.length===0&&(Yr=!1),kx()?.updateInlineArtifactBlocks(J,e.artifacts,{suppressTransition:ta}),Si(),Ja()},onHistoryStateChanged(e){Ke(e)},onHistoryNotice(e){qe(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?k.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?k.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):k.emit(`stream:resumed`,{executionId:t,after:n})}},dc),Qr.current=$,Q.push(()=>$.cancel()),Q.push(()=>{$.destroy(),lc?.destroy(),lc=null});let Ac=null;if($.onReadAloudChange((e,t)=>{kr=e,jr=t,Ir();let n=e??Ac;e&&(Ac=e);let r=n?$.getMessages().find(e=>e.id===n)??null:null;k.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Ac=null)}),m=!0,ya=!0,r.voiceRecognition?.enabled===!0&&ht(r.voiceRecognition.provider))try{$.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let jc=null,Mc=null,Nc=!1,Pc=$.getHistoryState(),Fc=()=>r.features?.history?.enabled===!0,Ic=e=>{e&&(sn.textContent=``,sn.textContent=e)},Lc=()=>{p.forEach(e=>e()),p=[];let t=jc,n=t?.railCollapseShortcut();t&&n&&p.push(f.register({id:`history-rail-collapse`,combo:n.combo,scope:r.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>He&&Ue===`rail`&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of r.layout?.header?.trailingActions??[])t.shortcut&&p.push(f.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let n=e.querySelector(`[data-persona-header-action="${t.id}"]`);n?n.click():r.layout?.header?.onAction?.(t.id)}}));for(let e of d)for(let t of e.shortcuts??[])p.push(f.register({...t,id:`${e.id}:${t.id}`}))};Lc();let Rc=null,zc=!1,Bc=()=>{if(!Ct)return;let e=r.layout?.header?.titleSource===`conversation`,t=e&&Rc?.trim()||null;Ct.textContent=t??r.launcher?.title??`Chat Assistant`;let n=Ct.closest(`.persona-combo-btn`);if(!n)return;let i=!e||$.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,i?`false`:`true`),n.setAttribute(`aria-haspopup`,i?`true`:`false`),i||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=i?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=i?``:`none`)},Vc=e=>{e!==Rc&&(Rc=e,Bc())},Hc=e=>{zc=e?.starred===!0,Vc(e&&e.title.trim()||null),Bc()};Bc(),K.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=$.getActiveConversationId();n&&(t===`delete`?Kc(e=>e.requestDeleteConversation(n)):t===`star`&&$.canUpdateConversations()&&Kc(e=>e.updateHistoryConversation(n,{starred:!zc})).catch(()=>{}))}),Ke=e=>{Pc=e,jc?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),As(e.sendBlocked||ta),jc?.syncEarlierMessagesPill()},qe=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(na.clear(),jo(),_o()),Ic(e.message),jc?.historySurface?.view.refresh()};let Uc={get actionManager(){return de},get activeConversationTitle(){return Rc},announceHistory:Ic,get applyRailChrome(){return Ge},set applyRailChrome(e){Ge=e},get artifactSplitRoot(){return ci},get body(){return q},get config(){return r},get container(){return K},get conversationOpenPendingEl(){return Ms},set conversationOpenPendingEl(e){Ms=e},get conversationOpenTakeover(){return Ns},set conversationOpenTakeover(e){Ns=e},currentKeyPrefix:ke,destroyCallbacks:Q,eventBus:k,get footer(){return Ot},get header(){return Tt},get historyChromeSync(){return Je},set historyChromeSync(e){Je=e},historyFeatureEnabled:Fc,get historyInternals(){return dc},set historyInternals(e){dc=e},get historyPresentation(){return Ue},set historyPresentation(e){Ue=e},get historySessionState(){return Pc},get historyVisible(){return He},set historyVisible(e){He=e},get isStreaming(){return ta},jumpToBottomInstant:xo,get lastAppliedMessages(){return bc},set lastAppliedMessages(e){bc=e},get launcherEnabled(){return I},get launcherSurfaceInstance(){return Tu},maybeFocusInput:js,messageCache:na,get messagesWrapper(){return J},mount:e,get open(){return z},panel:G,panelElements:nt,get persistentMetadata(){return N},set persistentMetadata(e){N=e},plugins:d,get reapplyHistoryHostChrome(){return We},set reapplyHistoryHostChrome(e){We=e},repinAnchoredMessage:Fo,resetAnchorState:jo,restoreScrollPosition:Eo,resumeAutoScroll:_o,runStorageMutation:qa,get session(){return $},setActiveConversationSummary:Hc,storageAdapter:A,get suppressScrollSend(){return ba},set suppressScrollSend(e){ba=e},syncScrollToBottomButton:ho,updateWelcome:Ws,getHistoryProviderFactory:Aw,historyErrors:{HistoryClientError:no,HistoryProviderError:fo},isDockedMountMode:Yh,renderLucideIcon:U,loadHistoryView:cw,createHeaderIconButton:lg,attachTooltip:Do},Wc=e=>(!jc&&!Nc&&(jc=e.createHistoryShell(Uc),jc.railCollapseShortcut()&&Lc()),jc),Gc=()=>{if(jc)return Promise.resolve(jc);let e=kw();return e?Promise.resolve(Wc(e)):(Mc??=Ow().then(Wc,e=>{throw Mc=null,e}),Mc)},Kc=e=>{let t=kw(),n=jc??(t?Wc(t):null);return n?e(n):Gc().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},qc=()=>{jc?.syncHistoryPresentation()};Q.push(()=>{Nc=!0}),Fc()&&Gc().catch(()=>{}).finally(re),r.clientToken&&(r.features?.history?.enabled===!0||r.sessionInit===`mount`)&&$.initClientSession().then(()=>{let e=jc;if(e?.historyAvailable())return $.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{jc?.syncEarlierMessagesPill()}).catch(e=>{r.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Jc=()=>$.warmClientSession(),Yc=e=>{let t=r.sessionInit??`input`,n=ir?.input??Y,i=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&i===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?i===n&&e.key===`Tab`:(ir?.form??ut)?.contains(i)))&&Jc()},Xc=[`input`,`pointerdown`,`keyup`];Xc.forEach(t=>e.addEventListener(t,Yc));let Zc,Qc,$c=()=>{let e=Qc;Qc=void 0;try{typeof e==`function`&&e()}catch{}},tl=()=>{let t=r.clientToken&&typeof r.sessionInit==`function`?r.sessionInit:void 0;if(t!==Zc){$c(),Zc=t;try{Qc=t?.({warm:Jc,mount:e})}catch{}}};tl(),Q.push(()=>{Xc.forEach(t=>e.removeEventListener(t,Yc)),$c()}),(Ee||r.onSSEEvent)&&$.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Be(e,t)});let nl=()=>{let e=r.resume??(ee?dc.getStoredResumableHandle?.():null);e&&typeof r.reconnectStream==`function`&&$.resumeFromHandle(e)};P?P.then(e=>{if(e){if(e.metadata&&(N=Kw(e.metadata),de.syncFromMetadata()),e.messages?.length){ba=!0;try{$.hydrateMessages(e.messages)}finally{ba=!1}Yo()}e.artifacts?.length&&$.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),eo(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Is=!0,te(),nl()}):(eo(ie),nl());let rl=()=>{L()&&(z||(r.launcher?.composerBar?.expandOnSubmit??!0)&&vs(!0,`auto`))},il=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Zw(i)}}:e:t,al=()=>{let e=Y.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},ol=!1,sl=null,cl=()=>{Y.value=``,Y.style.height=`auto`,Tn(),kl()},ll=null;function ul(e,t=4e3){dn(e),!L()&&pt&&(pt.hasAttribute(zw)||(pt.setAttribute(Bw,``),pt.setAttribute(`role`,`status`),pt.setAttribute(`aria-live`,`polite`),pt.textContent=e,dt(pt,r.statusIndicator??{},`idle`),ll&&clearTimeout(ll),ll=setTimeout(()=>{if(ll=null,pt?.hasAttribute(Bw)&&(pt.removeAttribute(Bw),pt.removeAttribute(`role`),pt.removeAttribute(`aria-live`),m)){let e=$.getStatus();$e(pt,Qe(e),r.statusIndicator??{},e)}},t)))}function dl(){let e=wn.getState().pendingSubmission;e&&(Un(void 0),Y&&(Y.value=e.text,Y.dispatchEvent(new Event(`input`,{bubbles:!0})),Tn()),e.options.selectedModelId&&(wn.setSelectedModelId(e.options.selectedModelId),Pn?.repaint()),e.options.activeModeIds?.length&&Mn(e.options.activeModeIds),e.options.quote&&zn(e.options.quote),Y?.focus())}let fl=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},hl=(e={})=>{let t=(e.overrideText??Y?.value??``).trim();return e.resolveInlineCommand&&t?(Cn?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>gl(e,t,n)):gl(e,t,null)},gl=(e,t,n)=>{if(n?.kind===`action`){cl(),Cn?.clear(),En();return}let i=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!rp({text:a,hasAttachments:(Sn?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:Sn?.isReady()??!0,hasMentions:Cn?.hasMentions()??!1,hasServerMentions:!!i,inputDisabled:bs(),sendDisabled:ws()}))return;let s=$.isStreaming()?Vn():`block`;if(s===`defer-one`&&!e.pending){if(wn.getState().pendingSubmission){ul(`One message is already queued. Edit or remove it first.`);return}_l({intent:e,sendText:a,serverMentions:i});return}let c={text:a,mentionRefs:[...Cn?.getMentionRefs()??[],...i?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:al(),options:{...wn.getState().selectedModelId&&{selectedModelId:wn.getState().selectedModelId},...wn.getState().activeModeIds.length>0&&{activeModeIds:[...wn.getState().activeModeIds]},...wn.getState().quote&&{quote:{...wn.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!Sn?.hasAttachments())return;let e=[...Sn.getContentParts()];return c.text&&e.push(ka(c.text)),e};c.contentParts=l();let u=()=>{ca(),rl();let t=Cn?.collectForSubmit()??null,n=il(t,i),a=l();e.consumeDraft!==!1&&cl();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&$.cancel(),$.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),Sn?.hasAttachments()&&Sn.clearAttachments(),t&&Cn?.clear(),En();let d=wn.getState().activeModeIds,f=Wf(d,r.composer?.modes);f.length!==d.length&&Mn(f),wn.getState().quote&&zn(void 0),to(),yr.release(),Cr()},d=r.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;sl=f;let p=e=>{sl=null,e.status===`error`?fl(e.error):e.status===`proceed`&&u()},m=op(d,c,f.signal);if(!(m instanceof Promise))p(m);else return wn.setPreparing(!0),m.then(p).finally(()=>wn.setPreparing(!1))};function _l(e){let t=wn.getState(),n=Sn?.hasAttachments()??!1,r=n?[...Sn.getContentParts()]:[];n&&e.sendText&&r.push(ka(e.sendText)),Un(np({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...Cn?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:al(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&cl(),n&&Sn.clearAttachments(),Cn?.clear(),En(),t.quote&&zn(void 0),to(),yr.release(),Cr(),dn(`Message queued. It sends when the response finishes.`)}function vl(){let e=wn.getState().pendingSubmission;e&&(Un(void 0),wl(e.text,{consumeDraft:!1,pending:e}))}function yl(e){if(r.messageActions?.showEdit!==!0)return;let t=$.getMessages().find(t=>t.id===e);t&&Ul(t)&&oa!==e&&(ca(),oa=e,sa=Yf({messageId:e,initialText:t.content,onSave:t=>bl(e,t),onCancel:()=>ca()}),na.delete(e),Zo(J,$.getMessages(),Ce),sa.focus())}function bl(e,t){let n=sa;oa=null,sa=null,n?.destroy(),na.delete(e),$.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Fo():Zo(J,$.getMessages(),Ce)}function xl(e){if($.isStreaming())return;let t=Vl($.getMessages(),e);t&&(ca(),$.resubmitFrom(t,{reason:`retry`})&&Fo())}Lr={regenerate:xl,edit:yl,quote:e=>{let t=$.getMessages().find(t=>t.id===e)?.content?.trim();t&&(zn({text:t,messageId:e}),Y?.focus())}};let Sl=async e=>{if(!ol){ol=!0;try{await hl({resolveInlineCommand:!0,...e})}finally{ol=!1}}};function Cl(e){ws()||(cl(),wl(e,{consumeDraft:!1}))}let wl=(e,t)=>{if(ol)return;ol=!0;let n=()=>{ol=!1};try{let r=hl({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Tl=e=>{e.preventDefault(),$.isStreaming()?($.cancel(),H?.reset(),Fe?.update()):ol||Sl()},El=()=>r.features?.composerHistory!==!1,Dl={...ym},Ol=!1,kl=()=>{Dl={...ym}},Al=()=>$.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),jl=e=>{if(!Y)return;Ol=!0,Y.value=e,Y.dispatchEvent(new Event(`input`,{bubbles:!0})),Ol=!1;let t=Y.value.length;Y.setSelectionRange(t,t)},Ml=e=>{Ol||(e.isComposing||Cn?.handleInput(e.inputType??void 0),kl())},Nl=()=>({submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:Jo(Y)}),Pl=e=>{if(Y&&!bs()&&(e.isComposing||!Cn?.handleKeydown(e))){if(El()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=Y.selectionStart===0&&Y.selectionEnd===0,n=bm({direction:e.key===`ArrowUp`?`up`:`down`,history:Al(),currentValue:Y.value,atStart:t,state:Dl});if(Dl=n.state,n.handled){e.preventDefault(),n.value!==void 0&&jl(n.value);return}}if(Xo(e,Nl())){if($.isStreaming()){if(e.preventDefault(),Vn()===`block`||ol||ws())return;kl(),Sl()}else ol||ws()?e.preventDefault():(kl(),e.preventDefault(),X.click())}}},Fl=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(K)&&(sl?(sl.abort(),sl=null,e.preventDefault(),e.stopImmediatePropagation()):$.isStreaming()&&($.cancel(),H?.reset(),Fe?.update(),kl(),e.preventDefault(),e.stopImmediatePropagation()))},Il=async e=>{if(r.attachments?.enabled!==!0||!Sn||bs())return;let t=Hw(e.clipboardData);t.length!==0&&(e.preventDefault(),await Sn.handleFiles(t))},Ll=null,Rl=!1,zl=null,Bl=null,Wl=()=>r.voiceRecognition?.completionBehavior===`review`;function Gl(e){Z?.setAttribute(`data-state`,e),e===`recording`?eu():tu()}let Kl=`--persona-voice-level`,ql=.5,Jl=null,Yl=-1,Xl=0,Zl=()=>{let e=[],t=It??Z?.parentElement??null;return t&&e.push(t),Ot&&e.push(Ot),e},Ql=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Yl){Yl=t;for(let e of Zl())e.style.setProperty(Kl,String(t))}},$l=()=>{Yl=-1,Xl=0;for(let e of Zl())e.style.removeProperty(Kl)};function eu(){if(Jl!==null)return;if(typeof requestAnimationFrame!=`function`){Ql(m?$.getVoiceLevel()??ql:ql);return}let e=()=>{Jl=requestAnimationFrame(e);let t=m?$.getVoiceLevel():null;t===null?Ql(ql):(Xl+=(t-Xl)*.3,Ql(Xl))};Jl=requestAnimationFrame(e)}function tu(){Jl!==null&&(cancelAnimationFrame(Jl),Jl=null),$l()}let nu=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ru=(e=`user`)=>{if(Rl||$.isStreaming())return;let t=nu();if(!t)return;Ll=new t;let n=r.voiceRecognition??{},i=n.pauseDuration??2e3;Ll.continuous=n.provider?.browser?.continuous??!0,Ll.interimResults=!0,Ll.lang=n.provider?.browser?.language??`en-US`;let a=Y.value;Ll.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let r=a+t+n;Y.value=r,Tn(),zl&&clearTimeout(zl),(t||n)&&(zl=window.setTimeout(()=>{if(Y.value.trim()&&Ll&&Rl){if(iu(),Wl())return;Sl({viaVoice:!0})}},i))},Ll.onerror=e=>{e.error!==`no-speech`&&iu()},Ll.onend=()=>{if(Rl){let e=Y.value.trim();!Wl()&&e&&e!==a.trim()&&Sl({viaVoice:!0}),iu()}};try{if(Ll.start(),Rl=!0,Fa.active=!0,e!==`system`&&(Fa.manuallyDeactivated=!1),za(e),Ba(),Cr(),Z){let e=r.voiceRecognition??{};Bl={backgroundColor:Z.style.backgroundColor,color:Z.style.color,borderColor:Z.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,i=e.recordingBorderColor;if(Z.classList.add(`persona-voice-recording`),Gl(`recording`),Z.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,Z.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=Z.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}i&&(Z.style.borderColor=i),Z.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{iu(`system`)}},iu=(e=`user`)=>{if(Rl){if(Rl=!1,zl&&=(clearTimeout(zl),null),Ll){try{Ll.stop()}catch{}Ll=null}if(Fa.active=!1,za(e),Ba(),Cr(),Z){if(Z.classList.remove(`persona-voice-recording`),Gl(`idle`),Bl){Z.style.backgroundColor=Bl.backgroundColor,Z.style.color=Bl.color,Z.style.borderColor=Bl.borderColor;let e=Z.querySelector(`svg`);e&&e.setAttribute(`stroke`,Bl.color||`currentColor`),Bl=null}Z.setAttribute(`aria-label`,`Start voice recognition`)}}},au=null,ou=e=>{let t=t=>{au??=t.createMicStateStyles({mic:()=>Z,config:()=>r,session:()=>$,get original(){return Bl},set original(e){Bl=e},setMicState:Gl,renderIcon:U,iconFallbackPx:24}),e(au)},n=xd();n?t(n):bd().then(t,()=>{})},su=()=>ou(e=>e.recording()),cu=()=>ou(e=>e.processing()),lu=()=>ou(e=>e.speaking()),uu=()=>ou(e=>e.reset()),du=()=>{if(!bs()){if(ht(r.voiceRecognition?.provider)){let e=$.getVoiceStatus(),t=$.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Fa.active=!1,Fa.manuallyDeactivated=!0,Ba(),za(`user`),uu()});return}$.toggleVoice().then(()=>{Fa.active=La(),Fa.manuallyDeactivated=!Fa.active,Ba(),za(`user`),Fa.active?su():uu()})}else if(Rl){let e=Y.value.trim();Fa.manuallyDeactivated=!0,Ba(),iu(`user`),e&&!Wl()&&Sl()}else Fa.manuallyDeactivated=!1,Ba(),ru(`user`)}};qn=du;let fu=()=>$.prewarmVoice(),pu=()=>{let e=r.voiceRecognition;return e?.enabled===!0?e.prewarm??(r.clientToken?`hover`:!1):!1},mu=e=>{pu()===`hover`&&Z?.contains(e.target)&&fu()},hu=[`pointerover`,`pointerdown`,`focusin`];hu.forEach(t=>e.addEventListener(t,mu));let gu,_u=null,vu,yu=()=>{let e=vu;vu=void 0;try{typeof e==`function`&&e()}catch{}},bu=()=>{let t=pu(),n=typeof t==`function`&&Z?t:void 0,r=n?Z:null;if((n!==gu||r!==_u)&&(yu(),gu=n,_u=r,n&&r))try{vu=n({warm:fu,micButton:r,mount:e})}catch{}};bu(),Q.push(()=>{hu.forEach(t=>e.removeEventListener(t,mu)),yu()}),Z&&Q.push(()=>{ht(r.voiceRecognition?.provider)?($.isVoiceActive()&&$.toggleVoice(),uu()):iu(`system`)});let xu=k.on(`assistant:complete`,()=>{wn.getState().pendingSubmission&&setTimeout(()=>{$.isStreaming()||vl()},0)});Q.push(xu);let Su=k.on(`assistant:complete`,()=>{Ia&&(Fa.active||Fa.manuallyDeactivated||(Ia!==`assistant`||Fa.lastUserMessageWasVoice)&&setTimeout(()=>{!Fa.active&&!Fa.manuallyDeactivated&&(ht(r.voiceRecognition?.provider)?$.toggleVoice().then(()=>{Fa.active=$.isVoiceActive(),za(`auto`),$.isVoiceActive()&&su()}):ru(`auto`))},600))});Q.push(Su);let Cu=k.on(`action:resubmit`,()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Q.push(Cu);let wu=()=>{vs(!z,`user`)},Tu=null,Eu=null;if(I&&!L()){let{instance:e,element:t}=G_({config:r,plugins:d,onToggle:wu});Tu=e,e||(Eu=t)}Tu?e.appendChild(Tu.element):Eu&&e.appendChild(Eu),_s(),Qi(),ec(),Qs(),As($.isStreaming()),Eo()||(Wt()===`follow`?vo(!0):xo()),Ha(),me&&(!I||L()?setTimeout(()=>js(),0):z&&setTimeout(()=>js(),200));let Du=null,Ou=()=>{Du&&(Du.disconnect(),Du.observe(Ot),Du.observe(K),Du.observe(mt))},ku=fn(),Au=()=>{if(L()){vn(),_s();return}let t=Yh(r),n=r.launcher?.sidebarMode??!1,i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640,s=i.innerWidth<=o,c=a&&s&&I;try{if(c){Hr(),Ur=xi();return}let e=!1;ve&&(ve=!1,Hr(),e=!0);let i=xi();if(!e&&i!==Ur&&(Hr(),e=!0),Ur=i,e&&fi(),!I&&!t){G.style.height=``,G.style.width=``;return}if(!n&&!t){let e=D_(r);G.style.width=e.width,G.style.maxWidth=e.maxWidth}yi(),Oi()}finally{vn(),bn();let t=fn();if(t!==ku&&(ku=t,Ws(),Qi()),_s(),z&&I){let t=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),n=r.launcher?.sidebarMode??!1,i=r.launcher?.mobileFullscreen??!0,a=Yh(r)&&i&&t,o=n||i&&t&&I||a;if(o&&!Ai){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&!ki&&(ki=Wh(n,r.launcher?.zIndex??1e5)),Ai=qh(e.ownerDocument)}else o||(ki?.(),ki=null,Ai?.(),Ai=null)}}};Au();let ju=e.ownerDocument.defaultView??window;if(ju.addEventListener(`resize`,Au),Q.push(()=>ju.removeEventListener(`resize`,Au)),typeof ResizeObserver<`u`){Du=new ResizeObserver(()=>{bn()}),Ou(),Q.push(()=>{Du?.disconnect(),Du=null});let e=new ResizeObserver(()=>{qc()});e.observe(K),Q.push(()=>e.disconnect())}ju.addEventListener(`resize`,qc),Q.push(()=>ju.removeEventListener(`resize`,qc)),fa=q.scrollTop;let Mu=Om(q),Nu=()=>{Ei();let e=q.scrollTop,t=Om(q),n=t<Mu;if(Mu=t,!Gt()){fa=e,ho();return}let{action:r,nextLastScrollTop:i}=Am({following:da.isFollowing(),currentScrollTop:e,lastScrollTop:fa,nearBottom:km(q,24),userScrollThreshold:4,isAutoScrolling:ma||ha||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});fa=i,r===`resume`?wo()||_o():r===`pause`&&go()};if(q.addEventListener(`scroll`,Nu,{passive:!0}),Q.push(()=>q.removeEventListener(`scroll`,Nu)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Io(),Zt(J)});e.observe(J),e.observe(q),Q.push(()=>e.disconnect())}let Pu=()=>{Gt()&&da.isFollowing()&&wo()&&go()},Fu=q.ownerDocument;Fu.addEventListener(`selectionchange`,Pu),Q.push(()=>{Fu.removeEventListener(`selectionchange`,Pu)});let Iu=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Lu=e=>{Iu.has(e.key)&&(Ea(),Jt()&&Gt()&&da.isFollowing()&&go())},Ru=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(Ea(),Jt()&&Gt()&&da.isFollowing()&&go())};q.addEventListener(`keydown`,Lu),q.addEventListener(`focusin`,Ru),Q.push(()=>{q.removeEventListener(`keydown`,Lu),q.removeEventListener(`focusin`,Ru)});let zu=e=>{if(e.deltaY!==0&&Ea(),!Gt())return;let t=jm({following:da.isFollowing(),deltaY:e.deltaY,nearBottom:km(q,24),resumeWhenNearBottom:!0});t===`pause`?go():t===`resume`&&!wo()&&_o()};q.addEventListener(`wheel`,zu,{passive:!0}),q.addEventListener(`touchmove`,Ea,{passive:!0}),q.addEventListener(`pointerdown`,Ea,{passive:!0}),Q.push(()=>{q.removeEventListener(`touchmove`,Ea),q.removeEventListener(`pointerdown`,Ea)}),Q.push(()=>q.removeEventListener(`wheel`,zu)),en.addEventListener(`click`,()=>{jo(),q.scrollTop=q.scrollHeight,fa=q.scrollTop,_o(),vo(!0),ho()}),Q.push(()=>en.remove()),Q.push(()=>{oo(),jo()});let Bu=()=>{xt&&(Bi&&=(xt.removeEventListener(`click`,Bi),null),R()?(xt.style.display=``,Bi=()=>{vs(!1,`user`)},xt.addEventListener(`click`,Bi)):xt.style.display=`none`)};Bu(),(()=>{let{clearChatButton:e}=nt;e&&e.addEventListener(`click`,()=>{let e=jc;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{r.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}$.clearMessages(),r.layout?.topFade&&(q.scrollTop=0),q.removeAttribute(`data-persona-top-fade`),na.clear(),_o(),xr(nt.composerOverlay);try{localStorage.removeItem(Rw),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Rw}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Rw)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),A?.clear&&qa(()=>A.clear(),`[AgentWidget] Failed to clear storage adapter:`),N={},de.syncFromMetadata(),Sn?.clearAttachments(),to(),Un(void 0),zn(void 0),ca(),Me?.clear(),H?.reset(),Fe?.update()})})();let Vu=[[`keydown`,Pl],[`input`,Ml],[`input`,Tn],[`input`,En],[`keyup`,En],[`paste`,Il],[`focus`,dr]],Hu=e=>{if(e)for(let[t,n]of Vu)ir?.addListener(e,t,n)},Uu=e=>{if(e)for(let[t,n]of Vu)ir?.removeListener(e,t,n)},Wu=()=>{ir&&(ir.addListener(ir.form,`submit`,Tl),ir.addListener(ir.footer,`click`,En),Hu(Y),Z&&ir.addListener(Z,`click`,du),bu())};Wu();let Gu=()=>{Cn?.onComposerSwap((e,t)=>{Uu(t),Y=e,ir&&(ir.input=e),Hu(e),or(),ks(),Tn()})};Gu();let Ku=!1;function qu(){if(!Ku){Ku=!0;try{let e=Y?.value??``,t=Ot.ownerDocument??document,n=Y?t.activeElement===Y:!1;tu(),ir?.destroy(),ir=null,Cn?.destroy(),Cn=null;let i=null,a=()=>(i=L()?Mg({config:r}):Ag({config:r}),i.footer),o=nr(a)??a();et.replaceComposer(o),Ot=et.composer.footer;let s=i!==null&&o===i.footer;tr=!s,Ft=s?i.setSendButtonMode:()=>{},er(Ot),sr(Ot),lr(),ur(),fr(),Gu(),gr(),_r(),vr(),Wu();let c=zi.indexOf(Ii);if(Ii.destroy(),Ii=ig(at),c>=0&&(zi[c]=Ii),Y&&(Y.value=e),Tn(),En(),ec(),Qi(),As($.isStreaming()),r.statusIndicator?.mode===`transient`&&!L()){let e=$.getStatus();$e(pt,Qe(e),r.statusIndicator,e)}Fa.active&&Gl(`recording`),Hr(),Ou(),vn(),Cr(),Ds(),n&&Y?.focus()}finally{Ku=!1}}}let Ju=e.ownerDocument??document;Ju.addEventListener(`keydown`,Fl,!0);let Yu=()=>{$a()},Xu=()=>{Ju.visibilityState===`hidden`&&$a()};typeof window<`u`&&(window.addEventListener(`pagehide`,Yu),Ju.addEventListener(`visibilitychange`,Xu),Q.push(()=>{window.removeEventListener(`pagehide`,Yu),Ju.removeEventListener(`visibilitychange`,Xu)}));let Zu=`persona-attachment-drop-active`,Qu=0,$u=()=>{Qu=0,K.classList.remove(Zu)},ed=()=>r.attachments?.enabled===!0&&Sn!==null&&!bs(),td=e=>{Uw(e.dataTransfer)&&ed()&&(Qu++,Qu===1&&K.classList.add(Zu))},nd=e=>{Uw(e.dataTransfer)&&ed()&&(Qu--,Qu<=0&&$u())},rd=e=>{Uw(e.dataTransfer)&&ed()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},id=e=>{if(!Uw(e.dataTransfer)||!ed())return;e.preventDefault(),e.stopPropagation(),$u();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&Sn.handleFiles(t)};K.addEventListener(`dragenter`,td,!0),K.addEventListener(`dragleave`,nd,!0),e.addEventListener(`dragover`,rd,!0),e.addEventListener(`drop`,id,!0);let ad=e.ownerDocument,od=e=>{ed()&&e.preventDefault()},sd=e=>{ed()&&e.preventDefault()};ad.addEventListener(`dragover`,od),ad.addEventListener(`drop`,sd),Q.push(()=>{ir?.destroy(),ir=null,tu(),pr?.destroy(),pr=null,In?.destroy(),In=null,Rn?.destroy(),Rn=null,Hn?.destroy(),Hn=null,Pn=null,Fn=null,$a(),Za.destroy(),ll&&clearTimeout(ll),ca(),sl?.abort(),sl=null,Sn?.destroy(),Sn=null,wn.destroy(),Ju.removeEventListener(`keydown`,Fl,!0),Cn?.destroy()}),Q.push(()=>{K.removeEventListener(`dragenter`,td,!0),K.removeEventListener(`dragleave`,nd,!0),e.removeEventListener(`dragover`,rd,!0),e.removeEventListener(`drop`,id,!0),ad.removeEventListener(`dragover`,od),ad.removeEventListener(`drop`,sd),$u()}),Q.push(()=>{$.cancel()}),Tu?Q.push(()=>{Tu?.destroy()}):Eu&&Q.push(()=>{Eu?.remove()});let cd={update(t){let n=r.future?.v5Defaults===!0,i=r.toolCall,a=r.messageActions,o=r.layout?.messages,s=r.colorScheme,f=r.loadingIndicator,p=r.iterationDisplay,m=r.features?.showReasoning,h=r.features?.showToolCalls,g=r.features?.toolCallDisplay,_=r.features?.reasoningDisplay,v=r.features?.streamAnimation?.type,y=r.features?.history?.enabled===!0,b=r.features?.history?.provider,x=r.getIdentityProof,S=r.clientToken,C=r.contextMentions;r=AS({...r,features:l},t),l=r.features,r=cS(r),c(),Ci(),Qp(e,r),Lx(e,r),Rx(e,r),Ge(),Si(),r.colorScheme!==s&&Mi();let w=ES.getForInstance(r.plugins);d.length=0,d.push(...w),Lc(),I=r.launcher?.enabled??!0,fe=r.launcher?.autoExpand??!1,we=r.features?.showReasoning??!0,Te=r.features?.showToolCalls??!0,De=r.features?.scrollToBottom??{};let T=Wt();Oe=r.features?.scrollBehavior??{},T!==Wt()&&(jo(),_o()),Aa(),xn(),ho();let E=Ee;if(Ee=r.features?.showEventStreamToggle??!1,Ee&&!E){if(Me||(Ve(),$.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Be(e,t)})),!$n&&Tt){let e=r.features?.eventStream?.classNames,t=`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`+(e?.toggleButton?` `+e.toggleButton:``);$n=B(`button`,t),$n.style.width=`28px`,$n.style.height=`28px`,$n.style.color=fg.actionIconColor,$n.type=`button`,$n.setAttribute(`aria-label`,`Event Stream`),$n.title=`Event Stream`;let n=j(u.Activity,`18px`,`currentColor`,1.5);n&&$n.appendChild(n);let i=nt.clearChatButtonWrapper,a=nt.closeButtonWrapper,o=i||a;o&&o.parentNode===Tt?Tt.insertBefore($n,o):Tt.appendChild($n),$n.addEventListener(`click`,()=>{Ie?Qn():Zn()})}}else!Ee&&E&&(Qn(),$n&&=($n.remove(),null),Me?.clear(),je?.destroy(),Me=null,je=null,H?.reset(),H=null,Ne=null);if(r.launcher?.enabled===!1&&Tu&&(Tu.destroy(),Tu=null),r.launcher?.enabled===!1&&Eu&&(Eu.remove(),Eu=null),r.launcher?.enabled!==!1&&!Tu&&!Eu){let{instance:t,element:n}=G_({config:r,plugins:d,onToggle:wu});Tu=t,t||(Eu=n),e.appendChild(n)}Tu&&Tu.update(r),Bc(),wt&&r.launcher?.subtitle!==void 0&&(wt.textContent=r.launcher.subtitle);let D=r.layout?.header;if(D?.layout!==_e&&Tt){let e=D?kg(r,D,{showClose:R(),onClose:()=>vs(!1,`user`)}):hg({config:r,showClose:R(),onClose:()=>vs(!1,`user`)});et.replaceHeader(e),Tt=et.header.element,St=et.header.iconHolder,Ct=et.header.headerTitle,wt=et.header.headerSubtitle,xt=et.header.closeButton,_e=D?.layout,Bc()}else if(D){if(St&&(St.style.display=D.showIcon===!1?`none`:``),Ct&&(Ct.style.display=D.showTitle===!1?`none`:``),wt&&(wt.style.display=D.showSubtitle===!1?`none`:``),xt){let e=R()&&D.showCloseButton!==!1;xt.style.display=e?``:`none`}if(nt.clearChatButtonWrapper){let e=D.showClearChat;if(e!==void 0){nt.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=nt;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let O=r.layout?.showHeader!==!1;Tt&&(Tt.style.display=O?``:`none`);let A=r.layout?.showFooter!==!1;Ot&&(Ot.style.display=A?``:`none`),vn(),ho(),I===ge?fe!==he&&vs(fe,`auto`):I?vs(fe,`auto`):(z=!0,_s()),he=fe,ge=I,Au(),Bu();let ee=JSON.stringify(r.toolCall)!==JSON.stringify(i),M=JSON.stringify(r.messageActions)!==JSON.stringify(a),N=JSON.stringify(r.layout?.messages)!==JSON.stringify(o),P=r.loadingIndicator?.render!==f?.render||r.loadingIndicator?.renderIdle!==f?.renderIdle||r.loadingIndicator?.showBubble!==f?.showBubble,te=r.iterationDisplay!==p,ne=(r.features?.showReasoning??!0)!==(m??!0)||(r.features?.showToolCalls??!0)!==(h??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(g)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(_);(r.future?.v5Defaults===!0!==n||ee||M||N||P||te||ne)&&$&&(la++,Zo(J,$.getMessages(),Ce));let re=r.features?.streamAnimation?.type;if(re!==v&&re&&re!==`none`){let t=Pi(re,r.features?.streamAnimation?.plugins);t&&ah(t,e)}let F=r.launcher??{},ie=F.headerIconHidden??!1,ae=r.layout?.header?.showIcon,oe=ie||ae===!1,le=F.headerIconName,ue=F.headerIconSize??`40px`;if(St){let e=Tt,t=e?.querySelector(`.persona-flex-col`);if(oe)St.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(St.style.display=``,St.style.height=ue,St.style.width=ue,e&&t&&(e.contains(St)?St.nextSibling!==t&&(St.remove(),e.insertBefore(St,t)):e.insertBefore(St,t)),le){let e=parseFloat(ue)||24,t=U(le,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,St.replaceChildren(t)):St.textContent=F.agentIconText??`💬`}else if(F.iconUrl){let e=St.querySelector(`img`);if(e)e.src=F.iconUrl,e.style.height=ue,e.style.width=ue;else{let e=document.createElement(`img`);e.src=F.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=ue,e.style.width=ue,St.replaceChildren(e)}}else{let e=St.querySelector(`svg`),t=St.querySelector(`img`);(e||t)&&St.replaceChildren(),St.textContent=F.agentIconText??`💬`}let n=St.querySelector(`img`);n&&(n.style.height=ue,n.style.width=ue)}}let pe=r.layout?.header?.showTitle,me=r.layout?.header?.showSubtitle;if(Ct&&(Ct.style.display=pe===!1?`none`:``),wt&&(wt.style.display=me===!1?`none`:``),xt){let e=R()&&r.layout?.header?.showCloseButton!==!1;if(xt.style.display=e?``:`none`,!L()){let e=F.closeButtonSize??``;xt.style.height=e,xt.style.width=e,xt.style.minWidth=e,xt.style.minHeight=e}let t=F.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=nt,i=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&i!==a){if(n.remove(),i){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=jc?.railColumn??K;e.style.position=`relative`,e.appendChild(n)}else{let e=F.clearChat?.placement??`inline`;n.className=(F.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,Tt&&Tt.appendChild(n)}}if(xt.style.color=F.closeButtonColor||fg.actionIconColor,F.closeButtonBackgroundColor?(xt.style.backgroundColor=F.closeButtonBackgroundColor,xt.classList.remove(`hover:persona-bg-gray-100`)):(xt.style.backgroundColor=``,xt.classList.add(`hover:persona-bg-gray-100`)),F.closeButtonBorderWidth||F.closeButtonBorderColor){let e=F.closeButtonBorderWidth||`0px`,t=F.closeButtonBorderColor||`transparent`;xt.style.border=`${e} solid ${t}`,xt.classList.remove(`persona-border-none`)}else xt.style.border=``,xt.classList.add(`persona-border-none`);F.closeButtonBorderRadius?(xt.style.borderRadius=F.closeButtonBorderRadius,xt.classList.remove(`persona-rounded-full`)):(xt.style.borderRadius=``,xt.classList.add(`persona-rounded-full`)),F.closeButtonPaddingX?(xt.style.paddingLeft=F.closeButtonPaddingX,xt.style.paddingRight=F.closeButtonPaddingX):(xt.style.paddingLeft=``,xt.style.paddingRight=``),F.closeButtonPaddingY?(xt.style.paddingTop=F.closeButtonPaddingY,xt.style.paddingBottom=F.closeButtonPaddingY):(xt.style.paddingTop=``,xt.style.paddingBottom=``),cg(xt,F.closeButtonIconName??`x`,{iconSize:L()?k_:void 0,iconText:F.closeButtonIconText??`×`});let o=F.closeButtonTooltipText??`Close chat`,s=F.closeButtonShowTooltip??!0;xt.setAttribute(`aria-label`,o),n&&Do({anchor:xt,trigger:n,text:()=>xt?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:ve,clearChatButtonWrapper:ye}=nt;if(ve){let e=F.clearChat??{},t=e.enabled??!0,n=r.layout?.header?.showClearChat,i=n===void 0?t:n,a=e.placement??`inline`;if(ye){ye.style.display=i?``:`none`;let{closeButtonWrapper:e}=nt;!L()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=ye.classList.contains(`persona-absolute`);if(!L()&&t!==n&&i){if(ye.remove(),t){ye.className=`persona-absolute persona-top-4 persona-z-50`,ye.style.right=`48px`;let e=jc?.railColumn??K;e.style.position=`relative`,e.appendChild(ye)}else{ye.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,ye.style.right=``;let e=nt.closeButtonWrapper;Tt&&e&&e.parentElement===Tt?Tt.insertBefore(ye,e):Tt&&Tt.appendChild(ye)}let e=nt.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!L()){let t=e.size??``;ve.style.height=t,ve.style.width=t,ve.style.minWidth=t,ve.style.minHeight=t}let t=e.iconColor??``;if(ve.style.color=t||fg.actionIconColor,cg(ve,e.iconName??`refresh-cw`,{iconSize:L()?A_:void 0}),e.backgroundColor?(ve.style.backgroundColor=e.backgroundColor,ve.classList.remove(`hover:persona-bg-gray-100`)):(ve.style.backgroundColor=``,ve.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;ve.style.border=`${t} solid ${n}`,ve.classList.remove(`persona-border-none`)}else ve.style.border=``,ve.classList.add(`persona-border-none`);e.borderRadius?(ve.style.borderRadius=e.borderRadius,ve.classList.remove(`persona-rounded-full`)):(ve.style.borderRadius=``,ve.classList.add(`persona-rounded-full`)),e.paddingX?(ve.style.paddingLeft=e.paddingX,ve.style.paddingRight=e.paddingX):(ve.style.paddingLeft=``,ve.style.paddingRight=``),e.paddingY?(ve.style.paddingTop=e.paddingY,ve.style.paddingBottom=e.paddingY):(ve.style.paddingTop=``,ve.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;ve.setAttribute(`aria-label`,n),ye&&Do({anchor:ve,trigger:ye,text:()=>ve?.getAttribute(`aria-label`)??n,enabled:r})}}let be=r.actionParsers&&r.actionParsers.length?r.actionParsers:[PS],xe=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[IS.message,IS.messageAndClick];de=RS({parsers:be,handlers:xe,getSessionMetadata:se,updateSessionMetadata:ce,emit:k.emit,documentRef:typeof document<`u`?document:null}),Ce=Jw(r,de,Se),fc(),$.updateConfig(r),tl(),(r.features?.history?.enabled===!0!==y||r.features?.history?.provider!==b||r.getIdentityProof!==x||r.clientToken!==S)&&(jc?.closeHistory({restoreFocus:!1}),jc?.installHistoryProvider()),jc?.syncHistoryChromeImpl(),qc(),Fc()&&!jc&&Gc().catch(()=>{}),Zo(J,$.getMessages(),Ce),Qi(),ec(),$s(),As($.isStreaming()),C!==r.contextMentions&&qu();let ke=r.voiceRecognition?.enabled===!0,Ae=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),V=ht(r.voiceRecognition?.provider);if(ke&&(Ae||V)){if(!Z||!It){let e=cs(r);if(e){Z=e.button,It=e.wrapper;let t=Nt&&Nt.parentElement===Mt?Nt:null;Mt?Mt.insertBefore(It,t):ut?.appendChild(It),ir&&(ir.micButton=Z),ir?.addListener(Z,`click`,du),Z.disabled=bs()||$.isStreaming()&&!xs()}}else{let e=r.voiceRecognition??{},t=r.sendButton??{},n=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;Z.classList.add(ns),Z.classList.toggle(rs,!i),Z.style.width=i??``,Z.style.height=i??``,Z.style.minWidth=i??``,Z.style.minHeight=i??``;let o=e.iconColor??t.textColor;Z.innerHTML=``;let s=U(n,a,o||`currentColor`,1.5);s?Z.appendChild(s):Z.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?Z.style.backgroundColor=c:Z.style.backgroundColor=``,o?Z.style.color=o:Z.style.color=`var(--persona-text, #111827)`,e.borderWidth?(Z.style.borderWidth=e.borderWidth,Z.style.borderStyle=`solid`):(Z.style.borderWidth=``,Z.style.borderStyle=``),e.borderColor?Z.style.borderColor=e.borderColor:Z.style.borderColor=``,e.paddingX?(Z.style.paddingLeft=e.paddingX,Z.style.paddingRight=e.paddingX):(Z.style.paddingLeft=``,Z.style.paddingRight=``),e.paddingY?(Z.style.paddingTop=e.paddingY,Z.style.paddingBottom=e.paddingY):(Z.style.paddingTop=``,Z.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;Z.setAttribute(`aria-label`,l),It&&Do({anchor:Z,trigger:It,text:()=>Z?.getAttribute(`aria-label`)??l,enabled:u}),It.style.display=``,Z.disabled=bs()||$.isStreaming()&&!xs()}}else Z&&It&&(It.style.display=`none`,ht(r.voiceRecognition?.provider)?$.isVoiceActive()&&$.toggleVoice():Rl&&iu());if(bu(),r.attachments?.enabled===!0){if(!Rt||!Lt){let e=r.attachments??{};Bt||(Bt=B(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Bt.style.display=`none`,(Y.parentElement??ut).insertBefore(Bt,Y)),zt||(zt=document.createElement(`input`),zt.type=`file`,zt.accept=(e.allowedTypes??Va).join(`,`),zt.multiple=(e.maxFiles??4)>1,zt.style.display=`none`,zt.setAttribute(`aria-label`,`Attach files`),(Y.parentElement??ut).insertBefore(zt,Y)),Rt=B(`div`,`persona-send-button-wrapper`),Lt=B(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ns} ${rs}`),Lt.type=`button`,Lt.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Lt.style.fontSize=`18px`,Lt.style.lineHeight=`1`;let n=U(t,24,`currentColor`,1.5);n?Lt.appendChild(n):Lt.textContent=`📎`,Lt.addEventListener(`click`,e=>{e.preventDefault(),zt?.click()}),Rt.appendChild(Lt);let i=e.buttonTooltipText??`Attach file`;Do({anchor:Lt,trigger:Rt,text:()=>Lt?.getAttribute(`aria-label`)??i}),jt?jt.append(Rt):ut.appendChild(Rt),ir&&(ir.attachmentButton=Lt,ir.attachmentInput=zt??void 0,ir.attachmentPreviews=Bt??void 0),!Sn&&zt&&Bt&&(Sn=Qd.fromConfig(e,On),Sn.setPreviewsContainer(Bt),ir?.addListener(zt,`change`,async()=>{Sn&&zt?.files&&(await Sn.handleFileSelect(zt.files),zt.value=``)}))}else{Rt.style.display=``;let e=r.attachments??{};zt&&(zt.accept=(e.allowedTypes??Va).join(`,`),zt.multiple=(e.maxFiles??4)>1),Sn&&Sn.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(K.querySelector(`.persona-attachment-drop-overlay`)?.remove(),K.appendChild(Yw(r.attachments?.dropOverlay)),Lt){let e=r.attachments??{},t=e.buttonTooltipText??`Attach file`;Lt.setAttribute(`aria-label`,t),Lt.textContent=``;let n=U(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?Lt.appendChild(n):Lt.textContent=`📎`,Rt&&Do({anchor:Lt,trigger:Rt,text:()=>Lt?.getAttribute(`aria-label`)??t})}}else Rt&&(Rt.style.display=`none`),Sn&&Sn.clearAttachments(),K.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Pe=r.sendButton??{},Fe=Pe.useIcon??!1,Le=Pe.iconText??`↑`,Re=Pe.iconName,ze=Pe.tooltipText??`Send message`,He=Pe.showTooltip??!1,Ue=Pe.size,Ke=parseFloat(Ue??``)||40,qe=Pe.backgroundColor,Je=Pe.textColor;if(Fe){if(X.style.width=Ue??``,X.style.height=Ue??``,X.style.minWidth=Ue??``,X.style.minHeight=Ue??``,X.style.fontSize=`18px`,X.style.lineHeight=`1`,Je?X.style.color=Je:X.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!$.isStreaming()){if(X.innerHTML=``,Re){let e=parseFloat(Pe.iconSize??``)||Math.round(Ke*.5),t=Je?.trim()||`currentColor`,n=Pe.iconStrokeWidth??2,r=U(Re,e,t,n),i=U(Pe.stopIconName??`square`,e,t,n);r&&i?X.appendChild(os(r,i)):r?X.appendChild(r):X.textContent=Le}else X.textContent=Le}X.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ns}`,qe?(X.style.backgroundColor=qe,X.classList.remove(`persona-bg-persona-primary`)):(X.style.backgroundColor=``,X.classList.add(`persona-bg-persona-primary`))}else X.textContent=r.copy?.sendButtonLabel??`Send`,X.style.width=``,X.style.height=``,X.style.minWidth=``,X.style.minHeight=``,X.style.fontSize=``,X.style.lineHeight=``,X.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`,qe?(X.style.backgroundColor=qe,X.classList.remove(`persona-bg-persona-accent`)):X.classList.add(`persona-bg-persona-accent`),Je?X.style.color=Je:X.classList.add(`persona-text-white`);Pe.borderWidth?(X.style.borderWidth=Pe.borderWidth,X.style.borderStyle=`solid`):(X.style.borderWidth=``,X.style.borderStyle=``),Pe.borderColor?X.style.borderColor=Pe.borderColor:X.style.borderColor=``,Pe.paddingX?(X.style.paddingLeft=Pe.paddingX,X.style.paddingRight=Pe.paddingX):(X.style.paddingLeft=``,X.style.paddingRight=``),Pe.paddingY?(X.style.paddingTop=Pe.paddingY,X.style.paddingBottom=Pe.paddingY):(X.style.paddingTop=``,X.style.paddingBottom=``),$.isStreaming()||X.setAttribute(`aria-label`,ze),Ds(),Nt&&Do({anchor:X,trigger:Nt,text:()=>X.getAttribute(`aria-label`)??ze,enabled:He}),wr(),Di();let Ye=Uf(wn.getState().activeModeIds,r.composer?.modes);wn.setActiveModeIds(Ye),An().length>0!=!!In&&_r(),In?.render(Ye,An());for(let e of[...Ln.keys()])Rf(e,r.composer?.modeGroups)||Ln.delete(e);Ln.forEach(e=>e.repaint()),Pn?.repaint(),pr?.resolve();let Xe=em(r,L());if(wi(),Xe){J.style.maxWidth=Xe,J.style.marginLeft=`auto`,J.style.marginRight=`auto`,J.style.width=`100%`,_t.style.maxWidth=Xe,_t.style.marginLeft=`auto`,_t.style.marginRight=`auto`,_t.style.width=`100%`;for(let e of[ut,at,Bt,pt])e&&(e.style.maxWidth=Xe,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{J.style.maxWidth=``,J.style.marginLeft=``,J.style.marginRight=``,J.style.width=``,_t.style.maxWidth=``,_t.style.marginLeft=``,_t.style.marginRight=``,_t.style.width=``;for(let e of[ut,at,Bt,pt])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let Ze=r.statusIndicator??{};if(ft(pt,ut,Ze),dt(pt,Ze,$?.getStatus()??`idle`),$){let e=$.getStatus();$e(pt,(e=>e===`idle`?Ze.idleText??Vr.idle:e===`connecting`?Ze.connectingText??Vr.connecting:e===`connected`?Ze.connectedText??Vr.connected:e===`error`?Ze.errorText??Vr.error:e===`paused`?Ze.pausedText??Vr.paused:e===`resuming`?Ze.resumingText??Vr.resuming:Vr[e])(e),Ze,e)}pt.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let Qe=Ze.align===`left`?`persona-text-left`:Ze.align===`center`?`persona-text-center`:`persona-text-right`;pt.classList.add(Qe),or(),ks(),Cr(),We()},open(){R()&&vs(!0,`api`)},close(){R()&&vs(!1,`api`)},toggle(){R()&&vs(!z,`api`)},reconnect(){$.reconnectNow()},clearChat(){Kr=!1,o.clear(),i.clear(),a.clear(),s.clear(),$.clearMessages(),r.layout?.topFade&&(q.scrollTop=0),q.removeAttribute(`data-persona-top-fade`),na.clear(),_o();try{localStorage.removeItem(Rw),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Rw}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Rw)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),A?.clear&&qa(()=>A.clear(),`[AgentWidget] Failed to clear storage adapter:`),N={},de.syncFromMetadata(),Sn?.clearAttachments(),to(),Un(void 0),zn(void 0),ca(),Me?.clear(),H?.reset(),Fe?.update()},setMessage(e){return!Y||$.isStreaming()||bs()?!1:(!z&&R()&&vs(!0,`system`),Y.value=e,Y.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if($.isStreaming()||ws())return!1;let t=e?.trim()||Y.value.trim();return t?(!z&&R()&&vs(!0,`system`),Y.value=``,Y.style.height=`auto`,Tn(),wl(t,{consumeDraft:!1}),!0):!1},getComposerState(){return wn.getState()},setQuote(e){let t=e?.text?.trim();t&&zn({...e,text:t})},clearQuote(){zn(void 0)},startVoiceRecognition(){return $.isStreaming()?!1:ht(r.voiceRecognition?.provider)?($.isVoiceActive()||$.isBargeInActive()||(!z&&R()&&vs(!0,`system`),Fa.manuallyDeactivated=!1,Ba(),$.toggleVoice().then(()=>{Fa.active=La(),Ba(),za(`user`),Fa.active&&su()})),!0):Rl?!0:nu()?(!z&&R()&&vs(!0,`system`),Fa.manuallyDeactivated=!1,Ba(),ru(`user`),!0):!1},stopVoiceRecognition(){return ht(r.voiceRecognition?.provider)?!$.isVoiceActive()&&!$.isBargeInActive()?!1:(($.isBargeInActive()?$.deactivateBargeIn():$.toggleVoice()).then(()=>{Fa.active=!1,Fa.manuallyDeactivated=!0,Ba(),za(`user`),uu()}),!0):Rl?(Fa.manuallyDeactivated=!0,Ba(),iu(`user`),!0):!1},injectMessage(e){return!z&&R()&&vs(!0,`system`),$.injectMessage(e)},injectAssistantMessage(e){!z&&R()&&vs(!0,`system`);let t=$.injectAssistantMessage(e);return be&&(be=!1,xe&&=(clearTimeout(xe),null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),t},injectUserMessage(e){return!z&&R()&&vs(!0,`system`),$.injectUserMessage(e)},injectSystemMessage(e){return!z&&R()&&vs(!0,`system`),$.injectSystemMessage(e)},injectMessageBatch(e){return!z&&R()&&vs(!0,`system`),$.injectMessageBatch(e)},injectComponentDirective(e){return!z&&R()&&vs(!0,`system`),$.injectComponentDirective(e)},injectTestMessage(e){!z&&R()&&vs(!0,`system`),$.injectTestEvent(e)},async connectStream(e,t){return $.connectStream(e,t)},__pushEventStreamEvent(e){Ee&&(Ve(),Be(e.type,e.payload))},showEventStream(){Ee&&Zn()},hideEventStream(){Ie&&Qn()},isEventStreamVisible(){return Ie},listConversations(e){return $.listConversations(e)},getActiveConversationId(){return $.getActiveConversationId()},openConversation(e,t){return Kc(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Kc(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Jc()},deleteConversation(e){return Kc(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Kc(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Kc(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Kc(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Kc(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=lc;if(!e)return null;let t=await e.get();return e===lc?t:null},getHistoryIdentityStatus(){let e=jc?.historyProvider;return e?e.getIdentityStatus():Fc()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Fc()?Kc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){jc?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return He},showArtifacts(){jx(r)&&(Kr=!1,Yr=!0,Si(),Rr?.setMobileOpen(!0))},hideArtifacts(){jx(r)&&(Kr=!0,Si())},upsertArtifact(e){return jx(r)?(nn(r.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Kr=!1,Yr=!0),$.upsertArtifact(e)):null},selectArtifact(e){jx(r)&&$.selectArtifact(e)},clearArtifacts(){jx(r)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return I&&!z&&!L()||!Y?!1:(Y.focus(),!0)},async resolveApproval(e,t,n){let r=$.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(D(r.approval))$.resolveWebMcpApproval(r.id,t);else return $.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){ea(e)},clearFollowUpSuggestions(){$i()},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...N}},updatePersistentMetadata(e){ce(e)},on(e,t){return k.on(e,t)},off(e,t){k.off(e,t)},isOpen(){return R()&&z},isVoiceActive(){return Fa.active},toggleReadAloud(e){$.toggleReadAloud(e)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(e){return $.getReadAloudState(e)},onReadAloudChange(e){return $.onReadAloudChange(e)},getState(){return{open:R()&&z,launcherEnabled:I,voiceActive:Fa.active,streaming:$.isStreaming()}},showCSATFeedback(e){!z&&R()&&vs(!0,`system`);let t=J.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Iw({onSubmit:async(t,n)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});J.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!z&&R()&&vs(!0,`system`);let t=J.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Lw({onSubmit:async(t,n)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});J.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return $.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return $.submitNPSFeedback(e,t)},destroy(){Dc(),mc!=null&&(clearInterval(mc),mc=null),o.clear(),i.clear(),a.clear(),s.clear(),Q.forEach(e=>e()),W.remove(),tt?.remove(),Tu?.destroy(),Eu?.remove(),Bi&&xt.removeEventListener(`click`,Bi)}};if(((n?.debugTools??!1)||r.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:cd,getMessages:cd.getMessages,getStatus:cd.getStatus,getMetadata:cd.getPersistentMetadata,updateMetadata:cd.updatePersistentMetadata,clearHistory:()=>cd.clearChat(),setVoiceActive:e=>e?cd.startVoiceRecognition():cd.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Q.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let t=e.getAttribute(`data-persona-instance`)||e.id||`persona-`+Math.random().toString(36).slice(2,8),n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Q.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),Ee){let e=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.showEventStream()},n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.hideEventStream()};window.addEventListener(`persona:showEventStream`,e),window.addEventListener(`persona:hideEventStream`,n),Q.push(()=>{window.removeEventListener(`persona:showEventStream`,e),window.removeEventListener(`persona:hideEventStream`,n)})}let r=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.showHistory()},i=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Q.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.showArtifacts()},o=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.hideArtifacts()},s=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||n?.artifact&&cd.upsertArtifact(n.artifact)},c=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||typeof n?.id==`string`&&cd.selectArtifact(n.id)},l=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&cd.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Q.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let ld=Ww(r.persistState);if(ld&&R()){let t=Gw(ld.storage),n=`${ld.keyPrefix}widget-open`,r=`${ld.keyPrefix}widget-voice`,i=`${ld.keyPrefix}widget-voice-mode`;if(t){let a=ld.persist?.openState&&t.getItem(n)===`true`,o=ld.persist?.voiceState&&t.getItem(r)===`true`,s=ld.persist?.voiceState&&t.getItem(i)===`true`;if(a&&(Tu?.setPanelOpen(!0,`auto`),setTimeout(()=>{cd.open(),setTimeout(()=>{if(o||s)cd.startVoiceRecognition();else if(ld.persist?.focusInput){let t=e.querySelector(`textarea`);t&&t.focus()}},100)},0)),ld.persist?.openState&&(k.on(`widget:opened`,()=>{t.setItem(n,`true`)}),k.on(`widget:closed`,()=>{t.setItem(n,`false`)})),ld.persist?.voiceState&&(k.on(`voice:state`,e=>{t.setItem(r,e.active?`true`:`false`)}),k.on(`user:message`,e=>{t.setItem(i,e.viaVoice?`true`:`false`)})),ld.clearOnChatClear){let e=()=>{t.removeItem(n),t.removeItem(r),t.removeItem(i)},a=()=>e();window.addEventListener(`persona:clear-chat`,a),Q.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(ae&&R()&&(Tu?.setPanelOpen(!0,`auto`),setTimeout(()=>{cd.open()},0)),hs(),!ua){let e=Dt(()=>{$&&(la++,na.clear(),Zo(J,$.getMessages(),Ce))});Q.push(e)}b=()=>{$&&(la++,na.clear(),Zo(J,$.getMessages(),Ce))},$.getMessages().length>0&&Yo(),E=()=>{$&&(la++,na.clear(),Zo(J,$.getMessages(),Ce))};let ud=Xe(()=>{$&&(la++,na.clear(),Zo(J,$.getMessages(),Ce))});Q.push(ud);let dd=Ax(()=>{$&&(la++,na.clear(),Zo(J,$.getMessages(),Ce),kx()?.updateInlineArtifactBlocks(J,Gr.artifacts,{suppressTransition:!0}),Si())});return Q.push(dd),cd};Wr();const $w=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},eT=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},tT=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},nT=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&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.")},rT=(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`},iT=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=``},aT=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,iT(e)},oT=e=>{e.style.transition=``},sT=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=``},cT=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},lT=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},uT=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},dT=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},fT=e=>{let t=Xp(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:wp(t,e)??e;return{inset:r(n?.inset,lp),canvasBackground:r(n?.canvasBackground,up)}},pT=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},mT=(e,t,n,r,i,a,o,s)=>{let c=Zh(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;uT(e,t,n,r,l),dT(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`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`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),sT(t),oT(r),aT(r),cT(n),lT(i,r),pT(r,!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`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(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`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),aT(r),eT(r,c.maxHeight),pT(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,sT(t),oT(r),cT(n),lT(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.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`,oT(r),iT(r),lT(i,r);let a=$w(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;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=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,sT(t),iT(r),cT(n),lT(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,tT(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${$w(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},hT=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return rT(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){rT(n,e)},destroy(){n.remove()}}},gT=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?fT(t):null};h();let g=()=>{mT(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=$p(()=>{h(),g()}))},y=()=>{p(),Zh(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,nT(o,Zh(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Zh(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},_T=(e,t)=>Yh(t)?gT(e,t):hT(e,t);Ae();const vT={desktop:{w:1280,h:800},mobile:{w:390,h:844}},yT=`persona-preview-shell-theme`,bT={load:()=>null,save:()=>{},clear:()=>{}},xT=[`How do I get started?`,`Pricing & plans`,`Talk to support`];function ST(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function CT(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 wT(e){let t=CT(e);return`* { box-sizing: border-box; }
|
|
1260
1260
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
1261
1261
|
html { color-scheme: ${e}; }
|
|
1262
1262
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -1280,7 +1280,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1280
1280
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
1281
1281
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
1282
1282
|
.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}; }
|
|
1283
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
1283
|
+
.preview-workspace-card.short { height: 96px; }`}function TT(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let r=n.getElementById(yT);r||(r=n.createElement(`style`),r.id=yT,n.head.appendChild(r)),r.textContent=wT(t)}function ET(e,t,n,r){let i=`
|
|
1284
1284
|
|
|
1285
1285
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
1286
1286
|
<div class="preview-iframe-chrome">
|
|
@@ -1333,16 +1333,16 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
1333
1333
|
<head>
|
|
1334
1334
|
<meta charset="UTF-8">
|
|
1335
1335
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1336
|
-
<link rel="stylesheet" href="${
|
|
1337
|
-
<style id="${
|
|
1336
|
+
<link rel="stylesheet" href="${ST(r)}">
|
|
1337
|
+
<style id="${yT}">${wT(t)}</style>
|
|
1338
1338
|
</head>
|
|
1339
1339
|
<body>
|
|
1340
1340
|
${n?a:i}
|
|
1341
1341
|
</body>
|
|
1342
|
-
</html>`}const
|
|
1343
|
-
${c?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
1342
|
+
</html>`}const DT=()=>[{id:`preview-adv-1`,role:`user`,content:`Can you create the product and gather the docs?`,createdAt:(/* @__PURE__ */ new Date(Date.now()-18e4)).toISOString()},{id:`preview-adv-2`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ 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:(/* @__PURE__ */ 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:(/* @__PURE__ */ 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:(/* @__PURE__ */ new Date(Date.now()-3e4)).toISOString()}],OT=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!==`tool-call`||e?.features?.reasoningDisplay?.activePreview);function kT(e,t,n=[]){if(e===`follow-ups`){let e=Date.now();return[{id:`preview-follow-up-user`,role:`user`,content:`What can Persona help me build?`,createdAt:(/* @__PURE__ */ new Date(e-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:(/* @__PURE__ */ new Date(e-6e4)).toISOString()},{id:`preview-follow-up-suggestions`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date(e-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:(/* @__PURE__ */ new Date()).toISOString()}]:e===`artifact`?[{id:`preview-art-1`,role:`user`,content:`Can you draft a quick overview of the project?`,createdAt:(/* @__PURE__ */ new Date(Date.now()-12e4)).toISOString()},{id:`preview-art-2`,role:`assistant`,content:`Here’s a project overview document for you.`,createdAt:(/* @__PURE__ */ new Date(Date.now()-6e4)).toISOString()}]:e===`conversation`&&OT(t)?[...DT(),...n]:[{id:`preview-conv-1`,role:`assistant`,content:`Hello! How can I help you today?`,createdAt:(/* @__PURE__ */ new Date(Date.now()-18e4)).toISOString()},{id:`preview-conv-2`,role:`user`,content:`I want to customize the theme editor preview.`,createdAt:(/* @__PURE__ */ 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’s possible, then adjust colors and tokens to match your brand.`,createdAt:(/* @__PURE__ */ new Date(Date.now()-6e4)).toISOString()},...n]}function AT(e,t,n=[]){let r={...e.launcher,enabled:!0,autoExpand:t!==`minimized`},i={...e,launcher:r,suggestionChips:t===`home`?e.suggestionChips?.length?e.suggestionChips:xT:e.suggestionChips,initialMessages:kT(t,e,n),storageAdapter:bT};return t===`artifact`&&(i.features={...i.features,artifacts:{...i.features?.artifacts,enabled:!0}}),t===`messages`&&(i.features={...i.features,history:{presentation:`panel`,...i.features?.history,enabled:!0}}),i}function jT(e,t){let n=R(e.config),r=e.config?.future,i=e.theme?kp(e.theme,{validate:!1,future:r}):kp(void 0,{future:r});return{...n,...e.config,theme:i,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??`light`}}function MT(e,t){let n=e.scene??`conversation`;return AT(jT(e,t),n,e.appendedMessages??[])}function NT(e){let t=e.compareMode??`off`,n=e.shellMode??`light`;return t===`themes`?[{mountId:`preview-light`,label:`Light`,config:MT(e,`light`),shellMode:`light`},{mountId:`preview-dark`,label:`Dark`,config:MT(e,`dark`),shellMode:`dark`}]:t===`baseline`&&(e.baselineConfig||e.baselineTheme)?[{mountId:`preview-baseline`,label:`Baseline`,config:MT({...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme},n),shellMode:n},{mountId:`preview-current`,label:`Current`,config:MT(e,n),shellMode:n}]:[{mountId:`preview-current`,label:`Current`,config:MT(e,n),shellMode:n}]}function PT(e,t){let n={...t},r=[],i=[],a=null,o=!1,s=1,c=1,l=0;function u(){return n.device??`desktop`}function d(){return n.zoom??s}function f(){let t=getComputedStyle(e),r=parseFloat(t.paddingLeft)+parseFloat(t.paddingRight),i=parseFloat(t.paddingTop)+parseFloat(t.paddingBottom),a=(n.compareMode??`off`)!==`off`,o=(e.clientWidth-r-40)/(a?2:1),s=e.clientHeight-i-40;if(o<=0||s<=0)return 1;let c=vT[u()]??vT.desktop;return Math.min(o/c.w,s/c.h,1)}function p(){s=f();let t=Math.max(.15,Math.min(1.5,d()));c=t;let r=Array.from(e.querySelectorAll(`.preview-iframe-wrapper`));for(let e of r){let n=e.dataset.device??`desktop`,r=vT[n]??vT.desktop;e.style.width=`${r.w*t}px`,e.style.height=`${r.h*t}px`,n===`mobile`&&(e.style.borderRadius=`${32*t}px`);let i=e.querySelector(`iframe`);i&&(i.style.width=`${r.w}px`,i.style.height=`${r.h}px`,i.style.transformOrigin=`top left`,i.style.transition=`none`,i.style.transform=`scale(${t})`)}n.onScaleChange?.(t)}function m(){n.onBeforeDestroy?.();for(let e of r)e.destroy();for(let e of i)e();r=[],i=[]}function h(){return Array.from(e.querySelectorAll(`iframe[data-mount-id]`))}function g(){if(o)return;m();let t=++l,a=NT(n),s=u(),c=(n.compareMode??`off`)!==`off`,d=(n.scene??`conversation`)===`minimized`,f=n.widgetCssPath??`/widget-dist/widget.css`,g=n.buildSrcdoc??ET,_=s===`mobile`?`preview-iframe-wrapper preview-iframe-wrapper-mobile`:`preview-iframe-wrapper`,v=e=>`<div class="${_}" data-mount-id="${e.mountId}" data-device="${s}" data-shell-mode="${e.shellMode}">
|
|
1343
|
+
${c?`<div class="preview-frame-meta"><span class="preview-frame-label">${ST(e.label)}</span></div>`:``}
|
|
1344
1344
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${e.mountId}"></iframe>
|
|
1345
|
-
</div>`,y=c?`<div class="preview-compare-grid">${a.map(e=>`<div class="preview-compare-cell">${v(e)}</div>`).join(``)}</div>`:`<div class="preview-single">${v(a[0])}</div>`;n.morphContainer?n.morphContainer(e,y):e.innerHTML=y,p();let b=h(),x=0,S=b.length,C=()=>{if(o||t!==l)return;for(let e of b){let t=e.dataset.mountId;if(!t||!e.contentDocument)continue;let n=a.find(e=>e.mountId===t);if(!n)continue;let o=()=>{},s=
|
|
1345
|
+
</div>`,y=c?`<div class="preview-compare-grid">${a.map(e=>`<div class="preview-compare-cell">${v(e)}</div>`).join(``)}</div>`:`<div class="preview-single">${v(a[0])}</div>`;n.morphContainer?n.morphContainer(e,y):e.innerHTML=y,p();let b=h(),x=0,S=b.length,C=()=>{if(o||t!==l)return;for(let e of b){let t=e.dataset.mountId;if(!t||!e.contentDocument)continue;let n=a.find(e=>e.mountId===t);if(!n)continue;let o=()=>{},s=Yh(n.config),c=s?(()=>{let r=e.contentDocument?.getElementById(`preview-content-${t}`);if(!r)return null;let i=_T(r,n.config),a=e.contentDocument.createElement(`div`);a.id=t,a.style.height=`100%`,a.style.display=`flex`,a.style.flexDirection=`column`,a.style.flex=`1`,a.style.minHeight=`0`,i.host.appendChild(a);let s=()=>i.syncWidgetState(l.getState()),c=o;return o=()=>{i.destroy(),c()},a.__syncDock=s,a.__hostLayout=i,a})():e.contentDocument.getElementById(t);if(!c)continue;let l=Qw(c,n.config);if(r.push(l),s&&c.__syncDock){let e=c.__syncDock,t=l.on(`widget:opened`,e),n=l.on(`widget:closed`,e),r=o;o=()=>{t(),n(),r()},e()}i.push(o),d&&l.close()}let e=n.scene??`conversation`;if(e===`messages`)for(let e of r)e.showHistory({focus:!1});if(e===`artifact`||n.config?.features?.artifacts?.enabled)for(let e of r)e.upsertArtifact({id:`preview-sample`,artifactType:`markdown`,title:`Sample Document`,content:`# Sample Artifact
|
|
1346
1346
|
|
|
1347
1347
|
This is a preview of the artifact sidebar.
|
|
1348
1348
|
|
|
@@ -1350,4 +1350,4 @@ This is a preview of the artifact sidebar.
|
|
|
1350
1350
|
|
|
1351
1351
|
- Markdown rendering
|
|
1352
1352
|
- Document toolbar
|
|
1353
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:b,controllers:[...r]})};for(let e of b){let t=e.dataset.mountId;if(!t)continue;let n=a.find(e=>e.mountId===t);n&&(e.addEventListener(`load`,()=>{x++,x>=S&&C()},{once:!0}),e.srcdoc=g(t,n.shellMode,
|
|
1353
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:b,controllers:[...r]})};for(let e of b){let t=e.dataset.mountId;if(!t)continue;let n=a.find(e=>e.mountId===t);n&&(e.addEventListener(`load`,()=>{x++,x>=S&&C()},{once:!0}),e.srcdoc=g(t,n.shellMode,Yh(n.config),f))}S===0&&C()}function _(){if(o)return;let t=NT(n);if(r.length!==t.length)g();else if(t.some(t=>{let n=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${t.mountId}"]`);return!n||n.dataset.shellMode!==t.shellMode}))g();else{r.forEach((e,r)=>{e.update(t[r].config),(n.scene??`conversation`)===`minimized`&&e.close()});for(let n of t){let t=e.querySelector(`iframe[data-mount-id="${n.mountId}"]`);t&&TT(t,n.shellMode)}n.onAfterUpdate?.({iframes:h(),controllers:[...r]})}}return typeof ResizeObserver<`u`&&(a=new ResizeObserver(()=>{o||p()}),a.observe(e)),g(),{update(e){if(o)return;let t=e.device!==void 0&&e.device!==n.device||e.scene!==void 0&&e.scene!==n.scene||e.compareMode!==void 0&&e.compareMode!==n.compareMode||e.widgetCssPath!==void 0&&e.widgetCssPath!==n.widgetCssPath;n={...n,...e},t?g():_()},destroy(){o||(o=!0,m(),a?.disconnect(),e.innerHTML=``)},getControllers(){return[...r]},fitToContainer(){o||(n={...n,zoom:void 0},p())},getIframes(){return h()},getScale(){return c},setZoom(e){o||(n={...n,zoom:e},p())}}}exports.createThemePreview=PT;
|