@nextclaw/ui 0.8.0 → 0.9.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/CHANGELOG.md +24 -0
- package/dist/assets/ChannelsList-DhvjpZcs.js +1 -0
- package/dist/assets/ChatPage-B8VBaMQm.js +38 -0
- package/dist/assets/{DocBrowser-DDX2HMXW.js → DocBrowser-LpzGe8An.js} +1 -1
- package/dist/assets/{LogoBadge-J53F_3JA.js → LogoBadge-Be4lktJN.js} +1 -1
- package/dist/assets/{MarketplacePage-0BZ4bza0.js → MarketplacePage-Cx9AI3_h.js} +3 -3
- package/dist/assets/{ModelConfig-Wzq9wGHV.js → ModelConfig-DuImUHIX.js} +1 -1
- package/dist/assets/ProvidersList-Ccleg25k.js +1 -0
- package/dist/assets/{RuntimeConfig-N771_AM6.js → RuntimeConfig-C6iqpJR_.js} +1 -1
- package/dist/assets/{SearchConfig-DVt5QVa_.js → SearchConfig-Dvp1TAXu.js} +1 -1
- package/dist/assets/{SecretsConfig-CkwauPa8.js → SecretsConfig-D5Ymlvt9.js} +1 -1
- package/dist/assets/{SessionsConfig-C3mnHzkZ.js → SessionsConfig-CIA_jA1P.js} +2 -2
- package/dist/assets/{chat-message-pxr79GDs.js → chat-message-B60Fh9kI.js} +1 -1
- package/dist/assets/index-BiPDnzv0.js +8 -0
- package/dist/assets/index-C8GsgIUn.css +1 -0
- package/dist/assets/{index-GdpEEKnz.js → index-CPDASUXh.js} +1 -1
- package/dist/assets/{label-CmksBHgc.js → label-D4fGx6Wb.js} +1 -1
- package/dist/assets/{page-layout-Db0GbnhS.js → page-layout-twy8gmBE.js} +1 -1
- package/dist/assets/popover-DYbYpt1j.js +1 -0
- package/dist/assets/{security-config-CjLFME5Q.js → security-config-BcIZ4rpb.js} +1 -1
- package/dist/assets/skeleton-DypBy7jp.js +1 -0
- package/dist/assets/{switch-C24d-UJU.js → switch-DqA6r5XR.js} +1 -1
- package/dist/assets/tabs-custom-C6enKKs1.js +1 -0
- package/dist/assets/{useConfirmDialog-BeP35LcG.js → useConfirmDialog-CHBf5Of7.js} +1 -1
- package/dist/assets/{vendor-psXJBy9u.js → vendor-DKBNiC31.js} +1 -1
- package/dist/index.html +3 -3
- package/package.json +6 -6
- package/src/api/config.ts +9 -38
- package/src/api/ncp-session.ts +50 -0
- package/src/api/types.ts +1 -0
- package/src/components/chat/ChatConversationPanel.test.tsx +65 -0
- package/src/components/chat/ChatConversationPanel.tsx +21 -12
- package/src/components/chat/ChatSidebar.test.tsx +203 -0
- package/src/components/chat/ChatSidebar.tsx +97 -7
- package/src/components/chat/adapters/chat-message.adapter.test.ts +132 -82
- package/src/components/chat/adapters/chat-message.adapter.ts +27 -9
- package/src/components/chat/chat-composer-state.ts +53 -0
- package/src/components/chat/chat-page-data.ts +30 -1
- package/src/components/chat/chat-page-runtime.test.ts +181 -0
- package/src/components/chat/chat-page-runtime.ts +101 -15
- package/src/components/chat/chat-session-preference-sync.test.ts +62 -0
- package/src/components/chat/chat-session-preference-sync.ts +75 -0
- package/src/components/chat/chat-stream/types.ts +3 -0
- package/src/components/chat/containers/chat-input-bar.container.tsx +12 -63
- package/src/components/chat/containers/chat-message-list.container.tsx +31 -27
- package/src/components/chat/legacy/LegacyChatPage.tsx +25 -0
- package/src/components/chat/managers/chat-input.manager.ts +48 -13
- package/src/components/chat/managers/chat-session-list.manager.test.ts +39 -0
- package/src/components/chat/managers/chat-session-list.manager.ts +9 -3
- package/src/components/chat/ncp/NcpChatPage.tsx +53 -13
- package/src/components/chat/ncp/ncp-chat-input.manager.ts +48 -12
- package/src/components/chat/ncp/ncp-chat-page-data.ts +34 -2
- package/src/components/chat/ncp/ncp-chat-thread.manager.ts +1 -1
- package/src/components/chat/ncp/ncp-session-adapter.test.ts +27 -1
- package/src/components/chat/ncp/ncp-session-adapter.ts +20 -0
- package/src/components/chat/presenter/chat-presenter-context.tsx +2 -0
- package/src/components/chat/stores/chat-input.store.ts +4 -0
- package/src/components/chat/stores/chat-thread.store.ts +2 -0
- package/src/components/chat/useChatSessionTypeState.test.tsx +58 -0
- package/src/components/chat/useChatSessionTypeState.ts +25 -8
- package/src/hooks/use-ncp-chat-session-types.ts +11 -0
- package/src/hooks/useConfig.ts +2 -4
- package/src/hooks/useMarketplace.ts +7 -4
- package/src/hooks/useWebSocket.ts +23 -2
- package/dist/assets/ChannelsList-DBcoVJRW.js +0 -1
- package/dist/assets/ChatPage-CD3cxyyM.js +0 -37
- package/dist/assets/ProvidersList-kwzRS8_M.js +0 -1
- package/dist/assets/index-BIvFMkN4.js +0 -1
- package/dist/assets/index-CzkY1reu.js +0 -8
- package/dist/assets/index-RZ0kHHRI.css +0 -1
- package/dist/assets/skeleton-CkpQeVWN.js +0 -1
- package/dist/assets/tabs-custom-D89bh-fc.js +0 -1
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
var ro=Object.defineProperty;var so=(e,t,n)=>t in e?ro(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var j=(e,t,n)=>so(e,typeof t!="symbol"?t+"":t,n);import{r as v,j as h,a2 as io,O as Ht,a3 as ao,s as Wn,A as Gn,B as Qn,N as vr,a4 as oo,z as lo,F as uo,D as co,E as ho,a5 as fo,t as po,c as go,R as mo,o as yo,T as qs,I as xo,C as Ws,P as bo,h as Gs,V as So,i as Qs,k as ko,l as Xn,m as wo,S as Xs,f as vo,g as Ys,a as Co,a6 as Io,a7 as To,a8 as Ro,a9 as Mo,q as Ao,aa as Eo,ab as Lo,ac as Js,ad as Zs,ae as ei,af as No,ag as Po,ah as jo,ai as Do,aj as _o,ak as Oo,al as vn,am as Cn,an as In,ao as kt,M as zo,ap as ti,aq as Fo,ar as Bo,as as $o,J as Yn,at as ni,au as ri}from"./vendor-psXJBy9u.js";import{u as Jn}from"./useConfirmDialog-BeP35LcG.js";import{i as Uo,t as R,u as si,a as ii,j as Ho,k as Ko,l as Vo,m as qo,c as Le,n as Wo,o as Go,p as Zn,q as Qo,T as Cr,L as Ir,r as Xo,B as st,I as ai,s as Kt,S as Tn,e as Rn,g as Mn,h as gt,v as Yo,w as Jo,x as Zo,y as el,f as tl,C as nl,z as rl,A as sl,E as il,F as al,G as ol,H as ll,J as ul,K as cl,M as dl,N as hl,O as fl}from"./index-CzkY1reu.js";import{b as pl,a as gl,S as ml,s as yl,c as Tr,e as Rr}from"./chat-message-pxr79GDs.js";import{u as oi,T as xl,a as bl,b as Sl,c as kl,P as wl,R as vl,d as Cl,e as Il,C as li,M as Tl}from"./MarketplacePage-0BZ4bza0.js";import{b as ui,c as ci,r as di}from"./provider-models-D3B_xWXx.js";import{R as Rl,A as Ml,P as Al,C as hi,T as El}from"./index-BIvFMkN4.js";import{P as Ll,a as Nl}from"./page-layout-Db0GbnhS.js";import"./index-GdpEEKnz.js";import"./skeleton-CkpQeVWN.js";import"./tabs-custom-D89bh-fc.js";const Pl="ncp";function Mr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="legacy"||t==="ncp"?t:null}function jl(e){const t=Mr(new URLSearchParams(e).get("chatChain"));return t||(Mr(void 0)??Pl)}function fi(e){const{modelOptions:t,selectedSessionPreferredModel:n,defaultModel:r,setSelectedModel:s}=e;v.useEffect(()=>{if(t.length===0){s("");return}s(i=>{var u;if(t.some(l=>l.value===i))return i;const a=n==null?void 0:n.trim();if(a&&t.some(l=>l.value===a))return a;const o=r==null?void 0:r.trim();return o&&t.some(l=>l.value===o)?o:((u=t[0])==null?void 0:u.value)??""})},[r,t,n,s])}function Dl(e){var k;const{view:t,selectedSessionKey:n,activeBackendRunId:r,isLocallyRunning:s,resumeRun:i}=e,[a,o]=v.useState(null),u=v.useRef(!1),l=v.useRef(new Map),c=v.useRef(new Map),d=v.useRef(new Map),p=v.useRef(r),f=v.useRef(new Set);v.useEffect(()=>{n&&f.current.add(n)},[n]),v.useEffect(()=>{n&&s&&f.current.delete(n)},[s,n]);const y=Uo(t==="chat"?{states:["queued","running"],limit:200,syncActiveStates:!0,isLocallyRunning:s}:void 0),m=v.useMemo(()=>{var w;return pl(((w=y.data)==null?void 0:w.runs)??[])},[(k=y.data)==null?void 0:k.runs]),S=v.useMemo(()=>{const w=gl(m);if(a){const E=m.get(a.sessionKey)??null;E&&(!a.runId||E.runId===a.runId)&&w.delete(a.sessionKey)}return w},[m,a]),g=v.useMemo(()=>{if(!n)return null;const w=m.get(n)??null;return(!w||!a||a.sessionKey!==n?!1:!a.runId||w.runId===a.runId)?null:w},[m,n,a]);return v.useEffect(()=>{r&&(p.current=r)},[r]),v.useEffect(()=>{if(t!=="chat"||!n||!g||!f.current.has(n)||s||r===g.runId||l.current.get(n)===g.runId)return;const E=c.current.get(n);if(E&&E===g.runId)return;const M=d.current.get(n);if(typeof M=="number"){const I=Date.parse(g.requestedAt??"");if(Number.isFinite(I)){if(I<=M+2e3)return}else if(Date.now()-M<=8e3)return}l.current.set(n,g.runId),f.current.delete(n),i(g)},[r,g,s,i,n,t]),v.useEffect(()=>{if(!n){l.current.clear(),c.current.clear(),d.current.clear(),f.current.clear();return}m.has(n)||(l.current.delete(n),c.current.delete(n),d.current.delete(n))},[m,n]),v.useEffect(()=>{var E,M,I;const w=u.current;if(u.current=s,!s&&w&&n){const P=((E=p.current)==null?void 0:E.trim())||((I=(M=m.get(n))==null?void 0:M.runId)==null?void 0:I.trim());P&&c.current.set(n,P),d.current.set(n,Date.now()),o({sessionKey:n,...P?{runId:P}:{}}),y.refetch()}},[m,s,n,y]),v.useEffect(()=>{if(!a)return;const w=m.get(a.sessionKey)??null;if(!w){o(null);return}a.runId&&w.runId!==a.runId&&o(null)},[m,a]),v.useEffect(()=>{s&&(a==null?void 0:a.sessionKey)===n&&o(null)},[s,n,a]),{sessionRunStatusByKey:S}}const Ee="native";function qe(e){return typeof e!="string"?Ee:e.trim().toLowerCase()||Ee}function Ot(e,t){return e==="native"?R("chatSessionTypeNative"):e==="codex-sdk"?R("chatSessionTypeCodex"):e==="claude-agent-sdk"?R("chatSessionTypeClaude"):(t==null?void 0:t.trim())||e}function _l(e){var n;const t=new Map;for(const r of e){const s=qe(r.value);t.set(s,{value:s,label:((n=r.label)==null?void 0:n.trim())||Ot(s)})}return t.has(Ee)||t.set(Ee,{value:Ee,label:Ot(Ee)}),Array.from(t.values()).sort((r,s)=>r.value===Ee?-1:s.value===Ee?1:r.value.localeCompare(s.value))}function pi(e){const{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:s,sessionTypesData:i}=e,a=v.useMemo(()=>_l((i==null?void 0:i.options)??[]),[i==null?void 0:i.options]),o=v.useMemo(()=>{const y=[...a],m=qe(t==null?void 0:t.sessionType);return y.some(S=>S.value===m)||y.push({value:m,label:Ot(m)}),y.sort((S,g)=>S.value===Ee?-1:g.value===Ee?1:S.value.localeCompare(g.value))},[a,t==null?void 0:t.sessionType]),u=v.useMemo(()=>qe((i==null?void 0:i.defaultType)??Ee),[i==null?void 0:i.defaultType]),l=v.useMemo(()=>qe((t==null?void 0:t.sessionType)??r??u),[u,r,t==null?void 0:t.sessionType]);v.useEffect(()=>{n||s(u)},[u,n,s]);const c=!n||!!(t!=null&&t.sessionTypeMutable),d=v.useMemo(()=>new Set(a.map(y=>y.value)),[a]),p=!!(t&&!d.has(qe(t.sessionType))),f=p?`${Ot(l)} ${R("chatSessionTypeUnavailableSuffix")}`:null;return{sessionTypeOptions:o,defaultSessionType:u,selectedSessionType:l,canEditSessionType:c,sessionTypeUnavailable:p,sessionTypeUnavailableMessage:f}}const Ol=new Set(["off","minimal","low","medium","high","adaptive","xhigh"]);function zl(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t&&Ol.has(t)?t:null}function Fl(e){var S,g,k,w,E;const t=si(),n=ii(),r=Ho({q:e.query.trim()||void 0,limit:120,activeMinutes:0}),s=oi("skill"),i=Ko({sessionKey:e.selectedSessionKey,agentId:e.selectedAgentId}),a=Vo(e.selectedSessionKey,300),o=qo(),u=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),l=v.useMemo(()=>{const M=ui({meta:n.data,config:t.data,onlyConfigured:!0}),I=new Set,P=[];for(const D of M)for(const F of D.models){const C=ci(D.prefix,F);!C||I.has(C)||(I.add(C),P.push({value:C,modelLabel:F,providerLabel:D.displayName,thinkingCapability:di(D.modelThinking,F,D.aliases)}))}return P.sort((D,F)=>{const C=D.providerLabel.localeCompare(F.providerLabel);return C!==0?C:D.modelLabel.localeCompare(F.modelLabel)})},[n.data,t.data]),c=v.useMemo(()=>{var M;return((M=r.data)==null?void 0:M.sessions)??[]},[(S=r.data)==null?void 0:S.sessions]),d=v.useMemo(()=>{var M;return((M=s.data)==null?void 0:M.records)??[]},[(g=s.data)==null?void 0:g.records]),p=v.useMemo(()=>c.find(M=>M.key===e.selectedSessionKey)??null,[e.selectedSessionKey,c]),f=pi({selectedSession:p,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:o.data});fi({modelOptions:l,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,defaultModel:(k=t.data)==null?void 0:k.agents.defaults.model,setSelectedModel:e.setSelectedModel});const y=v.useMemo(()=>{var M;return((M=a.data)==null?void 0:M.messages)??[]},[(w=a.data)==null?void 0:w.messages]),m=v.useMemo(()=>{var P;if(!e.selectedSessionKey)return null;const M=(P=a.data)==null?void 0:P.metadata;if(!M||typeof M!="object")return null;const I=[M.preferred_thinking,M.thinking,M.thinking_level,M.thinkingLevel];for(const D of I){const F=zl(D);if(F)return F}return null},[(E=a.data)==null?void 0:E.metadata,e.selectedSessionKey]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,chatCapabilitiesQuery:i,historyQuery:a,sessionTypesQuery:o,isProviderStateResolved:u,modelOptions:l,sessions:c,skillRecords:d,selectedSession:p,historyMessages:y,selectedSessionThinkingLevel:m,...f}}function gi(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const Bl={connected:{dotClass:"bg-emerald-500"},disconnected:{dotClass:"h-2.5 w-2.5 rounded-full border border-gray-400 bg-transparent"},connecting:{dotClass:"text-amber-600"}};function $l({status:e,className:t}){const n=Bl[e],r=e==="connected"?R("connected"):e==="disconnected"?R("disconnected"):R("connecting");return h.jsx(xl,{delayDuration:250,children:h.jsxs(bl,{children:[h.jsx(Sl,{asChild:!0,children:h.jsx("span",{role:"status","aria-label":r,className:Le("inline-flex h-5 w-5 items-center justify-center",t),children:e==="connecting"?h.jsx(io,{className:Le("h-3 w-3 animate-spin",n.dotClass)}):h.jsx("span",{className:Le(e==="connected"?"h-2 w-2 rounded-full":"",n.dotClass)})})}),h.jsx(kl,{side:"bottom",className:"text-xs",children:r})]})})}const mi=v.createContext(null);function yi({presenter:e,children:t}){return h.jsx(mi.Provider,{value:e,children:t})}function er(){const e=v.useContext(mi);if(!e)throw new Error("usePresenter must be used inside ChatPresenterProvider");return e}const Ul={sessionRunStatusByKey:new Map,isLocallyRunning:!1,activeBackendRunId:null},An=Ht(e=>({snapshot:Ul,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),Hl={sessions:[],selectedSessionKey:null,selectedAgentId:"main",query:"",isLoading:!1},re=Ht(e=>({snapshot:Hl,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function Kl(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),r=n-864e5,s=n-7*864e5,i=[],a=[],o=[],u=[];for(const c of e){const d=new Date(c.updatedAt).getTime();d>=n?i.push(c):d>=r?a.push(c):d>=s?o.push(c):u.push(c)}const l=[];return i.length>0&&l.push({label:R("chatSidebarToday"),sessions:i}),a.length>0&&l.push({label:R("chatSidebarYesterday"),sessions:a}),o.length>0&&l.push({label:R("chatSidebarPrevious7Days"),sessions:o}),u.length>0&&l.push({label:R("chatSidebarOlder"),sessions:u}),l}function Vl(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const ql=[{target:"/cron",label:()=>R("chatSidebarScheduledTasks"),icon:Gn},{target:"/skills",label:()=>R("chatSidebarSkills"),icon:Qn}];function Wl(){var f,y;const e=er(),t=Wo(),n=re(m=>m.snapshot),r=An(m=>m.snapshot),s=Go(m=>m.connectionStatus),{language:i,setLanguage:a}=Zn(),{theme:o,setTheme:u}=Qo(),l=R(((f=Cr.find(m=>m.value===o))==null?void 0:f.labelKey)??"themeWarm"),c=((y=Ir.find(m=>m.value===i))==null?void 0:y.label)??i,d=v.useMemo(()=>Kl(n.sessions),[n.sessions]),p=m=>{i!==m&&(a(m),window.location.reload())};return h.jsxs("aside",{className:"w-[280px] shrink-0 flex flex-col h-full bg-secondary border-r border-gray-200/60",children:[h.jsx("div",{className:"px-5 pt-5 pb-3",children:h.jsx(Xo,{className:"flex items-center gap-2.5 min-w-0",suffix:h.jsx($l,{status:s})})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs(st,{variant:"primary",className:"w-full rounded-xl",onClick:e.chatSessionListManager.createSession,children:[h.jsx(ao,{className:"h-4 w-4 mr-2"}),R("chatSidebarNewTask")]})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"relative",children:[h.jsx(Wn,{className:"h-3.5 w-3.5 absolute left-3 top-2.5 text-gray-400"}),h.jsx(ai,{value:n.query,onChange:m=>e.chatSessionListManager.setQuery(m.target.value),placeholder:R("chatSidebarSearchPlaceholder"),className:"pl-8 h-9 rounded-lg text-xs"})]})}),h.jsx("div",{className:"px-3 pb-2",children:h.jsx("ul",{className:"space-y-0.5",children:ql.map(m=>{const S=m.icon;return h.jsx("li",{children:h.jsx(vr,{to:m.target,className:({isActive:g})=>Le("group w-full flex items-center gap-3 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150",g?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-600 hover:bg-gray-200/60 hover:text-gray-900"),children:({isActive:g})=>h.jsxs(h.Fragment,{children:[h.jsx(S,{className:Le("h-4 w-4 transition-colors",g?"text-gray-900":"text-gray-500 group-hover:text-gray-800")}),h.jsx("span",{children:m.label()})]})})},m.target)})})}),h.jsx("div",{className:"mx-4 border-t border-gray-200/60"}),h.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar px-3 py-2",children:n.isLoading?h.jsx("div",{className:"text-xs text-gray-500 p-3",children:R("sessionsLoading")}):d.length===0?h.jsxs("div",{className:"p-4 text-center",children:[h.jsx(oo,{className:"h-6 w-6 mx-auto mb-2 text-gray-300"}),h.jsx("div",{className:"text-xs text-gray-500",children:R("sessionsEmpty")})]}):h.jsx("div",{className:"space-y-3",children:d.map(m=>h.jsxs("div",{children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider",children:m.label}),h.jsx("div",{className:"space-y-0.5",children:m.sessions.map(S=>{const g=n.selectedSessionKey===S.key,k=r.sessionRunStatusByKey.get(S.key);return h.jsxs("button",{onClick:()=>e.chatSessionListManager.selectSession(S.key),className:Le("w-full rounded-xl px-3 py-2 text-left transition-all text-[13px]",g?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-700 hover:bg-gray-200/60 hover:text-gray-900"),children:[h.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5",children:[h.jsx("span",{className:"truncate font-medium",children:Vl(S)}),h.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:k?h.jsx(ml,{status:k}):null})]}),h.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:[S.messageCount," · ",Kt(S.updatedAt)]})]},S.key)})})]},m.label))})}),h.jsxs("div",{className:"px-3 py-3 border-t border-gray-200/60 space-y-0.5",children:[h.jsx(vr,{to:"/settings",className:({isActive:m})=>Le("group w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150",m?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-600 hover:bg-gray-200/60 hover:text-gray-900"),children:({isActive:m})=>h.jsxs(h.Fragment,{children:[h.jsx(lo,{className:Le("h-4 w-4 transition-colors",m?"text-gray-900":"text-gray-500 group-hover:text-gray-800")}),h.jsx("span",{children:R("settings")})]})}),h.jsxs("button",{onClick:()=>t.open(void 0,{kind:"docs",newTab:!0,title:"Docs"}),className:"w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150 text-gray-600 hover:bg-gray-200/60 hover:text-gray-800",children:[h.jsx(uo,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:R("docBrowserHelp")})]}),h.jsxs(Tn,{value:o,onValueChange:m=>u(m),children:[h.jsxs(Rn,{className:"w-full h-auto rounded-xl border-0 bg-transparent shadow-none px-3 py-2 text-[13px] font-medium text-gray-600 hover:bg-gray-200/60 focus:ring-0",children:[h.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[h.jsx(co,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:R("theme")})]}),h.jsx("span",{className:"ml-auto text-[11px] text-gray-500",children:l})]}),h.jsx(Mn,{children:Cr.map(m=>h.jsx(gt,{value:m.value,className:"text-xs",children:R(m.labelKey)},m.value))})]}),h.jsxs(Tn,{value:i,onValueChange:m=>p(m),children:[h.jsxs(Rn,{className:"w-full h-auto rounded-xl border-0 bg-transparent shadow-none px-3 py-2 text-[13px] font-medium text-gray-600 hover:bg-gray-200/60 focus:ring-0",children:[h.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[h.jsx(ho,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:R("language")})]}),h.jsx("span",{className:"ml-auto text-[11px] text-gray-500",children:c})]}),h.jsx(Mn,{children:Ir.map(m=>h.jsx(gt,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]})]})}function Gl(e){return h.jsx("textarea",{value:e.value,onChange:t=>e.onValueChange(t.target.value),disabled:e.disabled,onKeyDown:e.onKeyDown,placeholder:e.placeholder,className:"w-full min-h-[68px] max-h-[220px] resize-y bg-transparent px-4 py-3 text-sm text-gray-800 outline-none placeholder:text-gray-400"})}function Ql(e){return e.items.length===0?null:h.jsx("div",{className:"px-4 pb-2",children:h.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.items.map(t=>h.jsxs("button",{type:"button",onClick:()=>e.onRemove(t.key),className:"inline-flex max-w-[200px] items-center gap-1.5 rounded-full bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary",children:[h.jsx("span",{className:"truncate",children:t.label}),h.jsx(fo,{className:"h-3 w-3 shrink-0"})]},t.key))})})}const Xl=e=>`[data-item-index="${e}"]`;function xi(e){const t=e.getItemSelector??Xl;v.useEffect(()=>{if(!e.isEnabled||e.itemCount===0)return;const n=e.containerRef.current;if(!n)return;const r=n.querySelector(t(e.activeIndex));r==null||r.scrollIntoView({block:"nearest",inline:"nearest"})},[t,e.activeIndex,e.containerRef,e.isEnabled,e.itemCount])}function Yl(){const e=v.useRef(null),[t,n]=v.useState(null);return v.useEffect(()=>{const r=e.current;if(!r||typeof ResizeObserver>"u")return;const s=()=>{n(r.getBoundingClientRect().width)};s();const i=new ResizeObserver(()=>s());return i.observe(r),()=>i.disconnect()},[]),{elementRef:e,width:t}}function oe(...e){return po(go(e))}const bi=v.forwardRef(({className:e,type:t,...n},r)=>h.jsx("input",{type:t,className:oe("flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));bi.displayName="ChatInput";const Jl=Rl,Zl=El,eu=Ml,Si=v.forwardRef(({className:e,sideOffset:t=8,align:n="start",...r},s)=>h.jsx(Al,{children:h.jsx(hi,{ref:s,sideOffset:t,align:n,className:oe("z-[var(--z-popover,50)] w-72 overflow-hidden rounded-2xl border border-gray-200/50 bg-white p-4 shadow-lg animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Si.displayName=hi.displayName;const tu=mo,nu=yo,ki=v.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(qs,{ref:r,className:oe("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-xl border border-gray-200/80 bg-white px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,h.jsx(xo,{asChild:!0,children:h.jsx(Ws,{className:"h-4 w-4 opacity-50"})})]}));ki.displayName=qs.displayName;const wi=v.forwardRef(({className:e,...t},n)=>h.jsx(Xs,{ref:n,className:oe("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(vo,{className:"h-4 w-4"})}));wi.displayName=Xs.displayName;const vi=v.forwardRef(({className:e,...t},n)=>h.jsx(Ys,{ref:n,className:oe("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(Ws,{className:"h-4 w-4"})}));vi.displayName=Ys.displayName;const Ci=v.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>h.jsx(bo,{children:h.jsxs(Gs,{ref:s,className:oe("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md bg-white text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[h.jsx(wi,{}),h.jsx(So,{className:oe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),h.jsx(vi,{})]})}));Ci.displayName=Gs.displayName;const Ii=v.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(Qs,{ref:r,className:oe("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-gray-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-gray-100",e),...n,children:[h.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:h.jsx(ko,{children:h.jsx(Xn,{className:"h-4 w-4"})})}),h.jsx(wo,{children:t})]}));Ii.displayName=Qs.displayName;const ru=wl,su=vl,iu=Cl,Ti=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>h.jsx(Il,{children:h.jsx(li,{ref:r,sideOffset:t,className:oe("z-[var(--z-tooltip)] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));Ti.displayName=li.displayName;const wt={Popover:Jl,PopoverAnchor:eu,PopoverContent:Si,PopoverTrigger:Zl,Input:bi,Select:tu,SelectContent:Ci,SelectItem:Ii,SelectTrigger:ki,SelectValue:nu,Tooltip:su,TooltipContent:Ti,TooltipProvider:ru,TooltipTrigger:iu},au=680,ou=.82,lu=560;function uu(e){const{Popover:t,PopoverAnchor:n,PopoverContent:r}=wt,{elementRef:s,width:i}=Yl(),a=v.useRef(null),{isOpen:o,isLoading:u,items:l,activeIndex:c,activeItem:d,texts:p,onSelectItem:f,onOpenChange:y,onSetActiveIndex:m}=e,S=v.useMemo(()=>{if(i)return Math.min(i>lu?i*ou:i,au)},[i]);return xi({containerRef:a,activeIndex:c,itemCount:l.length,isEnabled:o&&!u,getItemSelector:g=>`[data-slash-index="${g}"]`}),h.jsxs(t,{open:o,onOpenChange:y,children:[h.jsx(n,{asChild:!0,children:h.jsx("div",{ref:s,className:"pointer-events-none absolute bottom-full left-3 right-3 h-0"})}),h.jsx(r,{side:"top",align:"start",sideOffset:10,className:"z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md",onOpenAutoFocus:g=>g.preventDefault(),style:S?{width:`${S}px`}:void 0,children:h.jsxs("div",{className:"grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]",children:[h.jsx("div",{ref:a,role:"listbox","aria-label":p.slashSectionLabel,className:"custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5",children:u?h.jsx("div",{className:"p-2 text-xs text-gray-500",children:p.slashLoadingLabel}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500",children:p.slashSectionLabel}),l.length===0?h.jsx("div",{className:"px-2 text-xs text-gray-400",children:p.slashEmptyLabel}):h.jsx("div",{className:"space-y-1",children:l.map((g,k)=>{const w=k===c;return h.jsxs("button",{type:"button",role:"option","aria-selected":w,"data-slash-index":k,onMouseEnter:()=>m(k),onClick:()=>f(g),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${w?"bg-gray-100 text-gray-900":"text-gray-700 hover:bg-gray-50"}`,children:[h.jsx("span",{className:"truncate text-xs font-semibold",children:g.title}),h.jsx("span",{className:"truncate text-xs text-gray-500",children:g.subtitle})]},g.key)})})]})}),h.jsx("div",{className:"max-w-[320px] p-3.5",children:d?h.jsxs("div",{className:"space-y-3",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary",children:d.subtitle}),h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:d.title})]}),h.jsx("p",{className:"text-xs leading-5 text-gray-600",children:d.description}),h.jsx("div",{className:"space-y-1",children:d.detailLines.map(g=>h.jsx("div",{className:"rounded-md bg-gray-50 px-2 py-1 text-[11px] text-gray-600",children:g},g))}),h.jsx("div",{className:"pt-1 text-[11px] text-gray-500",children:p.slashSkillHintLabel})]}):h.jsx("div",{className:"text-xs text-gray-500",children:p.slashHintLabel})})]})})]})}const cu=Co("inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600",secondary:"bg-gray-100 text-gray-700 hover:bg-gray-200/80",ghost:"hover:bg-gray-100/80 hover:text-gray-800",link:"text-primary underline-offset-4 hover:underline",primary:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm",subtle:"bg-gray-100 text-gray-600 hover:bg-gray-200/80","primary-outline":"border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground"},size:{default:"h-9 px-4 py-2",sm:"h-8 px-3 text-xs",lg:"h-11 px-5 text-[14px]",xl:"h-12 px-6 text-[15px]",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Pt=v.forwardRef(({className:e,variant:t,size:n,...r},s)=>h.jsx("button",{className:oe(cu({variant:t,size:n,className:e})),ref:s,...r}));Pt.displayName="ChatButton";function Ar(){return h.jsx("span",{"aria-hidden":"true","data-testid":"chat-stop-icon",className:"block h-3 w-3 rounded-[2px] bg-gray-700 shadow-[inset_0_0_0_1px_rgba(17,24,39,0.06)]"})}function du(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=wt;return h.jsxs("div",{className:"flex flex-col items-end gap-1",children:[(i=e.sendError)!=null&&i.trim()?h.jsx("div",{className:"max-w-[420px] text-right text-[11px] text-red-600",children:e.sendError}):null,h.jsx("div",{className:"flex items-center gap-2",children:e.isSending?e.canStopGeneration?h.jsx(Pt,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,onClick:()=>void e.onStop(),disabled:e.stopDisabled,children:h.jsx(Ar,{})}):h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:h.jsx("span",{children:h.jsx(Pt,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,disabled:!0,children:h.jsx(Ar,{})})})}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:e.stopHint})})]})}):h.jsx(Pt,{size:"icon",className:"h-8 w-8 rounded-full","aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:h.jsx(Io,{className:"h-5 w-5"})})})]})}function hu(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>[r.label,r.key,r.description].filter(i=>typeof i=="string"&&i.trim().length>0).join(" ").toLowerCase().includes(n)):e}function fu(e){const{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:s}=wt,{picker:i}=e,a=v.useRef(null),o=v.useId(),[u,l]=v.useState(""),[c,d]=v.useState(0),p=v.useMemo(()=>new Set(i.selectedKeys),[i.selectedKeys]),f=i.selectedKeys.length,y=v.useMemo(()=>hu(i.options,u),[i.options,u]);v.useEffect(()=>{d(0)},[u]),v.useEffect(()=>{d(g=>y.length===0?0:Math.min(g,y.length-1))},[y.length]),xi({containerRef:a,activeIndex:c,itemCount:y.length,isEnabled:y.length>0,getItemSelector:g=>`[data-skill-index="${g}"]`});const m=g=>{if(p.has(g)){i.onSelectedKeysChange(i.selectedKeys.filter(k=>k!==g));return}i.onSelectedKeysChange([...i.selectedKeys,g])},S=g=>{if(y.length!==0){if(g.key==="ArrowDown"){g.preventDefault(),d(k=>Math.min(k+1,y.length-1));return}if(g.key==="ArrowUp"){g.preventDefault(),d(k=>Math.max(k-1,0));return}if(g.key==="Enter"){g.preventDefault();const k=y[c];k&&m(k.key)}}};return h.jsxs(n,{children:[h.jsx(s,{asChild:!0,children:h.jsxs("button",{type:"button","aria-haspopup":"listbox",className:"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900",children:[h.jsx(Qn,{className:"h-4 w-4"}),h.jsx("span",{children:i.title}),f>0?h.jsx("span",{className:"ml-0.5 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-primary/10 text-[10px] font-semibold text-primary",children:f}):null]})}),h.jsxs(r,{side:"top",align:"start",className:"w-[360px] p-0",children:[h.jsxs("div",{className:"space-y-2 border-b border-gray-100 px-4 py-3",children:[h.jsx("div",{className:"text-sm font-semibold text-gray-900",children:i.title}),h.jsxs("div",{className:"relative",children:[h.jsx(Wn,{className:"pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400"}),h.jsx(t,{value:u,onChange:g=>l(g.target.value),onKeyDown:S,placeholder:i.searchPlaceholder,role:"combobox","aria-controls":o,"aria-expanded":"true","aria-autocomplete":"list","aria-activedescendant":y[c]?`${o}-option-${c}`:void 0,className:"h-8 rounded-lg pl-8 text-xs"})]})]}),h.jsx("div",{ref:a,id:o,role:"listbox","aria-multiselectable":"true",className:"custom-scrollbar max-h-[320px] overflow-y-auto",children:i.isLoading?h.jsx("div",{className:"p-4 text-xs text-gray-500",children:i.loadingLabel}):y.length===0?h.jsx("div",{className:"p-4 text-center text-xs text-gray-500",children:i.emptyLabel}):h.jsx("div",{className:"py-1",children:y.map((g,k)=>{const w=p.has(g.key),E=k===c;return h.jsxs("button",{type:"button",id:`${o}-option-${k}`,role:"option","aria-selected":w,"data-skill-index":k,onClick:()=>m(g.key),onMouseEnter:()=>d(k),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${E?"bg-gray-50":"hover:bg-gray-50"}`,children:[h.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500",children:h.jsx(To,{className:"h-4 w-4"})}),h.jsxs("div",{className:"min-w-0 flex-1",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:"truncate text-sm text-gray-900",children:g.label}),g.badgeLabel?h.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary",children:g.badgeLabel}):null]}),h.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-500",children:g.description||g.key})]}),h.jsx("div",{className:"ml-3 shrink-0",children:h.jsx("span",{className:w?"inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-white":"inline-flex h-5 w-5 items-center justify-center rounded-full border border-gray-300 bg-white",children:w?h.jsx(Xn,{className:"h-3 w-3"}):null})})]},g.key)})})}),i.manageHref&&i.manageLabel?h.jsx("div",{className:"border-t border-gray-100 px-4 py-2.5",children:h.jsxs("a",{href:i.manageHref,className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80",children:[i.manageLabel,h.jsx(Ro,{className:"h-3 w-3"})]})}):null]})]})}function Ri({icon:e}){return e==="sparkles"?h.jsx(Ao,{className:"h-3.5 w-3.5 shrink-0 text-primary"}):e==="brain"?h.jsx(Eo,{className:"h-3.5 w-3.5 shrink-0 text-gray-500"}):null}function pu({icon:e}){return e==="paperclip"?h.jsx(Mo,{className:"h-4 w-4"}):h.jsx(Ri,{icon:e})}function gu(e){return e==="model"?"min-w-[220px]":e==="session-type"?"min-w-[140px]":e==="thinking"?"min-w-[150px]":""}function mu(e){return e==="model"?"w-[320px]":e==="session-type"?"w-[220px]":e==="thinking"?"w-[180px]":""}function yu({item:e}){const{Select:t,SelectContent:n,SelectItem:r,SelectTrigger:s,SelectValue:i}=wt;return h.jsxs(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[h.jsx(s,{className:`h-8 w-auto rounded-lg border-0 bg-transparent px-3 text-xs font-medium text-gray-600 shadow-none hover:bg-gray-100 focus:ring-0 ${gu(e.key)}`,children:e.selectedLabel?h.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-left",children:[h.jsx(Ri,{icon:e.icon}),h.jsx("span",{className:"truncate text-xs font-semibold text-gray-700",children:e.selectedLabel})]}):e.loading?h.jsx("div",{className:"h-3 w-24 animate-pulse rounded bg-gray-200"}):h.jsx(i,{placeholder:e.placeholder})}),h.jsxs(n,{className:mu(e.key),children:[e.options.length===0?e.loading?h.jsxs("div",{className:"space-y-2 px-3 py-2",children:[h.jsx("div",{className:"h-3 w-36 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-3 w-28 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-3 w-32 animate-pulse rounded bg-gray-200"})]}):e.emptyLabel?h.jsx("div",{className:"px-3 py-2 text-xs text-gray-500",children:e.emptyLabel}):null:null,e.options.map(a=>h.jsx(r,{value:a.value,className:"py-2",children:a.description?h.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:a.label}),h.jsx("span",{className:"truncate text-[11px] text-gray-500",children:a.description})]}):h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:a.label})},a.value))]})]})}function xu(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=wt;return h.jsxs("div",{className:"flex items-center justify-between px-3 pb-3",children:[h.jsxs("div",{className:"flex items-center gap-1",children:[e.skillPicker?h.jsx(fu,{picker:e.skillPicker}):null,e.selects.map(a=>h.jsx(yu,{item:a},a.key)),(i=e.accessories)==null?void 0:i.map(a=>{const o=h.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 disabled:cursor-not-allowed disabled:text-gray-400",onClick:a.onClick,disabled:a.disabled,"aria-label":a.label,children:[h.jsx(pu,{icon:a.icon}),h.jsx("span",{children:a.label})]});return a.tooltip?h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:o}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:a.tooltip})})]})},a.key):h.jsx("div",{children:o},a.key)})]}),h.jsx(du,{...e.actions})]})}function bu({hint:e}){if(!e)return null;if(e.loading)return h.jsx("div",{className:"px-4 pb-2",children:h.jsxs("div",{className:"inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2",children:[h.jsx("span",{className:"h-3 w-28 animate-pulse rounded bg-gray-200"}),h.jsx("span",{className:"h-3 w-16 animate-pulse rounded bg-gray-200"})]})});const t=e.tone==="warning"?"border-amber-200 bg-amber-50 text-amber-800":"border-gray-200 bg-gray-50 text-gray-700";return h.jsx("div",{className:"px-4 pb-2",children:h.jsxs("div",{className:`inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs ${t}`,children:[e.text?h.jsx("span",{children:e.text}):null,e.actionLabel&&e.onAction?h.jsx("button",{type:"button",onClick:e.onAction,className:"font-semibold underline-offset-2 hover:underline",children:e.actionLabel}):null]})})}function Su(e){return h.jsx("div",{className:"border-t border-gray-200/80 bg-white p-4",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)]",children:h.jsxs("div",{className:"overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-card",children:[h.jsxs("div",{className:"relative",children:[h.jsx(Gl,{value:e.value,placeholder:e.placeholder,disabled:e.disabled,onValueChange:e.onValueChange,onKeyDown:e.onKeyDown}),h.jsx(uu,{...e.slashMenu})]}),h.jsx(bu,{hint:e.hint}),h.jsx(Ql,{items:e.selectedItems.items,onRemove:e.selectedItems.onRemove}),h.jsx(xu,{...e.toolbar})]})})})}function Jt({role:e}){return e==="user"?h.jsx("div",{"data-testid":"chat-message-avatar-user",className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-white shadow-sm",children:h.jsx(Lo,{className:"h-4 w-4"})}):e==="tool"?h.jsx("div",{"data-testid":"chat-message-avatar-tool",className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700 shadow-sm",children:h.jsx(Js,{className:"h-4 w-4"})}):h.jsx("div",{"data-testid":"chat-message-avatar-assistant",className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-gray-200/80 bg-gray-900 text-white shadow-sm",children:h.jsx(Zs,{className:"h-4 w-4"})})}function ku(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const wu=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,vu=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Cu={};function Er(e,t){return(Cu.jsx?vu:wu).test(e)}const Iu=/[ \t\n\f\r]/g;function Tu(e){return typeof e=="object"?e.type==="text"?Lr(e.value):!1:Lr(e)}function Lr(e){return e.replace(Iu,"")===""}class vt{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}vt.prototype.normal={};vt.prototype.property={};vt.prototype.space=void 0;function Mi(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new vt(n,r,t)}function En(e){return e.toLowerCase()}class be{constructor(t,n){this.attribute=n,this.property=t}}be.prototype.attribute="";be.prototype.booleanish=!1;be.prototype.boolean=!1;be.prototype.commaOrSpaceSeparated=!1;be.prototype.commaSeparated=!1;be.prototype.defined=!1;be.prototype.mustUseProperty=!1;be.prototype.number=!1;be.prototype.overloadedBoolean=!1;be.prototype.property="";be.prototype.spaceSeparated=!1;be.prototype.space=void 0;let Ru=0;const H=Je(),ie=Je(),Ln=Je(),A=Je(),ee=Je(),it=Je(),we=Je();function Je(){return 2**++Ru}const Nn=Object.freeze(Object.defineProperty({__proto__:null,boolean:H,booleanish:ie,commaOrSpaceSeparated:we,commaSeparated:it,number:A,overloadedBoolean:Ln,spaceSeparated:ee},Symbol.toStringTag,{value:"Module"})),Zt=Object.keys(Nn);class tr extends be{constructor(t,n,r,s){let i=-1;if(super(t,n),Nr(this,"space",s),typeof r=="number")for(;++i<Zt.length;){const a=Zt[i];Nr(this,Zt[i],(r&Nn[a])===Nn[a])}}}tr.prototype.defined=!0;function Nr(e,t,n){n&&(e[t]=n)}function ot(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new tr(r,e.transform(e.attributes||{},r),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[En(r)]=r,n[En(i.attribute)]=r}return new vt(t,n,e.space)}const Ai=ot({properties:{ariaActiveDescendant:null,ariaAtomic:ie,ariaAutoComplete:null,ariaBusy:ie,ariaChecked:ie,ariaColCount:A,ariaColIndex:A,ariaColSpan:A,ariaControls:ee,ariaCurrent:null,ariaDescribedBy:ee,ariaDetails:null,ariaDisabled:ie,ariaDropEffect:ee,ariaErrorMessage:null,ariaExpanded:ie,ariaFlowTo:ee,ariaGrabbed:ie,ariaHasPopup:null,ariaHidden:ie,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ee,ariaLevel:A,ariaLive:null,ariaModal:ie,ariaMultiLine:ie,ariaMultiSelectable:ie,ariaOrientation:null,ariaOwns:ee,ariaPlaceholder:null,ariaPosInSet:A,ariaPressed:ie,ariaReadOnly:ie,ariaRelevant:null,ariaRequired:ie,ariaRoleDescription:ee,ariaRowCount:A,ariaRowIndex:A,ariaRowSpan:A,ariaSelected:ie,ariaSetSize:A,ariaSort:null,ariaValueMax:A,ariaValueMin:A,ariaValueNow:A,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Ei(e,t){return t in e?e[t]:t}function Li(e,t){return Ei(e,t.toLowerCase())}const Mu=ot({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:it,acceptCharset:ee,accessKey:ee,action:null,allow:null,allowFullScreen:H,allowPaymentRequest:H,allowUserMedia:H,alt:null,as:null,async:H,autoCapitalize:null,autoComplete:ee,autoFocus:H,autoPlay:H,blocking:ee,capture:null,charSet:null,checked:H,cite:null,className:ee,cols:A,colSpan:null,content:null,contentEditable:ie,controls:H,controlsList:ee,coords:A|it,crossOrigin:null,data:null,dateTime:null,decoding:null,default:H,defer:H,dir:null,dirName:null,disabled:H,download:Ln,draggable:ie,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:H,formTarget:null,headers:ee,height:A,hidden:Ln,high:A,href:null,hrefLang:null,htmlFor:ee,httpEquiv:ee,id:null,imageSizes:null,imageSrcSet:null,inert:H,inputMode:null,integrity:null,is:null,isMap:H,itemId:null,itemProp:ee,itemRef:ee,itemScope:H,itemType:ee,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:H,low:A,manifest:null,max:null,maxLength:A,media:null,method:null,min:null,minLength:A,multiple:H,muted:H,name:null,nonce:null,noModule:H,noValidate:H,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:H,optimum:A,pattern:null,ping:ee,placeholder:null,playsInline:H,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:H,referrerPolicy:null,rel:ee,required:H,reversed:H,rows:A,rowSpan:A,sandbox:ee,scope:null,scoped:H,seamless:H,selected:H,shadowRootClonable:H,shadowRootDelegatesFocus:H,shadowRootMode:null,shape:null,size:A,sizes:null,slot:null,span:A,spellCheck:ie,src:null,srcDoc:null,srcLang:null,srcSet:null,start:A,step:null,style:null,tabIndex:A,target:null,title:null,translate:null,type:null,typeMustMatch:H,useMap:null,value:ie,width:A,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ee,axis:null,background:null,bgColor:null,border:A,borderColor:null,bottomMargin:A,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:H,declare:H,event:null,face:null,frame:null,frameBorder:null,hSpace:A,leftMargin:A,link:null,longDesc:null,lowSrc:null,marginHeight:A,marginWidth:A,noResize:H,noHref:H,noShade:H,noWrap:H,object:null,profile:null,prompt:null,rev:null,rightMargin:A,rules:null,scheme:null,scrolling:ie,standby:null,summary:null,text:null,topMargin:A,valueType:null,version:null,vAlign:null,vLink:null,vSpace:A,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:H,disableRemotePlayback:H,prefix:null,property:null,results:A,security:null,unselectable:null},space:"html",transform:Li}),Au=ot({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:we,accentHeight:A,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:A,amplitude:A,arabicForm:null,ascent:A,attributeName:null,attributeType:null,azimuth:A,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:A,by:null,calcMode:null,capHeight:A,className:ee,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:A,diffuseConstant:A,direction:null,display:null,dur:null,divisor:A,dominantBaseline:null,download:H,dx:null,dy:null,edgeMode:null,editable:null,elevation:A,enableBackground:null,end:null,event:null,exponent:A,externalResourcesRequired:null,fill:null,fillOpacity:A,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:it,g2:it,glyphName:it,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:A,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:A,horizOriginX:A,horizOriginY:A,id:null,ideographic:A,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:A,k:A,k1:A,k2:A,k3:A,k4:A,kernelMatrix:we,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:A,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:A,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:A,overlineThickness:A,paintOrder:null,panose1:null,path:null,pathLength:A,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ee,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:A,pointsAtY:A,pointsAtZ:A,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:we,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:we,rev:we,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:we,requiredFeatures:we,requiredFonts:we,requiredFormats:we,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:A,specularExponent:A,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:A,strikethroughThickness:A,string:null,stroke:null,strokeDashArray:we,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:A,strokeOpacity:A,strokeWidth:null,style:null,surfaceScale:A,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:we,tabIndex:A,tableValues:null,target:null,targetX:A,targetY:A,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:we,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:A,underlineThickness:A,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:A,values:null,vAlphabetic:A,vMathematical:A,vectorEffect:null,vHanging:A,vIdeographic:A,version:null,vertAdvY:A,vertOriginX:A,vertOriginY:A,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:A,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Ei}),Ni=ot({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Pi=ot({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Li}),ji=ot({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Eu={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Lu=/[A-Z]/g,Pr=/-[a-z]/g,Nu=/^data[-\w.:]+$/i;function Pu(e,t){const n=En(t);let r=t,s=be;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Nu.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Pr,Du);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Pr.test(i)){let a=i.replace(Lu,ju);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}s=tr}return new s(r,t)}function ju(e){return"-"+e.toLowerCase()}function Du(e){return e.charAt(1).toUpperCase()}const _u=Mi([Ai,Mu,Ni,Pi,ji],"html"),nr=Mi([Ai,Au,Ni,Pi,ji],"svg");function Ou(e){return e.join(" ").trim()}var et={},en,jr;function zu(){if(jr)return en;jr=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,u=`
|
|
2
|
-
`,l="/",c="*",d="",p="comment",f="declaration";function y(S,g){if(typeof S!="string")throw new TypeError("First argument must be a string");if(!S)return[];g=g||{};var k=1,w=1;function E(z){var N=z.match(t);N&&(k+=N.length);var q=z.lastIndexOf(u);w=~q?z.length-q:w+z.length}function M(){var z={line:k,column:w};return function(N){return N.position=new I(z),F(),N}}function I(z){this.start=z,this.end={line:k,column:w},this.source=g.source}I.prototype.content=S;function P(z){var N=new Error(g.source+":"+k+":"+w+": "+z);if(N.reason=z,N.filename=g.source,N.line=k,N.column=w,N.source=S,!g.silent)throw N}function D(z){var N=z.exec(S);if(N){var q=N[0];return E(q),S=S.slice(q.length),N}}function F(){D(n)}function C(z){var N;for(z=z||[];N=_();)N!==!1&&z.push(N);return z}function _(){var z=M();if(!(l!=S.charAt(0)||c!=S.charAt(1))){for(var N=2;d!=S.charAt(N)&&(c!=S.charAt(N)||l!=S.charAt(N+1));)++N;if(N+=2,d===S.charAt(N-1))return P("End of comment missing");var q=S.slice(2,N-2);return w+=2,E(q),S=S.slice(N),w+=2,z({type:p,comment:q})}}function O(){var z=M(),N=D(r);if(N){if(_(),!D(s))return P("property missing ':'");var q=D(i),Y=z({type:f,property:m(N[0].replace(e,d)),value:q?m(q[0].replace(e,d)):d});return D(a),Y}}function G(){var z=[];C(z);for(var N;N=O();)N!==!1&&(z.push(N),C(z));return z}return F(),G()}function m(S){return S?S.replace(o,d):d}return en=y,en}var Dr;function Fu(){if(Dr)return et;Dr=1;var e=et&&et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(et,"__esModule",{value:!0}),et.default=n;const t=e(zu());function n(r,s){let i=null;if(!r||typeof r!="string")return i;const a=(0,t.default)(r),o=typeof s=="function";return a.forEach(u=>{if(u.type!=="declaration")return;const{property:l,value:c}=u;o?s(l,c,u):c&&(i=i||{},i[l]=c)}),i}return et}var dt={},_r;function Bu(){if(_r)return dt;_r=1,Object.defineProperty(dt,"__esModule",{value:!0}),dt.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,s=/^-(ms)-/,i=function(l){return!l||n.test(l)||e.test(l)},a=function(l,c){return c.toUpperCase()},o=function(l,c){return"".concat(c,"-")},u=function(l,c){return c===void 0&&(c={}),i(l)?l:(l=l.toLowerCase(),c.reactCompat?l=l.replace(s,o):l=l.replace(r,o),l.replace(t,a))};return dt.camelCase=u,dt}var ht,Or;function $u(){if(Or)return ht;Or=1;var e=ht&&ht.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},t=e(Fu()),n=Bu();function r(s,i){var a={};return!s||typeof s!="string"||(0,t.default)(s,function(o,u){o&&u&&(a[(0,n.camelCase)(o,i)]=u)}),a}return r.default=r,ht=r,ht}var Uu=$u();const Hu=ei(Uu),Di=_i("end"),rr=_i("start");function _i(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Ku(e){const t=rr(e),n=Di(e);if(t&&n)return{start:t,end:n}}function mt(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?zr(e.position):"start"in e||"end"in e?zr(e):"line"in e||"column"in e?Pn(e):""}function Pn(e){return Fr(e&&e.line)+":"+Fr(e&&e.column)}function zr(e){return Pn(e&&e.start)+"-"+Pn(e&&e.end)}function Fr(e){return e&&typeof e=="number"?e:1}class fe extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},a=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?s=t:!i.cause&&t&&(a=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const u=r.indexOf(":");u===-1?i.ruleId=r:(i.source=r.slice(0,u),i.ruleId=r.slice(u+1))}if(!i.place&&i.ancestors&&i.ancestors){const u=i.ancestors[i.ancestors.length-1];u&&(i.place=u.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=o?o.line:void 0,this.name=mt(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}fe.prototype.file="";fe.prototype.name="";fe.prototype.reason="";fe.prototype.message="";fe.prototype.stack="";fe.prototype.column=void 0;fe.prototype.line=void 0;fe.prototype.ancestors=void 0;fe.prototype.cause=void 0;fe.prototype.fatal=void 0;fe.prototype.place=void 0;fe.prototype.ruleId=void 0;fe.prototype.source=void 0;const sr={}.hasOwnProperty,Vu=new Map,qu=/[A-Z]/g,Wu=new Set(["table","tbody","thead","tfoot","tr"]),Gu=new Set(["td","th"]),Oi="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Qu(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=rc(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=nc(n,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?nr:_u,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=zi(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function zi(e,t,n){if(t.type==="element")return Xu(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Yu(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Zu(e,t,n);if(t.type==="mdxjsEsm")return Ju(e,t);if(t.type==="root")return ec(e,t,n);if(t.type==="text")return tc(e,t)}function Xu(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=nr,e.schema=s),e.ancestors.push(t);const i=Bi(e,t.tagName,!1),a=sc(e,t);let o=ar(e,t);return Wu.has(t.tagName)&&(o=o.filter(function(u){return typeof u=="string"?!Tu(u):!0})),Fi(e,a,i,t),ir(a,o),e.ancestors.pop(),e.schema=r,e.create(t,i,a,n)}function Yu(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}bt(e,t.position)}function Ju(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);bt(e,t.position)}function Zu(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=nr,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:Bi(e,t.name,!0),a=ic(e,t),o=ar(e,t);return Fi(e,a,i,t),ir(a,o),e.ancestors.pop(),e.schema=r,e.create(t,i,a,n)}function ec(e,t,n){const r={};return ir(r,ar(e,t)),e.create(t,e.Fragment,r,n)}function tc(e,t){return t.value}function Fi(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function ir(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function nc(e,t,n){return r;function r(s,i,a,o){const l=Array.isArray(a.children)?n:t;return o?l(i,a,o):l(i,a)}}function rc(e,t){return n;function n(r,s,i,a){const o=Array.isArray(i.children),u=rr(r);return t(s,i,a,o,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function sc(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&sr.call(t.properties,s)){const i=ac(e,s,t.properties[s]);if(i){const[a,o]=i;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&Gu.has(t.tagName)?r=o:n[a]=o}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function ic(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const a=i.expression;a.type;const o=a.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else bt(e,t.position);else{const s=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,i=e.evaluater.evaluateExpression(o.expression)}else bt(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function ar(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:Vu;for(;++r<t.children.length;){const i=t.children[r];let a;if(e.passKeys){const u=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(u){const l=s.get(u)||0;a=u+"-"+l,s.set(u,l+1)}}const o=zi(e,i,a);o!==void 0&&n.push(o)}return n}function ac(e,t,n){const r=Pu(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?ku(n):Ou(n)),r.property==="style"){let s=typeof n=="object"?n:oc(e,String(n));return e.stylePropertyNameCase==="css"&&(s=lc(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&r.space?Eu[r.property]||r.property:r.attribute,n]}}function oc(e,t){try{return Hu(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,s=new fe("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=Oi+"#cannot-parse-style-attribute",s}}function Bi(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,a;for(;++i<s.length;){const o=Er(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}r=a}else r=Er(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const s=r.value;return sr.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(r);bt(e)}function bt(e,t){const n=new fe("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=Oi+"#cannot-handle-mdx-estrees-without-createevaluater",n}function lc(e){const t={};let n;for(n in e)sr.call(e,n)&&(t[uc(n)]=e[n]);return t}function uc(e){let t=e.replace(qu,cc);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function cc(e){return"-"+e.toLowerCase()}const tn={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},dc={};function or(e,t){const n=dc,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return $i(e,r,s)}function $i(e,t,n){if(hc(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Br(e.children,t,n)}return Array.isArray(e)?Br(e,t,n):""}function Br(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=$i(e[s],t,n);return r.join("")}function hc(e){return!!(e&&typeof e=="object")}const $r=document.createElement("i");function lr(e){const t="&"+e+";";$r.innerHTML=t;const n=$r.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function ve(e,t,n,r){const s=e.length;let i=0,a;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)a=Array.from(r),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);i<r.length;)a=r.slice(i,i+1e4),a.unshift(t,0),e.splice(...a),i+=1e4,t+=1e4}function Re(e,t){return e.length>0?(ve(e,e.length,0,t),e):t}const Ur={}.hasOwnProperty;function Ui(e){const t={};let n=-1;for(;++n<e.length;)fc(t,e[n]);return t}function fc(e,t){let n;for(n in t){const s=(Ur.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let a;if(i)for(a in i){Ur.call(s,a)||(s[a]=[]);const o=i[a];pc(s[a],Array.isArray(o)?o:o?[o]:[])}}}function pc(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);ve(e,0,0,r)}function Hi(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ne(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ge=We(/[A-Za-z]/),he=We(/[\dA-Za-z]/),gc=We(/[#-'*+\--9=?A-Z^-~]/);function zt(e){return e!==null&&(e<32||e===127)}const jn=We(/\d/),mc=We(/[\dA-Fa-f]/),yc=We(/[!-/:-@[-`{-~]/);function B(e){return e!==null&&e<-2}function Z(e){return e!==null&&(e<0||e===32)}function V(e){return e===-2||e===-1||e===32}const Vt=We(new RegExp("\\p{P}|\\p{S}","u")),Ye=We(/\s/);function We(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function lt(e){const t=[];let n=-1,r=0,s=0;for(;++n<e.length;){const i=e.charCodeAt(n);let a="";if(i===37&&he(e.charCodeAt(n+1))&&he(e.charCodeAt(n+2)))s=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(a=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(n+1);i<56320&&o>56319&&o<57344?(a=String.fromCharCode(i,o),s=1):a="�"}else a=String.fromCharCode(i);a&&(t.push(e.slice(r,n),encodeURIComponent(a)),r=n+s+1,a=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function X(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return a;function a(u){return V(u)?(e.enter(n),o(u)):t(u)}function o(u){return V(u)&&i++<s?(e.consume(u),o):(e.exit(n),t(u))}}const xc={tokenize:bc};function bc(e){const t=e.attempt(this.parser.constructs.contentInitial,r,s);let n;return t;function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),X(e,t,"linePrefix")}function s(o){return e.enter("paragraph"),i(o)}function i(o){const u=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=u),n=u,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return B(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),a)}}const Sc={tokenize:kc},Hr={tokenize:wc};function kc(e){const t=this,n=[];let r=0,s,i,a;return o;function o(w){if(r<n.length){const E=n[r];return t.containerState=E[1],e.attempt(E[0].continuation,u,l)(w)}return l(w)}function u(w){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&k();const E=t.events.length;let M=E,I;for(;M--;)if(t.events[M][0]==="exit"&&t.events[M][1].type==="chunkFlow"){I=t.events[M][1].end;break}g(r);let P=E;for(;P<t.events.length;)t.events[P][1].end={...I},P++;return ve(t.events,M+1,0,t.events.slice(E)),t.events.length=P,l(w)}return o(w)}function l(w){if(r===n.length){if(!s)return p(w);if(s.currentConstruct&&s.currentConstruct.concrete)return y(w);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Hr,c,d)(w)}function c(w){return s&&k(),g(r),p(w)}function d(w){return t.parser.lazy[t.now().line]=r!==n.length,a=t.now().offset,y(w)}function p(w){return t.containerState={},e.attempt(Hr,f,y)(w)}function f(w){return r++,n.push([t.currentConstruct,t.containerState]),p(w)}function y(w){if(w===null){s&&k(),g(0),e.consume(w);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),m(w)}function m(w){if(w===null){S(e.exit("chunkFlow"),!0),g(0),e.consume(w);return}return B(w)?(e.consume(w),S(e.exit("chunkFlow")),r=0,t.interrupt=void 0,o):(e.consume(w),m)}function S(w,E){const M=t.sliceStream(w);if(E&&M.push(null),w.previous=i,i&&(i.next=w),i=w,s.defineSkip(w.start),s.write(M),t.parser.lazy[w.start.line]){let I=s.events.length;for(;I--;)if(s.events[I][1].start.offset<a&&(!s.events[I][1].end||s.events[I][1].end.offset>a))return;const P=t.events.length;let D=P,F,C;for(;D--;)if(t.events[D][0]==="exit"&&t.events[D][1].type==="chunkFlow"){if(F){C=t.events[D][1].end;break}F=!0}for(g(r),I=P;I<t.events.length;)t.events[I][1].end={...C},I++;ve(t.events,D+1,0,t.events.slice(P)),t.events.length=I}}function g(w){let E=n.length;for(;E-- >w;){const M=n[E];t.containerState=M[1],M[0].exit.call(t,e)}n.length=w}function k(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function wc(e,t,n){return X(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function at(e){if(e===null||Z(e)||Ye(e))return 1;if(Vt(e))return 2}function qt(e,t,n){const r=[];let s=-1;for(;++s<e.length;){const i=e[s].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}const Dn={name:"attention",resolveAll:vc,tokenize:Cc};function vc(e,t){let n=-1,r,s,i,a,o,u,l,c;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;u=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},p={...e[n][1].start};Kr(d,-u),Kr(p,u),a={type:u>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},o={type:u>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:p},i={type:u>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},s={type:u>1?"strong":"emphasis",start:{...a.start},end:{...o.end}},e[r][1].end={...a.start},e[n][1].start={...o.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=Re(l,[["enter",e[r][1],t],["exit",e[r][1],t]])),l=Re(l,[["enter",s,t],["enter",a,t],["exit",a,t],["enter",i,t]]),l=Re(l,qt(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=Re(l,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,l=Re(l,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,ve(e,r-1,n-r+3,l),n=r+l.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function Cc(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,s=at(r);let i;return a;function a(u){return i=u,e.enter("attentionSequence"),o(u)}function o(u){if(u===i)return e.consume(u),o;const l=e.exit("attentionSequence"),c=at(u),d=!c||c===2&&s||n.includes(u),p=!s||s===2&&c||n.includes(r);return l._open=!!(i===42?d:d&&(s||!p)),l._close=!!(i===42?p:p&&(c||!d)),t(u)}}function Kr(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Ic={name:"autolink",tokenize:Tc};function Tc(e,t,n){let r=0;return s;function s(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return ge(f)?(e.consume(f),a):f===64?n(f):l(f)}function a(f){return f===43||f===45||f===46||he(f)?(r=1,o(f)):l(f)}function o(f){return f===58?(e.consume(f),r=0,u):(f===43||f===45||f===46||he(f))&&r++<32?(e.consume(f),o):(r=0,l(f))}function u(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||zt(f)?n(f):(e.consume(f),u)}function l(f){return f===64?(e.consume(f),c):gc(f)?(e.consume(f),l):n(f)}function c(f){return he(f)?d(f):n(f)}function d(f){return f===46?(e.consume(f),r=0,c):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):p(f)}function p(f){if((f===45||he(f))&&r++<63){const y=f===45?p:d;return e.consume(f),y}return n(f)}}const Ct={partial:!0,tokenize:Rc};function Rc(e,t,n){return r;function r(i){return V(i)?X(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||B(i)?t(i):n(i)}}const Ki={continuation:{tokenize:Ac},exit:Ec,name:"blockQuote",tokenize:Mc};function Mc(e,t,n){const r=this;return s;function s(a){if(a===62){const o=r.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),i}return n(a)}function i(a){return V(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function Ac(e,t,n){const r=this;return s;function s(a){return V(a)?X(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(Ki,t,n)(a)}}function Ec(e){e.exit("blockQuote")}const Vi={name:"characterEscape",tokenize:Lc};function Lc(e,t,n){return r;function r(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),s}function s(i){return yc(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const qi={name:"characterReference",tokenize:Nc};function Nc(e,t,n){const r=this;let s=0,i,a;return o;function o(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),u}function u(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),l):(e.enter("characterReferenceValue"),i=31,a=he,c(d))}function l(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=mc,c):(e.enter("characterReferenceValue"),i=7,a=jn,c(d))}function c(d){if(d===59&&s){const p=e.exit("characterReferenceValue");return a===he&&!lr(r.sliceSerialize(p))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(d)&&s++<i?(e.consume(d),c):n(d)}}const Vr={partial:!0,tokenize:jc},qr={concrete:!0,name:"codeFenced",tokenize:Pc};function Pc(e,t,n){const r=this,s={partial:!0,tokenize:M};let i=0,a=0,o;return u;function u(I){return l(I)}function l(I){const P=r.events[r.events.length-1];return i=P&&P[1].type==="linePrefix"?P[2].sliceSerialize(P[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(I)}function c(I){return I===o?(a++,e.consume(I),c):a<3?n(I):(e.exit("codeFencedFenceSequence"),V(I)?X(e,d,"whitespace")(I):d(I))}function d(I){return I===null||B(I)?(e.exit("codeFencedFence"),r.interrupt?t(I):e.check(Vr,m,E)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(I))}function p(I){return I===null||B(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(I)):V(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),X(e,f,"whitespace")(I)):I===96&&I===o?n(I):(e.consume(I),p)}function f(I){return I===null||B(I)?d(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),y(I))}function y(I){return I===null||B(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(I)):I===96&&I===o?n(I):(e.consume(I),y)}function m(I){return e.attempt(s,E,S)(I)}function S(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),g}function g(I){return i>0&&V(I)?X(e,k,"linePrefix",i+1)(I):k(I)}function k(I){return I===null||B(I)?e.check(Vr,m,E)(I):(e.enter("codeFlowValue"),w(I))}function w(I){return I===null||B(I)?(e.exit("codeFlowValue"),k(I)):(e.consume(I),w)}function E(I){return e.exit("codeFenced"),t(I)}function M(I,P,D){let F=0;return C;function C(N){return I.enter("lineEnding"),I.consume(N),I.exit("lineEnding"),_}function _(N){return I.enter("codeFencedFence"),V(N)?X(I,O,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):O(N)}function O(N){return N===o?(I.enter("codeFencedFenceSequence"),G(N)):D(N)}function G(N){return N===o?(F++,I.consume(N),G):F>=a?(I.exit("codeFencedFenceSequence"),V(N)?X(I,z,"whitespace")(N):z(N)):D(N)}function z(N){return N===null||B(N)?(I.exit("codeFencedFence"),P(N)):D(N)}}}function jc(e,t,n){const r=this;return s;function s(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i)}function i(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}const nn={name:"codeIndented",tokenize:_c},Dc={partial:!0,tokenize:Oc};function _c(e,t,n){const r=this;return s;function s(l){return e.enter("codeIndented"),X(e,i,"linePrefix",5)(l)}function i(l){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(l):n(l)}function a(l){return l===null?u(l):B(l)?e.attempt(Dc,a,u)(l):(e.enter("codeFlowValue"),o(l))}function o(l){return l===null||B(l)?(e.exit("codeFlowValue"),a(l)):(e.consume(l),o)}function u(l){return e.exit("codeIndented"),t(l)}}function Oc(e,t,n){const r=this;return s;function s(a){return r.parser.lazy[r.now().line]?n(a):B(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s):X(e,i,"linePrefix",5)(a)}function i(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):B(a)?s(a):n(a)}}const zc={name:"codeText",previous:Bc,resolve:Fc,tokenize:$c};function Fc(e){let t=e.length-4,n=3,r,s;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)s===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(s=r):(r===t||e[r][1].type==="lineEnding")&&(e[s][1].type="codeTextData",r!==s+2&&(e[s][1].end=e[r-1][1].end,e.splice(s+2,r-s-2),t-=r-s-2,r=s+2),s=void 0);return e}function Bc(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function $c(e,t,n){let r=0,s,i;return a;function a(d){return e.enter("codeText"),e.enter("codeTextSequence"),o(d)}function o(d){return d===96?(e.consume(d),r++,o):(e.exit("codeTextSequence"),u(d))}function u(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),u):d===96?(i=e.enter("codeTextSequence"),s=0,c(d)):B(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),u):(e.enter("codeTextData"),l(d))}function l(d){return d===null||d===32||d===96||B(d)?(e.exit("codeTextData"),u(d)):(e.consume(d),l)}function c(d){return d===96?(e.consume(d),s++,c):s===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(i.type="codeTextData",l(d))}}class Uc{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const s=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return r&&ft(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),ft(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),ft(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);ft(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);ft(this.left,n.reverse())}}}function ft(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function Wi(e){const t={};let n=-1,r,s,i,a,o,u,l;const c=new Uc(e);for(;++n<c.length;){for(;n in t;)n=t[n];if(r=c.get(n),n&&r[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(u=r[1]._tokenizer.events,i=0,i<u.length&&u[i][1].type==="lineEndingBlank"&&(i+=2),i<u.length&&u[i][1].type==="content"))for(;++i<u.length&&u[i][1].type!=="content";)u[i][1].type==="chunkText"&&(u[i][1]._isInFirstContentOfListItem=!0,i++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,Hc(c,n)),n=t[n],l=!0);else if(r[1]._container){for(i=n,s=void 0;i--;)if(a=c.get(i),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(s&&(c.get(s)[1].type="lineEndingBlank"),a[1].type="lineEnding",s=i);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;s&&(r[1].end={...c.get(s)[1].start},o=c.slice(s,n),o.unshift(r),c.splice(s,n-s+1,o))}}return ve(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!l}function Hc(e,t){const n=e.get(t)[1],r=e.get(t)[2];let s=t-1;const i=[];let a=n._tokenizer;a||(a=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,u=[],l={};let c,d,p=-1,f=n,y=0,m=0;const S=[m];for(;f;){for(;e.get(++s)[1]!==f;);i.push(s),f._tokenizer||(c=r.sliceStream(f),f.next||c.push(null),d&&a.defineSkip(f.start),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(c),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++p<o.length;)o[p][0]==="exit"&&o[p-1][0]==="enter"&&o[p][1].type===o[p-1][1].type&&o[p][1].start.line!==o[p][1].end.line&&(m=p+1,S.push(m),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(a.events=[],f?(f._tokenizer=void 0,f.previous=void 0):S.pop(),p=S.length;p--;){const g=o.slice(S[p],S[p+1]),k=i.pop();u.push([k,k+g.length-1]),e.splice(k,2,g)}for(u.reverse(),p=-1;++p<u.length;)l[y+u[p][0]]=y+u[p][1],y+=u[p][1]-u[p][0]-1;return l}const Kc={resolve:qc,tokenize:Wc},Vc={partial:!0,tokenize:Gc};function qc(e){return Wi(e),e}function Wc(e,t){let n;return r;function r(o){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(o)}function s(o){return o===null?i(o):B(o)?e.check(Vc,a,i)(o):(e.consume(o),s)}function i(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}function Gc(e,t,n){const r=this;return s;function s(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),X(e,i,"linePrefix")}function i(a){if(a===null||B(a))return n(a);const o=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(r.parser.constructs.flow,n,t)(a)}}function Gi(e,t,n,r,s,i,a,o,u){const l=u||Number.POSITIVE_INFINITY;let c=0;return d;function d(g){return g===60?(e.enter(r),e.enter(s),e.enter(i),e.consume(g),e.exit(i),p):g===null||g===32||g===41||zt(g)?n(g):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),m(g))}function p(g){return g===62?(e.enter(i),e.consume(g),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===62?(e.exit("chunkString"),e.exit(o),p(g)):g===null||g===60||B(g)?n(g):(e.consume(g),g===92?y:f)}function y(g){return g===60||g===62||g===92?(e.consume(g),f):f(g)}function m(g){return!c&&(g===null||g===41||Z(g))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),t(g)):c<l&&g===40?(e.consume(g),c++,m):g===41?(e.consume(g),c--,m):g===null||g===32||g===40||zt(g)?n(g):(e.consume(g),g===92?S:m)}function S(g){return g===40||g===41||g===92?(e.consume(g),m):m(g)}}function Qi(e,t,n,r,s,i){const a=this;let o=0,u;return l;function l(f){return e.enter(r),e.enter(s),e.consume(f),e.exit(s),e.enter(i),c}function c(f){return o>999||f===null||f===91||f===93&&!u||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?n(f):f===93?(e.exit(i),e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):B(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||B(f)||o++>999?(e.exit("chunkString"),c(f)):(e.consume(f),u||(u=!V(f)),f===92?p:d)}function p(f){return f===91||f===92||f===93?(e.consume(f),o++,d):d(f)}}function Xi(e,t,n,r,s,i){let a;return o;function o(p){return p===34||p===39||p===40?(e.enter(r),e.enter(s),e.consume(p),e.exit(s),a=p===40?41:p,u):n(p)}function u(p){return p===a?(e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):(e.enter(i),l(p))}function l(p){return p===a?(e.exit(i),u(a)):p===null?n(p):B(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),X(e,l,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===a||p===null||B(p)?(e.exit("chunkString"),l(p)):(e.consume(p),p===92?d:c)}function d(p){return p===a||p===92?(e.consume(p),c):c(p)}}function yt(e,t){let n;return r;function r(s){return B(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):V(s)?X(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const Qc={name:"definition",tokenize:Yc},Xc={partial:!0,tokenize:Jc};function Yc(e,t,n){const r=this;let s;return i;function i(f){return e.enter("definition"),a(f)}function a(f){return Qi.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return s=Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),u):n(f)}function u(f){return Z(f)?yt(e,l)(f):l(f)}function l(f){return Gi(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(Xc,d,d)(f)}function d(f){return V(f)?X(e,p,"whitespace")(f):p(f)}function p(f){return f===null||B(f)?(e.exit("definition"),r.parser.defined.push(s),t(f)):n(f)}}function Jc(e,t,n){return r;function r(o){return Z(o)?yt(e,s)(o):n(o)}function s(o){return Xi(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return V(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||B(o)?t(o):n(o)}}const Zc={name:"hardBreakEscape",tokenize:ed};function ed(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return B(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const td={name:"headingAtx",resolve:nd,tokenize:rd};function nd(e,t){let n=e.length-2,r=3,s,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(s={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},ve(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function rd(e,t,n){let r=0;return s;function s(c){return e.enter("atxHeading"),i(c)}function i(c){return e.enter("atxHeadingSequence"),a(c)}function a(c){return c===35&&r++<6?(e.consume(c),a):c===null||Z(c)?(e.exit("atxHeadingSequence"),o(c)):n(c)}function o(c){return c===35?(e.enter("atxHeadingSequence"),u(c)):c===null||B(c)?(e.exit("atxHeading"),t(c)):V(c)?X(e,o,"whitespace")(c):(e.enter("atxHeadingText"),l(c))}function u(c){return c===35?(e.consume(c),u):(e.exit("atxHeadingSequence"),o(c))}function l(c){return c===null||c===35||Z(c)?(e.exit("atxHeadingText"),o(c)):(e.consume(c),l)}}const sd=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Wr=["pre","script","style","textarea"],id={concrete:!0,name:"htmlFlow",resolveTo:ld,tokenize:ud},ad={partial:!0,tokenize:dd},od={partial:!0,tokenize:cd};function ld(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function ud(e,t,n){const r=this;let s,i,a,o,u;return l;function l(b){return c(b)}function c(b){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(b),d}function d(b){return b===33?(e.consume(b),p):b===47?(e.consume(b),i=!0,m):b===63?(e.consume(b),s=3,r.interrupt?t:x):ge(b)?(e.consume(b),a=String.fromCharCode(b),S):n(b)}function p(b){return b===45?(e.consume(b),s=2,f):b===91?(e.consume(b),s=5,o=0,y):ge(b)?(e.consume(b),s=4,r.interrupt?t:x):n(b)}function f(b){return b===45?(e.consume(b),r.interrupt?t:x):n(b)}function y(b){const ce="CDATA[";return b===ce.charCodeAt(o++)?(e.consume(b),o===ce.length?r.interrupt?t:O:y):n(b)}function m(b){return ge(b)?(e.consume(b),a=String.fromCharCode(b),S):n(b)}function S(b){if(b===null||b===47||b===62||Z(b)){const ce=b===47,Se=a.toLowerCase();return!ce&&!i&&Wr.includes(Se)?(s=1,r.interrupt?t(b):O(b)):sd.includes(a.toLowerCase())?(s=6,ce?(e.consume(b),g):r.interrupt?t(b):O(b)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(b):i?k(b):w(b))}return b===45||he(b)?(e.consume(b),a+=String.fromCharCode(b),S):n(b)}function g(b){return b===62?(e.consume(b),r.interrupt?t:O):n(b)}function k(b){return V(b)?(e.consume(b),k):C(b)}function w(b){return b===47?(e.consume(b),C):b===58||b===95||ge(b)?(e.consume(b),E):V(b)?(e.consume(b),w):C(b)}function E(b){return b===45||b===46||b===58||b===95||he(b)?(e.consume(b),E):M(b)}function M(b){return b===61?(e.consume(b),I):V(b)?(e.consume(b),M):w(b)}function I(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),u=b,P):V(b)?(e.consume(b),I):D(b)}function P(b){return b===u?(e.consume(b),u=null,F):b===null||B(b)?n(b):(e.consume(b),P)}function D(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||Z(b)?M(b):(e.consume(b),D)}function F(b){return b===47||b===62||V(b)?w(b):n(b)}function C(b){return b===62?(e.consume(b),_):n(b)}function _(b){return b===null||B(b)?O(b):V(b)?(e.consume(b),_):n(b)}function O(b){return b===45&&s===2?(e.consume(b),q):b===60&&s===1?(e.consume(b),Y):b===62&&s===4?(e.consume(b),ue):b===63&&s===3?(e.consume(b),x):b===93&&s===5?(e.consume(b),me):B(b)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(ad,se,G)(b)):b===null||B(b)?(e.exit("htmlFlowData"),G(b)):(e.consume(b),O)}function G(b){return e.check(od,z,se)(b)}function z(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),N}function N(b){return b===null||B(b)?G(b):(e.enter("htmlFlowData"),O(b))}function q(b){return b===45?(e.consume(b),x):O(b)}function Y(b){return b===47?(e.consume(b),a="",le):O(b)}function le(b){if(b===62){const ce=a.toLowerCase();return Wr.includes(ce)?(e.consume(b),ue):O(b)}return ge(b)&&a.length<8?(e.consume(b),a+=String.fromCharCode(b),le):O(b)}function me(b){return b===93?(e.consume(b),x):O(b)}function x(b){return b===62?(e.consume(b),ue):b===45&&s===2?(e.consume(b),x):O(b)}function ue(b){return b===null||B(b)?(e.exit("htmlFlowData"),se(b)):(e.consume(b),ue)}function se(b){return e.exit("htmlFlow"),t(b)}}function cd(e,t,n){const r=this;return s;function s(a){return B(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):n(a)}function i(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}function dd(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Ct,t,n)}}const hd={name:"htmlText",tokenize:fd};function fd(e,t,n){const r=this;let s,i,a;return o;function o(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),u}function u(x){return x===33?(e.consume(x),l):x===47?(e.consume(x),M):x===63?(e.consume(x),w):ge(x)?(e.consume(x),D):n(x)}function l(x){return x===45?(e.consume(x),c):x===91?(e.consume(x),i=0,y):ge(x)?(e.consume(x),k):n(x)}function c(x){return x===45?(e.consume(x),f):n(x)}function d(x){return x===null?n(x):x===45?(e.consume(x),p):B(x)?(a=d,Y(x)):(e.consume(x),d)}function p(x){return x===45?(e.consume(x),f):d(x)}function f(x){return x===62?q(x):x===45?p(x):d(x)}function y(x){const ue="CDATA[";return x===ue.charCodeAt(i++)?(e.consume(x),i===ue.length?m:y):n(x)}function m(x){return x===null?n(x):x===93?(e.consume(x),S):B(x)?(a=m,Y(x)):(e.consume(x),m)}function S(x){return x===93?(e.consume(x),g):m(x)}function g(x){return x===62?q(x):x===93?(e.consume(x),g):m(x)}function k(x){return x===null||x===62?q(x):B(x)?(a=k,Y(x)):(e.consume(x),k)}function w(x){return x===null?n(x):x===63?(e.consume(x),E):B(x)?(a=w,Y(x)):(e.consume(x),w)}function E(x){return x===62?q(x):w(x)}function M(x){return ge(x)?(e.consume(x),I):n(x)}function I(x){return x===45||he(x)?(e.consume(x),I):P(x)}function P(x){return B(x)?(a=P,Y(x)):V(x)?(e.consume(x),P):q(x)}function D(x){return x===45||he(x)?(e.consume(x),D):x===47||x===62||Z(x)?F(x):n(x)}function F(x){return x===47?(e.consume(x),q):x===58||x===95||ge(x)?(e.consume(x),C):B(x)?(a=F,Y(x)):V(x)?(e.consume(x),F):q(x)}function C(x){return x===45||x===46||x===58||x===95||he(x)?(e.consume(x),C):_(x)}function _(x){return x===61?(e.consume(x),O):B(x)?(a=_,Y(x)):V(x)?(e.consume(x),_):F(x)}function O(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),s=x,G):B(x)?(a=O,Y(x)):V(x)?(e.consume(x),O):(e.consume(x),z)}function G(x){return x===s?(e.consume(x),s=void 0,N):x===null?n(x):B(x)?(a=G,Y(x)):(e.consume(x),G)}function z(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||Z(x)?F(x):(e.consume(x),z)}function N(x){return x===47||x===62||Z(x)?F(x):n(x)}function q(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function Y(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),le}function le(x){return V(x)?X(e,me,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):me(x)}function me(x){return e.enter("htmlTextData"),a(x)}}const ur={name:"labelEnd",resolveAll:yd,resolveTo:xd,tokenize:bd},pd={tokenize:Sd},gd={tokenize:kd},md={tokenize:wd};function yd(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const s=r.type==="labelImage"?4:2;r.type="data",t+=s}}return e.length!==n.length&&ve(e,0,e.length,n),e}function xd(e,t){let n=e.length,r=0,s,i,a,o;for(;n--;)if(s=e[n][1],i){if(s.type==="link"||s.type==="labelLink"&&s._inactive)break;e[n][0]==="enter"&&s.type==="labelLink"&&(s._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(s.type==="labelImage"||s.type==="labelLink")&&!s._balanced&&(i=n,s.type!=="labelLink")){r=2;break}}else s.type==="labelEnd"&&(a=n);const u={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},l={type:"label",start:{...e[i][1].start},end:{...e[a][1].end}},c={type:"labelText",start:{...e[i+r+2][1].end},end:{...e[a-2][1].start}};return o=[["enter",u,t],["enter",l,t]],o=Re(o,e.slice(i+1,i+r+3)),o=Re(o,[["enter",c,t]]),o=Re(o,qt(t.parser.constructs.insideSpan.null,e.slice(i+r+4,a-3),t)),o=Re(o,[["exit",c,t],e[a-2],e[a-1],["exit",l,t]]),o=Re(o,e.slice(a+1)),o=Re(o,[["exit",u,t]]),ve(e,i,e.length,o),e}function bd(e,t,n){const r=this;let s=r.events.length,i,a;for(;s--;)if((r.events[s][1].type==="labelImage"||r.events[s][1].type==="labelLink")&&!r.events[s][1]._balanced){i=r.events[s][1];break}return o;function o(p){return i?i._inactive?d(p):(a=r.parser.defined.includes(Ne(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),u):n(p)}function u(p){return p===40?e.attempt(pd,c,a?c:d)(p):p===91?e.attempt(gd,c,a?l:d)(p):a?c(p):d(p)}function l(p){return e.attempt(md,c,d)(p)}function c(p){return t(p)}function d(p){return i._balanced=!0,n(p)}}function Sd(e,t,n){return r;function r(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),s}function s(d){return Z(d)?yt(e,i)(d):i(d)}function i(d){return d===41?c(d):Gi(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return Z(d)?yt(e,u)(d):c(d)}function o(d){return n(d)}function u(d){return d===34||d===39||d===40?Xi(e,l,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function l(d){return Z(d)?yt(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):n(d)}}function kd(e,t,n){const r=this;return s;function s(o){return Qi.call(r,e,i,a,"reference","referenceMarker","referenceString")(o)}function i(o){return r.parser.defined.includes(Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function a(o){return n(o)}}function wd(e,t,n){return r;function r(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),s}function s(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const vd={name:"labelStartImage",resolveAll:ur.resolveAll,tokenize:Cd};function Cd(e,t,n){const r=this;return s;function s(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):n(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const Id={name:"labelStartLink",resolveAll:ur.resolveAll,tokenize:Td};function Td(e,t,n){const r=this;return s;function s(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),i}function i(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const rn={name:"lineEnding",tokenize:Rd};function Rd(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),X(e,t,"linePrefix")}}const jt={name:"thematicBreak",tokenize:Md};function Md(e,t,n){let r=0,s;return i;function i(l){return e.enter("thematicBreak"),a(l)}function a(l){return s=l,o(l)}function o(l){return l===s?(e.enter("thematicBreakSequence"),u(l)):r>=3&&(l===null||B(l))?(e.exit("thematicBreak"),t(l)):n(l)}function u(l){return l===s?(e.consume(l),r++,u):(e.exit("thematicBreakSequence"),V(l)?X(e,o,"whitespace")(l):o(l))}}const xe={continuation:{tokenize:Nd},exit:jd,name:"list",tokenize:Ld},Ad={partial:!0,tokenize:Dd},Ed={partial:!0,tokenize:Pd};function Ld(e,t,n){const r=this,s=r.events[r.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,a=0;return o;function o(f){const y=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:jn(f)){if(r.containerState.type||(r.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(jt,n,l)(f):l(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(f)}return n(f)}function u(f){return jn(f)&&++a<10?(e.consume(f),u):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),l(f)):n(f)}function l(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(Ct,r.interrupt?n:c,e.attempt(Ad,p,d))}function c(f){return r.containerState.initialBlankLine=!0,i++,p(f)}function d(f){return V(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),p):n(f)}function p(f){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Nd(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Ct,s,i);function s(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!V(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Ed,t,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(xe,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Pd(e,t,n){const r=this;return X(e,s,"listItemIndent",r.containerState.size+1);function s(i){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?t(i):n(i)}}function jd(e){e.exit(this.containerState.type)}function Dd(e,t,n){const r=this;return X(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const a=r.events[r.events.length-1];return!V(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Gr={name:"setextUnderline",resolveTo:_d,tokenize:Od};function _d(e,t){let n=e.length,r,s,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(s=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const a={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",a,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=a,e.push(["exit",a,t]),e}function Od(e,t,n){const r=this;let s;return i;function i(l){let c=r.events.length,d;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){d=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),s=l,a(l)):n(l)}function a(l){return e.enter("setextHeadingLineSequence"),o(l)}function o(l){return l===s?(e.consume(l),o):(e.exit("setextHeadingLineSequence"),V(l)?X(e,u,"lineSuffix")(l):u(l))}function u(l){return l===null||B(l)?(e.exit("setextHeadingLine"),t(l)):n(l)}}const zd={tokenize:Fd};function Fd(e){const t=this,n=e.attempt(Ct,r,e.attempt(this.parser.constructs.flowInitial,s,X(e,e.attempt(this.parser.constructs.flow,s,e.attempt(Kc,s)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Bd={resolveAll:Ji()},$d=Yi("string"),Ud=Yi("text");function Yi(e){return{resolveAll:Ji(e==="text"?Hd:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,a,o);return a;function a(c){return l(c)?i(c):o(c)}function o(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),u}function u(c){return l(c)?(n.exit("data"),i(c)):(n.consume(c),u)}function l(c){if(c===null)return!0;const d=s[c];let p=-1;if(d)for(;++p<d.length;){const f=d[p];if(!f.previous||f.previous.call(r,r.previous))return!0}return!1}}}function Ji(e){return t;function t(n,r){let s=-1,i;for(;++s<=n.length;)i===void 0?n[s]&&n[s][1].type==="data"&&(i=s,s++):(!n[s]||n[s][1].type!=="data")&&(s!==i+2&&(n[i][1].end=n[s-1][1].end,n.splice(i+2,s-i-2),s=i+2),i=void 0);return e?e(n,r):n}}function Hd(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],s=t.sliceStream(r);let i=s.length,a=-1,o=0,u;for(;i--;){const l=s[i];if(typeof l=="string"){for(a=l.length;l.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(l===-2)u=!0,o++;else if(l!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(o=0),o){const l={type:n===e.length||u||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?a:r.start._bufferIndex+a,_index:r.start._index+i,line:r.end.line,column:r.end.column-o,offset:r.end.offset-o},end:{...r.end}};r.end={...l.start},r.start.offset===r.end.offset?Object.assign(r,l):(e.splice(n,0,["enter",l,t],["exit",l,t]),n+=2)}n++}return e}const Kd={42:xe,43:xe,45:xe,48:xe,49:xe,50:xe,51:xe,52:xe,53:xe,54:xe,55:xe,56:xe,57:xe,62:Ki},Vd={91:Qc},qd={[-2]:nn,[-1]:nn,32:nn},Wd={35:td,42:jt,45:[Gr,jt],60:id,61:Gr,95:jt,96:qr,126:qr},Gd={38:qi,92:Vi},Qd={[-5]:rn,[-4]:rn,[-3]:rn,33:vd,38:qi,42:Dn,60:[Ic,hd],91:Id,92:[Zc,Vi],93:ur,95:Dn,96:zc},Xd={null:[Dn,Bd]},Yd={null:[42,95]},Jd={null:[]},Zd=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Yd,contentInitial:Vd,disable:Jd,document:Kd,flow:Wd,flowInitial:qd,insideSpan:Xd,string:Gd,text:Qd},Symbol.toStringTag,{value:"Module"}));function eh(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const s={},i=[];let a=[],o=[];const u={attempt:P(M),check:P(I),consume:k,enter:w,exit:E,interrupt:P(I,{interrupt:!0})},l={code:null,containerState:{},defineSkip:m,events:[],now:y,parser:e,previous:null,sliceSerialize:p,sliceStream:f,write:d};let c=t.tokenize.call(l,u);return t.resolveAll&&i.push(t),l;function d(_){return a=Re(a,_),S(),a[a.length-1]!==null?[]:(D(t,0),l.events=qt(i,l.events,l),l.events)}function p(_,O){return nh(f(_),O)}function f(_){return th(a,_)}function y(){const{_bufferIndex:_,_index:O,line:G,column:z,offset:N}=r;return{_bufferIndex:_,_index:O,line:G,column:z,offset:N}}function m(_){s[_.line]=_.column,C()}function S(){let _;for(;r._index<a.length;){const O=a[r._index];if(typeof O=="string")for(_=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===_&&r._bufferIndex<O.length;)g(O.charCodeAt(r._bufferIndex));else g(O)}}function g(_){c=c(_)}function k(_){B(_)?(r.line++,r.column=1,r.offset+=_===-3?2:1,C()):_!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===a[r._index].length&&(r._bufferIndex=-1,r._index++)),l.previous=_}function w(_,O){const G=O||{};return G.type=_,G.start=y(),l.events.push(["enter",G,l]),o.push(G),G}function E(_){const O=o.pop();return O.end=y(),l.events.push(["exit",O,l]),O}function M(_,O){D(_,O.from)}function I(_,O){O.restore()}function P(_,O){return G;function G(z,N,q){let Y,le,me,x;return Array.isArray(z)?se(z):"tokenize"in z?se([z]):ue(z);function ue(ne){return Ce;function Ce(ye){const Ie=ye!==null&&ne[ye],Te=ye!==null&&ne.null,Pe=[...Array.isArray(Ie)?Ie:Ie?[Ie]:[],...Array.isArray(Te)?Te:Te?[Te]:[]];return se(Pe)(ye)}}function se(ne){return Y=ne,le=0,ne.length===0?q:b(ne[le])}function b(ne){return Ce;function Ce(ye){return x=F(),me=ne,ne.partial||(l.currentConstruct=ne),ne.name&&l.parser.constructs.disable.null.includes(ne.name)?Se():ne.tokenize.call(O?Object.assign(Object.create(l),O):l,u,ce,Se)(ye)}}function ce(ne){return _(me,x),N}function Se(ne){return x.restore(),++le<Y.length?b(Y[le]):q}}}function D(_,O){_.resolveAll&&!i.includes(_)&&i.push(_),_.resolve&&ve(l.events,O,l.events.length-O,_.resolve(l.events.slice(O),l)),_.resolveTo&&(l.events=_.resolveTo(l.events,l))}function F(){const _=y(),O=l.previous,G=l.currentConstruct,z=l.events.length,N=Array.from(o);return{from:z,restore:q};function q(){r=_,l.previous=O,l.currentConstruct=G,l.events.length=z,o=N,C()}}function C(){r.line in s&&r.column<2&&(r.column=s[r.line],r.offset+=s[r.line]-1)}}function th(e,t){const n=t.start._index,r=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let a;if(n===s)a=[e[n].slice(r,i)];else{if(a=e.slice(n,s),r>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}i>0&&a.push(e[s].slice(0,i))}return a}function nh(e,t){let n=-1;const r=[];let s;for(;++n<e.length;){const i=e[n];let a;if(typeof i=="string")a=i;else switch(i){case-5:{a="\r";break}case-4:{a=`
|
|
3
|
-
`;break}case-3:{a=`\r
|
|
4
|
-
`;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&s)continue;a=" ";break}default:a=String.fromCharCode(i)}s=i===-2,r.push(a)}return r.join("")}function rh(e){const r={constructs:Ui([Zd,...(e||{}).extensions||[]]),content:s(xc),defined:[],document:s(Sc),flow:s(zd),lazy:{},string:s($d),text:s(Ud)};return r;function s(i){return a;function a(o){return eh(r,i,o)}}}function sh(e){for(;!Wi(e););return e}const Qr=/[\0\t\n\r]/g;function ih(){let e=1,t="",n=!0,r;return s;function s(i,a,o){const u=[];let l,c,d,p,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(a||void 0).decode(i)),d=0,t="",n&&(i.charCodeAt(0)===65279&&d++,n=void 0);d<i.length;){if(Qr.lastIndex=d,l=Qr.exec(i),p=l&&l.index!==void 0?l.index:i.length,f=i.charCodeAt(p),!l){t=i.slice(d);break}if(f===10&&d===p&&r)u.push(-3),r=void 0;else switch(r&&(u.push(-5),r=void 0),d<p&&(u.push(i.slice(d,p)),e+=p-d),f){case 0:{u.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,u.push(-2);e++<c;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:r=!0,e=1}d=p+1}return o&&(r&&u.push(-5),t&&u.push(t),u.push(null)),u}}const ah=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function oh(e){return e.replace(ah,lh)}function lh(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const s=n.charCodeAt(1),i=s===120||s===88;return Hi(n.slice(i?2:1),i?16:10)}return lr(n)||e}const Zi={}.hasOwnProperty;function uh(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),ch(n)(sh(rh(n).document().write(ih()(e,t,!0))))}function ch(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(kr),autolinkProtocol:F,autolinkEmail:F,atxHeading:i(ze),blockQuote:i(Te),characterEscape:F,characterReference:F,codeFenced:i(Pe),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(Pe,a),codeText:i($,a),codeTextData:F,data:F,codeFlowValue:F,definition:i(pe),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(Me),hardBreakEscape:i(Ge),hardBreakTrailing:i(Ge),htmlFlow:i(Sr,a),htmlFlowData:F,htmlText:i(Sr,a),htmlTextData:F,image:i(Ya),label:a,link:i(kr),listItem:i(Ja),listItemValue:p,listOrdered:i(wr,d),listUnordered:i(wr),paragraph:i(Za),reference:b,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(ze),strong:i(eo),thematicBreak:i(no)},exit:{atxHeading:u(),atxHeadingSequence:M,autolink:u(),autolinkEmail:Ie,autolinkProtocol:ye,blockQuote:u(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:Se,characterReferenceMarkerNumeric:Se,characterReferenceValue:ne,characterReference:Ce,codeFenced:u(S),codeFencedFence:m,codeFencedFenceInfo:f,codeFencedFenceMeta:y,codeFlowValue:C,codeIndented:u(g),codeText:u(N),codeTextData:C,data:C,definition:u(),definitionDestinationString:E,definitionLabelString:k,definitionTitleString:w,emphasis:u(),hardBreakEscape:u(O),hardBreakTrailing:u(O),htmlFlow:u(G),htmlFlowData:C,htmlText:u(z),htmlTextData:C,image:u(Y),label:me,labelText:le,lineEnding:_,link:u(q),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:ce,resourceDestinationString:x,resourceTitleString:ue,resource:se,setextHeading:u(D),setextHeadingLineSequence:P,setextHeadingText:I,strong:u(),thematicBreak:u()}};ea(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(T){let L={type:"root",children:[]};const U={stack:[L],tokenStack:[],config:t,enter:o,exit:l,buffer:a,resume:c,data:n},Q=[];let J=-1;for(;++J<T.length;)if(T[J][1].type==="listOrdered"||T[J][1].type==="listUnordered")if(T[J][0]==="enter")Q.push(J);else{const Ae=Q.pop();J=s(T,Ae,J)}for(J=-1;++J<T.length;){const Ae=t[T[J][0]];Zi.call(Ae,T[J][1].type)&&Ae[T[J][1].type].call(Object.assign({sliceSerialize:T[J][2].sliceSerialize},U),T[J][1])}if(U.tokenStack.length>0){const Ae=U.tokenStack[U.tokenStack.length-1];(Ae[1]||Xr).call(U,void 0,Ae[0])}for(L.position={start:Ve(T.length>0?T[0][1].start:{line:1,column:1,offset:0}),end:Ve(T.length>0?T[T.length-2][1].end:{line:1,column:1,offset:0})},J=-1;++J<t.transforms.length;)L=t.transforms[J](L)||L;return L}function s(T,L,U){let Q=L-1,J=-1,Ae=!1,Qe,Fe,ut,ct;for(;++Q<=U;){const ke=T[Q];switch(ke[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ke[0]==="enter"?J++:J--,ct=void 0;break}case"lineEndingBlank":{ke[0]==="enter"&&(Qe&&!ct&&!J&&!ut&&(ut=Q),ct=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ct=void 0}if(!J&&ke[0]==="enter"&&ke[1].type==="listItemPrefix"||J===-1&&ke[0]==="exit"&&(ke[1].type==="listUnordered"||ke[1].type==="listOrdered")){if(Qe){let Ze=Q;for(Fe=void 0;Ze--;){const Be=T[Ze];if(Be[1].type==="lineEnding"||Be[1].type==="lineEndingBlank"){if(Be[0]==="exit")continue;Fe&&(T[Fe][1].type="lineEndingBlank",Ae=!0),Be[1].type="lineEnding",Fe=Ze}else if(!(Be[1].type==="linePrefix"||Be[1].type==="blockQuotePrefix"||Be[1].type==="blockQuotePrefixWhitespace"||Be[1].type==="blockQuoteMarker"||Be[1].type==="listItemIndent"))break}ut&&(!Fe||ut<Fe)&&(Qe._spread=!0),Qe.end=Object.assign({},Fe?T[Fe][1].start:ke[1].end),T.splice(Fe||Q,0,["exit",Qe,ke[2]]),Q++,U++}if(ke[1].type==="listItemPrefix"){const Ze={type:"listItem",_spread:!1,start:Object.assign({},ke[1].start),end:void 0};Qe=Ze,T.splice(Q,0,["enter",Ze,ke[2]]),Q++,U++,ut=void 0,ct=!0}}}return T[L][1]._spread=Ae,U}function i(T,L){return U;function U(Q){o.call(this,T(Q),Q),L&&L.call(this,Q)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(T,L,U){this.stack[this.stack.length-1].children.push(T),this.stack.push(T),this.tokenStack.push([L,U||void 0]),T.position={start:Ve(L.start),end:void 0}}function u(T){return L;function L(U){T&&T.call(this,U),l.call(this,U)}}function l(T,L){const U=this.stack.pop(),Q=this.tokenStack.pop();if(Q)Q[0].type!==T.type&&(L?L.call(this,T,Q[0]):(Q[1]||Xr).call(this,T,Q[0]));else throw new Error("Cannot close `"+T.type+"` ("+mt({start:T.start,end:T.end})+"): it’s not open");U.position.end=Ve(T.end)}function c(){return or(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function p(T){if(this.data.expectingFirstListItemValue){const L=this.stack[this.stack.length-2];L.start=Number.parseInt(this.sliceSerialize(T),10),this.data.expectingFirstListItemValue=void 0}}function f(){const T=this.resume(),L=this.stack[this.stack.length-1];L.lang=T}function y(){const T=this.resume(),L=this.stack[this.stack.length-1];L.meta=T}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function S(){const T=this.resume(),L=this.stack[this.stack.length-1];L.value=T.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){const T=this.resume(),L=this.stack[this.stack.length-1];L.value=T.replace(/(\r?\n|\r)$/g,"")}function k(T){const L=this.resume(),U=this.stack[this.stack.length-1];U.label=L,U.identifier=Ne(this.sliceSerialize(T)).toLowerCase()}function w(){const T=this.resume(),L=this.stack[this.stack.length-1];L.title=T}function E(){const T=this.resume(),L=this.stack[this.stack.length-1];L.url=T}function M(T){const L=this.stack[this.stack.length-1];if(!L.depth){const U=this.sliceSerialize(T).length;L.depth=U}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function P(T){const L=this.stack[this.stack.length-1];L.depth=this.sliceSerialize(T).codePointAt(0)===61?1:2}function D(){this.data.setextHeadingSlurpLineEnding=void 0}function F(T){const U=this.stack[this.stack.length-1].children;let Q=U[U.length-1];(!Q||Q.type!=="text")&&(Q=to(),Q.position={start:Ve(T.start),end:void 0},U.push(Q)),this.stack.push(Q)}function C(T){const L=this.stack.pop();L.value+=this.sliceSerialize(T),L.position.end=Ve(T.end)}function _(T){const L=this.stack[this.stack.length-1];if(this.data.atHardBreak){const U=L.children[L.children.length-1];U.position.end=Ve(T.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(L.type)&&(F.call(this,T),C.call(this,T))}function O(){this.data.atHardBreak=!0}function G(){const T=this.resume(),L=this.stack[this.stack.length-1];L.value=T}function z(){const T=this.resume(),L=this.stack[this.stack.length-1];L.value=T}function N(){const T=this.resume(),L=this.stack[this.stack.length-1];L.value=T}function q(){const T=this.stack[this.stack.length-1];if(this.data.inReference){const L=this.data.referenceType||"shortcut";T.type+="Reference",T.referenceType=L,delete T.url,delete T.title}else delete T.identifier,delete T.label;this.data.referenceType=void 0}function Y(){const T=this.stack[this.stack.length-1];if(this.data.inReference){const L=this.data.referenceType||"shortcut";T.type+="Reference",T.referenceType=L,delete T.url,delete T.title}else delete T.identifier,delete T.label;this.data.referenceType=void 0}function le(T){const L=this.sliceSerialize(T),U=this.stack[this.stack.length-2];U.label=oh(L),U.identifier=Ne(L).toLowerCase()}function me(){const T=this.stack[this.stack.length-1],L=this.resume(),U=this.stack[this.stack.length-1];if(this.data.inReference=!0,U.type==="link"){const Q=T.children;U.children=Q}else U.alt=L}function x(){const T=this.resume(),L=this.stack[this.stack.length-1];L.url=T}function ue(){const T=this.resume(),L=this.stack[this.stack.length-1];L.title=T}function se(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function ce(T){const L=this.resume(),U=this.stack[this.stack.length-1];U.label=L,U.identifier=Ne(this.sliceSerialize(T)).toLowerCase(),this.data.referenceType="full"}function Se(T){this.data.characterReferenceType=T.type}function ne(T){const L=this.sliceSerialize(T),U=this.data.characterReferenceType;let Q;U?(Q=Hi(L,U==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Q=lr(L);const J=this.stack[this.stack.length-1];J.value+=Q}function Ce(T){const L=this.stack.pop();L.position.end=Ve(T.end)}function ye(T){C.call(this,T);const L=this.stack[this.stack.length-1];L.url=this.sliceSerialize(T)}function Ie(T){C.call(this,T);const L=this.stack[this.stack.length-1];L.url="mailto:"+this.sliceSerialize(T)}function Te(){return{type:"blockquote",children:[]}}function Pe(){return{type:"code",lang:null,meta:null,value:""}}function $(){return{type:"inlineCode",value:""}}function pe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Me(){return{type:"emphasis",children:[]}}function ze(){return{type:"heading",depth:0,children:[]}}function Ge(){return{type:"break"}}function Sr(){return{type:"html",value:""}}function Ya(){return{type:"image",title:null,url:"",alt:null}}function kr(){return{type:"link",title:null,url:"",children:[]}}function wr(T){return{type:"list",ordered:T.type==="listOrdered",start:null,spread:T._spread,children:[]}}function Ja(T){return{type:"listItem",spread:T._spread,checked:null,children:[]}}function Za(){return{type:"paragraph",children:[]}}function eo(){return{type:"strong",children:[]}}function to(){return{type:"text",value:""}}function no(){return{type:"thematicBreak"}}}function Ve(e){return{line:e.line,column:e.column,offset:e.offset}}function ea(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?ea(e,r):dh(e,r)}}function dh(e,t){let n;for(n in t)if(Zi.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function Xr(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+mt({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+mt({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+mt({start:t.start,end:t.end})+") is still open")}function hh(e){const t=this;t.parser=n;function n(r){return uh(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function fh(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function ph(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
5
|
-
`}]}function gh(e,t){const n=t.value?t.value+`
|
|
6
|
-
`:"",r={},s=t.lang?t.lang.split(/\s+/):[];s.length>0&&(r.className=["language-"+s[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function mh(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yh(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function xh(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),s=lt(r.toLowerCase()),i=e.footnoteOrder.indexOf(r);let a,o=e.footnoteCounts.get(r);o===void 0?(o=0,e.footnoteOrder.push(r),a=e.footnoteOrder.length):a=i+1,o+=1,e.footnoteCounts.set(r,o);const u={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+s,id:n+"fnref-"+s+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,u);const l={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(t,l),e.applyData(t,l)}function bh(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Sh(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function ta(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const s=e.all(t),i=s[0];i&&i.type==="text"?i.value="["+i.value:s.unshift({type:"text",value:"["});const a=s[s.length-1];return a&&a.type==="text"?a.value+=r:s.push({type:"text",value:r}),s}function kh(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return ta(e,t);const s={src:lt(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(t,i),e.applyData(t,i)}function wh(e,t){const n={src:lt(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function vh(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function Ch(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return ta(e,t);const s={href:lt(r.url||"")};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"a",properties:s,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Ih(e,t){const n={href:lt(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Th(e,t,n){const r=e.all(t),s=n?Rh(n):na(t),i={},a=[];if(typeof t.checked=="boolean"){const c=r[0];let d;c&&c.type==="element"&&c.tagName==="p"?d=c:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<r.length;){const c=r[o];(s||o!==0||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
|
|
7
|
-
`}),c.type==="element"&&c.tagName==="p"&&!s?a.push(...c.children):a.push(c)}const u=r[r.length-1];u&&(s||u.type!=="element"||u.tagName!=="p")&&a.push({type:"text",value:`
|
|
8
|
-
`});const l={type:"element",tagName:"li",properties:i,children:a};return e.patch(t,l),e.applyData(t,l)}function Rh(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=na(n[r])}return t}function na(e){const t=e.spread;return t??e.children.length>1}function Mh(e,t){const n={},r=e.all(t);let s=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++s<r.length;){const a=r[s];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)}function Ah(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Eh(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function Lh(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Nh(e,t){const n=e.all(t),r=n.shift(),s=[];if(r){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],a),s.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},o=rr(t.children[1]),u=Di(t.children[t.children.length-1]);o&&u&&(a.position={start:o,end:u}),s.push(a)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function Ph(e,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,o=a?a.length:t.children.length;let u=-1;const l=[];for(;++u<o;){const d=t.children[u],p={},f=a?a[u]:void 0;f&&(p.align=f);let y={type:"element",tagName:i,properties:p,children:[]};d&&(y.children=e.all(d),e.patch(d,y),y=e.applyData(d,y)),l.push(y)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(l,!0)};return e.patch(t,c),e.applyData(t,c)}function jh(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Yr=9,Jr=32;function Dh(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),s=0;const i=[];for(;r;)i.push(Zr(t.slice(s,r.index),s>0,!0),r[0]),s=r.index+r[0].length,r=n.exec(t);return i.push(Zr(t.slice(s),s>0,!1)),i.join("")}function Zr(e,t,n){let r=0,s=e.length;if(t){let i=e.codePointAt(r);for(;i===Yr||i===Jr;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(s-1);for(;i===Yr||i===Jr;)s--,i=e.codePointAt(s-1)}return s>r?e.slice(r,s):""}function _h(e,t){const n={type:"text",value:Dh(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Oh(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const zh={blockquote:fh,break:ph,code:gh,delete:mh,emphasis:yh,footnoteReference:xh,heading:bh,html:Sh,imageReference:kh,image:wh,inlineCode:vh,linkReference:Ch,link:Ih,listItem:Th,list:Mh,paragraph:Ah,root:Eh,strong:Lh,table:Nh,tableCell:jh,tableRow:Ph,text:_h,thematicBreak:Oh,toml:Tt,yaml:Tt,definition:Tt,footnoteDefinition:Tt};function Tt(){}const ra=-1,Wt=0,xt=1,Ft=2,cr=3,dr=4,hr=5,fr=6,sa=7,ia=8,es=typeof self=="object"?self:globalThis,Fh=(e,t)=>{const n=(s,i)=>(e.set(i,s),s),r=s=>{if(e.has(s))return e.get(s);const[i,a]=t[s];switch(i){case Wt:case ra:return n(a,s);case xt:{const o=n([],s);for(const u of a)o.push(r(u));return o}case Ft:{const o=n({},s);for(const[u,l]of a)o[r(u)]=r(l);return o}case cr:return n(new Date(a),s);case dr:{const{source:o,flags:u}=a;return n(new RegExp(o,u),s)}case hr:{const o=n(new Map,s);for(const[u,l]of a)o.set(r(u),r(l));return o}case fr:{const o=n(new Set,s);for(const u of a)o.add(r(u));return o}case sa:{const{name:o,message:u}=a;return n(new es[o](u),s)}case ia:return n(BigInt(a),s);case"BigInt":return n(Object(BigInt(a)),s);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:o}=new Uint8Array(a);return n(new DataView(o),a)}}return n(new es[i](a),s)};return r},ts=e=>Fh(new Map,e)(0),tt="",{toString:Bh}={},{keys:$h}=Object,pt=e=>{const t=typeof e;if(t!=="object"||!e)return[Wt,t];const n=Bh.call(e).slice(8,-1);switch(n){case"Array":return[xt,tt];case"Object":return[Ft,tt];case"Date":return[cr,tt];case"RegExp":return[dr,tt];case"Map":return[hr,tt];case"Set":return[fr,tt];case"DataView":return[xt,n]}return n.includes("Array")?[xt,n]:n.includes("Error")?[sa,n]:[Ft,n]},Rt=([e,t])=>e===Wt&&(t==="function"||t==="symbol"),Uh=(e,t,n,r)=>{const s=(a,o)=>{const u=r.push(a)-1;return n.set(o,u),u},i=a=>{if(n.has(a))return n.get(a);let[o,u]=pt(a);switch(o){case Wt:{let c=a;switch(u){case"bigint":o=ia,c=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);c=null;break;case"undefined":return s([ra],a)}return s([o,c],a)}case xt:{if(u){let p=a;return u==="DataView"?p=new Uint8Array(a.buffer):u==="ArrayBuffer"&&(p=new Uint8Array(a)),s([u,[...p]],a)}const c=[],d=s([o,c],a);for(const p of a)c.push(i(p));return d}case Ft:{if(u)switch(u){case"BigInt":return s([u,a.toString()],a);case"Boolean":case"Number":case"String":return s([u,a.valueOf()],a)}if(t&&"toJSON"in a)return i(a.toJSON());const c=[],d=s([o,c],a);for(const p of $h(a))(e||!Rt(pt(a[p])))&&c.push([i(p),i(a[p])]);return d}case cr:return s([o,a.toISOString()],a);case dr:{const{source:c,flags:d}=a;return s([o,{source:c,flags:d}],a)}case hr:{const c=[],d=s([o,c],a);for(const[p,f]of a)(e||!(Rt(pt(p))||Rt(pt(f))))&&c.push([i(p),i(f)]);return d}case fr:{const c=[],d=s([o,c],a);for(const p of a)(e||!Rt(pt(p)))&&c.push(i(p));return d}}const{message:l}=a;return s([o,{name:u,message:l}],a)};return i},ns=(e,{json:t,lossy:n}={})=>{const r=[];return Uh(!(t||n),!!t,new Map,r)(e),r},Bt=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?ts(ns(e,t)):structuredClone(e):(e,t)=>ts(ns(e,t));function Hh(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function Kh(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Vh(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Hh,r=e.options.footnoteBackLabel||Kh,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let u=-1;for(;++u<e.footnoteOrder.length;){const l=e.footnoteById.get(e.footnoteOrder[u]);if(!l)continue;const c=e.all(l),d=String(l.identifier).toUpperCase(),p=lt(d.toLowerCase());let f=0;const y=[],m=e.footnoteCounts.get(d);for(;m!==void 0&&++f<=m;){y.length>0&&y.push({type:"text",value:" "});let k=typeof n=="string"?n:n(u,f);typeof k=="string"&&(k={type:"text",value:k}),y.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+p+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(u,f),className:["data-footnote-backref"]},children:Array.isArray(k)?k:[k]})}const S=c[c.length-1];if(S&&S.type==="element"&&S.tagName==="p"){const k=S.children[S.children.length-1];k&&k.type==="text"?k.value+=" ":S.children.push({type:"text",value:" "}),S.children.push(...y)}else c.push(...y);const g={type:"element",tagName:"li",properties:{id:t+"fn-"+p},children:e.wrap(c,!0)};e.patch(l,g),o.push(g)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Bt(a),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:`
|
|
9
|
-
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:`
|
|
10
|
-
`}]}}const Gt=(function(e){if(e==null)return Qh;if(typeof e=="function")return Qt(e);if(typeof e=="object")return Array.isArray(e)?qh(e):Wh(e);if(typeof e=="string")return Gh(e);throw new Error("Expected function, string, or object as test")});function qh(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Gt(e[n]);return Qt(r);function r(...s){let i=-1;for(;++i<t.length;)if(t[i].apply(this,s))return!0;return!1}}function Wh(e){const t=e;return Qt(n);function n(r){const s=r;let i;for(i in e)if(s[i]!==t[i])return!1;return!0}}function Gh(e){return Qt(t);function t(n){return n&&n.type===e}}function Qt(e){return t;function t(n,r,s){return!!(Xh(n)&&e.call(this,n,typeof r=="number"?r:void 0,s||void 0))}}function Qh(){return!0}function Xh(e){return e!==null&&typeof e=="object"&&"type"in e}const aa=[],Yh=!0,_n=!1,Jh="skip";function oa(e,t,n,r){let s;typeof t=="function"&&typeof n!="function"?(r=n,n=t):s=t;const i=Gt(s),a=r?-1:1;o(e,void 0,[])();function o(u,l,c){const d=u&&typeof u=="object"?u:{};if(typeof d.type=="string"){const f=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(u.type+(f?"<"+f+">":""))+")"})}return p;function p(){let f=aa,y,m,S;if((!t||i(u,l,c[c.length-1]||void 0))&&(f=Zh(n(u,c)),f[0]===_n))return f;if("children"in u&&u.children){const g=u;if(g.children&&f[0]!==Jh)for(m=(r?g.children.length:-1)+a,S=c.concat(g);m>-1&&m<g.children.length;){const k=g.children[m];if(y=o(k,m,S)(),y[0]===_n)return y;m=typeof y[1]=="number"?y[1]:m+a}}return f}}}function Zh(e){return Array.isArray(e)?e:typeof e=="number"?[Yh,e]:e==null?aa:[e]}function pr(e,t,n,r){let s,i,a;typeof t=="function"&&typeof n!="function"?(i=void 0,a=t,s=n):(i=t,a=n,s=r),oa(e,i,o,s);function o(u,l){const c=l[l.length-1],d=c?c.children.indexOf(u):void 0;return a(u,d,c)}}const On={}.hasOwnProperty,ef={};function tf(e,t){const n=t||ef,r=new Map,s=new Map,i=new Map,a={...zh,...n.handlers},o={all:l,applyData:rf,definitionById:r,footnoteById:s,footnoteCounts:i,footnoteOrder:[],handlers:a,one:u,options:n,patch:nf,wrap:af};return pr(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?r:s,p=String(c.identifier).toUpperCase();d.has(p)||d.set(p,c)}}),o;function u(c,d){const p=c.type,f=o.handlers[p];if(On.call(o.handlers,p)&&f)return f(o,c,d);if(o.options.passThrough&&o.options.passThrough.includes(p)){if("children"in c){const{children:m,...S}=c,g=Bt(S);return g.children=o.all(c),g}return Bt(c)}return(o.options.unknownHandler||sf)(o,c,d)}function l(c){const d=[];if("children"in c){const p=c.children;let f=-1;for(;++f<p.length;){const y=o.one(p[f],c);if(y){if(f&&p[f-1].type==="break"&&(!Array.isArray(y)&&y.type==="text"&&(y.value=rs(y.value)),!Array.isArray(y)&&y.type==="element")){const m=y.children[0];m&&m.type==="text"&&(m.value=rs(m.value))}Array.isArray(y)?d.push(...y):d.push(y)}}}return d}}function nf(e,t){e.position&&(t.position=Ku(e))}function rf(e,t){let n=t;if(e&&e.data){const r=e.data.hName,s=e.data.hChildren,i=e.data.hProperties;if(typeof r=="string")if(n.type==="element")n.tagName=r;else{const a="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:a}}n.type==="element"&&i&&Object.assign(n.properties,Bt(i)),"children"in n&&n.children&&s!==null&&s!==void 0&&(n.children=s)}return n}function sf(e,t){const n=t.data||{},r="value"in t&&!(On.call(n,"hProperties")||On.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function af(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:`
|
|
11
|
-
`});++r<e.length;)r&&n.push({type:"text",value:`
|
|
12
|
-
`}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
13
|
-
`}),n}function rs(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function ss(e,t){const n=tf(e,t),r=n.one(e,void 0),s=Vh(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return s&&i.children.push({type:"text",value:`
|
|
14
|
-
`},s),i}function of(e,t){return e&&"run"in e?async function(n,r){const s=ss(n,{file:r,...t});await e.run(s,r)}:function(n,r){return ss(n,{file:r,...e||t})}}function is(e){if(e)throw e}var sn,as;function lf(){if(as)return sn;as=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=function(l){return typeof Array.isArray=="function"?Array.isArray(l):t.call(l)==="[object Array]"},i=function(l){if(!l||t.call(l)!=="[object Object]")return!1;var c=e.call(l,"constructor"),d=l.constructor&&l.constructor.prototype&&e.call(l.constructor.prototype,"isPrototypeOf");if(l.constructor&&!c&&!d)return!1;var p;for(p in l);return typeof p>"u"||e.call(l,p)},a=function(l,c){n&&c.name==="__proto__"?n(l,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):l[c.name]=c.newValue},o=function(l,c){if(c==="__proto__")if(e.call(l,c)){if(r)return r(l,c).value}else return;return l[c]};return sn=function u(){var l,c,d,p,f,y,m=arguments[0],S=1,g=arguments.length,k=!1;for(typeof m=="boolean"&&(k=m,m=arguments[1]||{},S=2),(m==null||typeof m!="object"&&typeof m!="function")&&(m={});S<g;++S)if(l=arguments[S],l!=null)for(c in l)d=o(m,c),p=o(l,c),m!==p&&(k&&p&&(i(p)||(f=s(p)))?(f?(f=!1,y=d&&s(d)?d:[]):y=d&&i(d)?d:{},a(m,{name:c,newValue:u(k,y,p)})):typeof p<"u"&&a(m,{name:c,newValue:p}));return m},sn}var uf=lf();const an=ei(uf);function zn(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function cf(){const e=[],t={run:n,use:r};return t;function n(...s){let i=-1;const a=s.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);o(null,...s);function o(u,...l){const c=e[++i];let d=-1;if(u){a(u);return}for(;++d<s.length;)(l[d]===null||l[d]===void 0)&&(l[d]=s[d]);s=l,c?df(c,o)(...l):a(null,...l)}}function r(s){if(typeof s!="function")throw new TypeError("Expected `middelware` to be a function, not "+s);return e.push(s),t}}function df(e,t){let n;return r;function r(...a){const o=e.length>a.length;let u;o&&a.push(s);try{u=e.apply(this,a)}catch(l){const c=l;if(o&&n)throw c;return s(c)}o||(u&&u.then&&typeof u.then=="function"?u.then(i,s):u instanceof Error?s(u):i(u))}function s(a,...o){n||(n=!0,t(a,...o))}function i(a){s(null,a)}}const De={basename:hf,dirname:ff,extname:pf,join:gf,sep:"/"};function hf(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');It(e);let n=0,r=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else r<0&&(i=!0,r=s+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let a=-1,o=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else a<0&&(i=!0,a=s+1),o>-1&&(e.codePointAt(s)===t.codePointAt(o--)?o<0&&(r=s):(o=-1,r=a));return n===r?r=a:r<0&&(r=e.length),e.slice(n,r)}function ff(e){if(It(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function pf(e){It(e);let t=e.length,n=-1,r=0,s=-1,i=0,a;for(;t--;){const o=e.codePointAt(t);if(o===47){if(a){r=t+1;break}continue}n<0&&(a=!0,n=t+1),o===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||n<0||i===0||i===1&&s===n-1&&s===r+1?"":e.slice(s,n)}function gf(...e){let t=-1,n;for(;++t<e.length;)It(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":mf(n)}function mf(e){It(e);const t=e.codePointAt(0)===47;let n=yf(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function yf(e,t){let n="",r=0,s=-1,i=0,a=-1,o,u;for(;++a<=e.length;){if(a<e.length)o=e.codePointAt(a);else{if(o===47)break;o=47}if(o===47){if(!(s===a-1||i===1))if(s!==a-1&&i===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",r=0):(n=n.slice(0,u),r=n.length-1-n.lastIndexOf("/")),s=a,i=0;continue}}else if(n.length>0){n="",r=0,s=a,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,a):n=e.slice(s+1,a),r=a-s-1;s=a,i=0}else o===46&&i>-1?i++:i=-1}return n}function It(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const xf={cwd:bf};function bf(){return"/"}function Fn(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Sf(e){if(typeof e=="string")e=new URL(e);else if(!Fn(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return kf(e)}function kf(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const s=new TypeError("File URL path must not include encoded / characters");throw s.code="ERR_INVALID_FILE_URL_PATH",s}}return decodeURIComponent(t)}const on=["history","path","basename","stem","extname","dirname"];class la{constructor(t){let n;t?Fn(t)?n={path:t}:typeof t=="string"||wf(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":xf.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<on.length;){const i=on[r];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let s;for(s in n)on.includes(s)||(this[s]=n[s])}get basename(){return typeof this.path=="string"?De.basename(this.path):void 0}set basename(t){un(t,"basename"),ln(t,"basename"),this.path=De.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?De.dirname(this.path):void 0}set dirname(t){os(this.basename,"dirname"),this.path=De.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?De.extname(this.path):void 0}set extname(t){if(ln(t,"extname"),os(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=De.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Fn(t)&&(t=Sf(t)),un(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?De.basename(this.path,this.extname):void 0}set stem(t){un(t,"stem"),ln(t,"stem"),this.path=De.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const s=this.message(t,n,r);throw s.fatal=!0,s}info(t,n,r){const s=this.message(t,n,r);return s.fatal=void 0,s}message(t,n,r){const s=new fe(t,n,r);return this.path&&(s.name=this.path+":"+s.name,s.file=this.path),s.fatal=!1,this.messages.push(s),s}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function ln(e,t){if(e&&e.includes(De.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+De.sep+"`")}function un(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function os(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function wf(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const vf=(function(e){const r=this.constructor.prototype,s=r[e],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,r),i}),Cf={}.hasOwnProperty;class gr extends vf{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=cf()}copy(){const t=new gr;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(an(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(hn("data",this.frozen),this.namespace[t]=n,this):Cf.call(this.namespace,t)&&this.namespace[t]||void 0:t?(hn("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const s=n.call(t,...r);typeof s=="function"&&this.transformers.use(s)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=Mt(t),r=this.parser||this.Parser;return cn("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),cn("process",this.parser||this.Parser),dn("process",this.compiler||this.Compiler),n?s(void 0,n):new Promise(s);function s(i,a){const o=Mt(t),u=r.parse(o);r.run(u,o,function(c,d,p){if(c||!d||!p)return l(c);const f=d,y=r.stringify(f,p);Rf(y)?p.value=y:p.result=y,l(c,p)});function l(c,d){c||!d?a(c):i?i(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),cn("processSync",this.parser||this.Parser),dn("processSync",this.compiler||this.Compiler),this.process(t,s),us("processSync","process",n),r;function s(i,a){n=!0,is(i),r=a}}run(t,n,r){ls(t),this.freeze();const s=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?i(void 0,r):new Promise(i);function i(a,o){const u=Mt(n);s.run(t,u,l);function l(c,d,p){const f=d||t;c?o(c):a?a(f):r(void 0,f,p)}}}runSync(t,n){let r=!1,s;return this.run(t,n,i),us("runSync","run",r),s;function i(a,o){is(a),s=o,r=!0}}stringify(t,n){this.freeze();const r=Mt(n),s=this.compiler||this.Compiler;return dn("stringify",s),ls(t),s(t,r)}use(t,...n){const r=this.attachers,s=this.namespace;if(hn("use",this.frozen),t!=null)if(typeof t=="function")u(t,n);else if(typeof t=="object")Array.isArray(t)?o(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(l){if(typeof l=="function")u(l,[]);else if(typeof l=="object")if(Array.isArray(l)){const[c,...d]=l;u(c,d)}else a(l);else throw new TypeError("Expected usable value, not `"+l+"`")}function a(l){if(!("plugins"in l)&&!("settings"in l))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(l.plugins),l.settings&&(s.settings=an(!0,s.settings,l.settings))}function o(l){let c=-1;if(l!=null)if(Array.isArray(l))for(;++c<l.length;){const d=l[c];i(d)}else throw new TypeError("Expected a list of plugins, not `"+l+"`")}function u(l,c){let d=-1,p=-1;for(;++d<r.length;)if(r[d][0]===l){p=d;break}if(p===-1)r.push([l,...c]);else if(c.length>0){let[f,...y]=c;const m=r[p][1];zn(m)&&zn(f)&&(f=an(!0,m,f)),r[p]=[l,f,...y]}}}}const If=new gr().freeze();function cn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function dn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function hn(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function ls(e){if(!zn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function us(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Mt(e){return Tf(e)?e:new la(e)}function Tf(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Rf(e){return typeof e=="string"||Mf(e)}function Mf(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Af="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",cs=[],ds={allowDangerousHtml:!0},Ef=/^(https?|ircs?|mailto|xmpp)$/i,Lf=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Nf(e){const t=Pf(e),n=jf(e);return Df(t.runSync(t.parse(n),n),e)}function Pf(e){const t=e.rehypePlugins||cs,n=e.remarkPlugins||cs,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...ds}:ds;return If().use(hh).use(n).use(of,r).use(t)}function jf(e){const t=e.children||"",n=new la;return typeof t=="string"&&(n.value=t),n}function Df(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,a=t.skipHtml,o=t.unwrapDisallowed,u=t.urlTransform||_f;for(const c of Lf)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+Af+c.id,void 0);return pr(e,l),Qu(e,{Fragment:h.Fragment,components:s,ignoreInvalidStyle:!0,jsx:h.jsx,jsxs:h.jsxs,passKeys:!0,passNode:!0});function l(c,d,p){if(c.type==="raw"&&p&&typeof d=="number")return a?p.children.splice(d,1):p.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let f;for(f in tn)if(Object.hasOwn(tn,f)&&Object.hasOwn(c.properties,f)){const y=c.properties[f],m=tn[f];(m===null||m.includes(c.tagName))&&(c.properties[f]=u(String(y||""),f,c))}}if(c.type==="element"){let f=n?!n.includes(c.tagName):i?i.includes(c.tagName):!1;if(!f&&r&&typeof d=="number"&&(f=!r(c,d,p)),f&&p&&typeof d=="number")return o&&c.children?p.children.splice(d,1,...c.children):p.children.splice(d,1),d}}}function _f(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),s=e.indexOf("/");return t===-1||s!==-1&&t>s||n!==-1&&t>n||r!==-1&&t>r||Ef.test(e.slice(0,t))?e:""}function hs(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,s=n.indexOf(t);for(;s!==-1;)r++,s=n.indexOf(t,s+t.length);return r}function Of(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function zf(e,t,n){const s=Gt((n||{}).ignore||[]),i=Ff(t);let a=-1;for(;++a<i.length;)oa(e,"text",o);function o(l,c){let d=-1,p;for(;++d<c.length;){const f=c[d],y=p?p.children:void 0;if(s(f,y?y.indexOf(f):void 0,p))return;p=f}if(p)return u(l,c)}function u(l,c){const d=c[c.length-1],p=i[a][0],f=i[a][1];let y=0;const S=d.children.indexOf(l);let g=!1,k=[];p.lastIndex=0;let w=p.exec(l.value);for(;w;){const E=w.index,M={index:w.index,input:w.input,stack:[...c,l]};let I=f(...w,M);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?p.lastIndex=E+1:(y!==E&&k.push({type:"text",value:l.value.slice(y,E)}),Array.isArray(I)?k.push(...I):I&&k.push(I),y=E+w[0].length,g=!0),!p.global)break;w=p.exec(l.value)}return g?(y<l.value.length&&k.push({type:"text",value:l.value.slice(y)}),d.children.splice(S,1,...k)):k=[l],S+k.length}}function Ff(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const s=n[r];t.push([Bf(s[0]),$f(s[1])])}return t}function Bf(e){return typeof e=="string"?new RegExp(Of(e),"g"):e}function $f(e){return typeof e=="function"?e:function(){return e}}const fn="phrasing",pn=["autolink","link","image","label"];function Uf(){return{transforms:[Qf],enter:{literalAutolink:Kf,literalAutolinkEmail:gn,literalAutolinkHttp:gn,literalAutolinkWww:gn},exit:{literalAutolink:Gf,literalAutolinkEmail:Wf,literalAutolinkHttp:Vf,literalAutolinkWww:qf}}}function Hf(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:fn,notInConstruct:pn},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:fn,notInConstruct:pn},{character:":",before:"[ps]",after:"\\/",inConstruct:fn,notInConstruct:pn}]}}function Kf(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function gn(e){this.config.enter.autolinkProtocol.call(this,e)}function Vf(e){this.config.exit.autolinkProtocol.call(this,e)}function qf(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function Wf(e){this.config.exit.autolinkEmail.call(this,e)}function Gf(e){this.exit(e)}function Qf(e){zf(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Xf],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),Yf]],{ignore:["link","linkReference"]})}function Xf(e,t,n,r,s){let i="";if(!ua(s)||(/^w/i.test(t)&&(n=t+n,t="",i="http://"),!Jf(n)))return!1;const a=Zf(n+r);if(!a[0])return!1;const o={type:"link",title:null,url:i+t+a[0],children:[{type:"text",value:t+a[0]}]};return a[1]?[o,{type:"text",value:a[1]}]:o}function Yf(e,t,n,r){return!ua(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function Jf(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Zf(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const s=hs(e,"(");let i=hs(e,")");for(;r!==-1&&s>i;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[e,n]}function ua(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||Ye(n)||Vt(n))&&(!t||n!==47)}ca.peek=lp;function ep(){this.buffer()}function tp(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function np(){this.buffer()}function rp(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function sp(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(e)).toLowerCase(),n.label=t}function ip(e){this.exit(e)}function ap(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(e)).toLowerCase(),n.label=t}function op(e){this.exit(e)}function lp(){return"["}function ca(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const a=n.enter("footnoteReference"),o=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),o(),a(),i+=s.move("]"),i}function up(){return{enter:{gfmFootnoteCallString:ep,gfmFootnoteCall:tp,gfmFootnoteDefinitionLabelString:np,gfmFootnoteDefinition:rp},exit:{gfmFootnoteCallString:sp,gfmFootnoteCall:ip,gfmFootnoteDefinitionLabelString:ap,gfmFootnoteDefinition:op}}}function cp(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:ca},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,a){const o=i.createTracker(a);let u=o.move("[^");const l=i.enter("footnoteDefinition"),c=i.enter("label");return u+=o.move(i.safe(i.associationId(r),{before:u,after:"]"})),c(),u+=o.move("]:"),r.children&&r.children.length>0&&(o.shift(4),u+=o.move((t?`
|
|
15
|
-
`:" ")+i.indentLines(i.containerFlow(r,o.current()),t?da:dp))),l(),u}}function dp(e,t,n){return t===0?e:da(e,t,n)}function da(e,t,n){return(n?"":" ")+e}const hp=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];ha.peek=yp;function fp(){return{canContainEols:["delete"],enter:{strikethrough:gp},exit:{strikethrough:mp}}}function pp(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:hp}],handlers:{delete:ha}}}function gp(e){this.enter({type:"delete",children:[]},e)}function mp(e){this.exit(e)}function ha(e,t,n,r){const s=n.createTracker(r),i=n.enter("strikethrough");let a=s.move("~~");return a+=n.containerPhrasing(e,{...s.current(),before:a,after:"~"}),a+=s.move("~~"),i(),a}function yp(){return"~"}function xp(e){return e.length}function bp(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||xp,i=[],a=[],o=[],u=[];let l=0,c=-1;for(;++c<e.length;){const m=[],S=[];let g=-1;for(e[c].length>l&&(l=e[c].length);++g<e[c].length;){const k=Sp(e[c][g]);if(n.alignDelimiters!==!1){const w=s(k);S[g]=w,(u[g]===void 0||w>u[g])&&(u[g]=w)}m.push(k)}a[c]=m,o[c]=S}let d=-1;if(typeof r=="object"&&"length"in r)for(;++d<l;)i[d]=fs(r[d]);else{const m=fs(r);for(;++d<l;)i[d]=m}d=-1;const p=[],f=[];for(;++d<l;){const m=i[d];let S="",g="";m===99?(S=":",g=":"):m===108?S=":":m===114&&(g=":");let k=n.alignDelimiters===!1?1:Math.max(1,u[d]-S.length-g.length);const w=S+"-".repeat(k)+g;n.alignDelimiters!==!1&&(k=S.length+k+g.length,k>u[d]&&(u[d]=k),f[d]=k),p[d]=w}a.splice(1,0,p),o.splice(1,0,f),c=-1;const y=[];for(;++c<a.length;){const m=a[c],S=o[c];d=-1;const g=[];for(;++d<l;){const k=m[d]||"";let w="",E="";if(n.alignDelimiters!==!1){const M=u[d]-(S[d]||0),I=i[d];I===114?w=" ".repeat(M):I===99?M%2?(w=" ".repeat(M/2+.5),E=" ".repeat(M/2-.5)):(w=" ".repeat(M/2),E=w):E=" ".repeat(M)}n.delimiterStart!==!1&&!d&&g.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&k==="")&&(n.delimiterStart!==!1||d)&&g.push(" "),n.alignDelimiters!==!1&&g.push(w),g.push(k),n.alignDelimiters!==!1&&g.push(E),n.padding!==!1&&g.push(" "),(n.delimiterEnd!==!1||d!==l-1)&&g.push("|")}y.push(n.delimiterEnd===!1?g.join("").replace(/ +$/,""):g.join(""))}return y.join(`
|
|
16
|
-
`)}function Sp(e){return e==null?"":String(e)}function fs(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function kp(e,t,n,r){const s=n.enter("blockquote"),i=n.createTracker(r);i.move("> "),i.shift(2);const a=n.indentLines(n.containerFlow(e,i.current()),wp);return s(),a}function wp(e,t,n){return">"+(n?"":" ")+e}function vp(e,t){return ps(e,t.inConstruct,!0)&&!ps(e,t.notInConstruct,!1)}function ps(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function gs(e,t,n,r){let s=-1;for(;++s<n.unsafe.length;)if(n.unsafe[s].character===`
|
|
17
|
-
`&&vp(n.stack,n.unsafe[s]))return/[ \t]/.test(r.before)?"":" ";return`\\
|
|
18
|
-
`}function Cp(e,t){const n=String(e);let r=n.indexOf(t),s=r,i=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===s?++i>a&&(a=i):i=1,s=r+t.length,r=n.indexOf(t,s);return a}function Ip(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Tp(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function Rp(e,t,n,r){const s=Tp(n),i=e.value||"",a=s==="`"?"GraveAccent":"Tilde";if(Ip(e,n)){const d=n.enter("codeIndented"),p=n.indentLines(i,Mp);return d(),p}const o=n.createTracker(r),u=s.repeat(Math.max(Cp(i,s)+1,3)),l=n.enter("codeFenced");let c=o.move(u);if(e.lang){const d=n.enter(`codeFencedLang${a}`);c+=o.move(n.safe(e.lang,{before:c,after:" ",encode:["`"],...o.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${a}`);c+=o.move(" "),c+=o.move(n.safe(e.meta,{before:c,after:`
|
|
19
|
-
`,encode:["`"],...o.current()})),d()}return c+=o.move(`
|
|
20
|
-
`),i&&(c+=o.move(i+`
|
|
21
|
-
`)),c+=o.move(u),l(),c}function Mp(e,t,n){return(n?"":" ")+e}function mr(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function Ap(e,t,n,r){const s=mr(n),i=s==='"'?"Quote":"Apostrophe",a=n.enter("definition");let o=n.enter("label");const u=n.createTracker(r);let l=u.move("[");return l+=u.move(n.safe(n.associationId(e),{before:l,after:"]",...u.current()})),l+=u.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),l+=u.move("<"),l+=u.move(n.safe(e.url,{before:l,after:">",...u.current()})),l+=u.move(">")):(o=n.enter("destinationRaw"),l+=u.move(n.safe(e.url,{before:l,after:e.title?" ":`
|
|
22
|
-
`,...u.current()}))),o(),e.title&&(o=n.enter(`title${i}`),l+=u.move(" "+s),l+=u.move(n.safe(e.title,{before:l,after:s,...u.current()})),l+=u.move(s),o()),a(),l}function Ep(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function St(e){return"&#x"+e.toString(16).toUpperCase()+";"}function $t(e,t,n){const r=at(e),s=at(t);return r===void 0?s===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}fa.peek=Lp;function fa(e,t,n,r){const s=Ep(n),i=n.enter("emphasis"),a=n.createTracker(r),o=a.move(s);let u=a.move(n.containerPhrasing(e,{after:s,before:o,...a.current()}));const l=u.charCodeAt(0),c=$t(r.before.charCodeAt(r.before.length-1),l,s);c.inside&&(u=St(l)+u.slice(1));const d=u.charCodeAt(u.length-1),p=$t(r.after.charCodeAt(0),d,s);p.inside&&(u=u.slice(0,-1)+St(d));const f=a.move(s);return i(),n.attentionEncodeSurroundingInfo={after:p.outside,before:c.outside},o+u+f}function Lp(e,t,n){return n.options.emphasis||"*"}function Np(e,t){let n=!1;return pr(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,_n}),!!((!e.depth||e.depth<3)&&or(e)&&(t.options.setext||n))}function Pp(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(Np(e,n)){const c=n.enter("headingSetext"),d=n.enter("phrasing"),p=n.containerPhrasing(e,{...i.current(),before:`
|
|
23
|
-
`,after:`
|
|
24
|
-
`});return d(),c(),p+`
|
|
25
|
-
`+(s===1?"=":"-").repeat(p.length-(Math.max(p.lastIndexOf("\r"),p.lastIndexOf(`
|
|
26
|
-
`))+1))}const a="#".repeat(s),o=n.enter("headingAtx"),u=n.enter("phrasing");i.move(a+" ");let l=n.containerPhrasing(e,{before:"# ",after:`
|
|
27
|
-
`,...i.current()});return/^[\t ]/.test(l)&&(l=St(l.charCodeAt(0))+l.slice(1)),l=l?a+" "+l:a,n.options.closeAtx&&(l+=" "+a),u(),o(),l}pa.peek=jp;function pa(e){return e.value||""}function jp(){return"<"}ga.peek=Dp;function ga(e,t,n,r){const s=mr(n),i=s==='"'?"Quote":"Apostrophe",a=n.enter("image");let o=n.enter("label");const u=n.createTracker(r);let l=u.move("![");return l+=u.move(n.safe(e.alt,{before:l,after:"]",...u.current()})),l+=u.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),l+=u.move("<"),l+=u.move(n.safe(e.url,{before:l,after:">",...u.current()})),l+=u.move(">")):(o=n.enter("destinationRaw"),l+=u.move(n.safe(e.url,{before:l,after:e.title?" ":")",...u.current()}))),o(),e.title&&(o=n.enter(`title${i}`),l+=u.move(" "+s),l+=u.move(n.safe(e.title,{before:l,after:s,...u.current()})),l+=u.move(s),o()),l+=u.move(")"),a(),l}function Dp(){return"!"}ma.peek=_p;function ma(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let a=n.enter("label");const o=n.createTracker(r);let u=o.move("![");const l=n.safe(e.alt,{before:u,after:"]",...o.current()});u+=o.move(l+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),{before:u,after:"]",...o.current()});return a(),n.stack=c,i(),s==="full"||!l||l!==d?u+=o.move(d+"]"):s==="shortcut"?u=u.slice(0,-1):u+=o.move("]"),u}function _p(){return"!"}ya.peek=Op;function ya(e,t,n){let r=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i<n.unsafe.length;){const a=n.unsafe[i],o=n.compilePattern(a);let u;if(a.atBreak)for(;u=o.exec(r);){let l=u.index;r.charCodeAt(l)===10&&r.charCodeAt(l-1)===13&&l--,r=r.slice(0,l)+" "+r.slice(u.index+1)}}return s+r+s}function Op(){return"`"}function xa(e,t){const n=or(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}ba.peek=zp;function ba(e,t,n,r){const s=mr(n),i=s==='"'?"Quote":"Apostrophe",a=n.createTracker(r);let o,u;if(xa(e,n)){const c=n.stack;n.stack=[],o=n.enter("autolink");let d=a.move("<");return d+=a.move(n.containerPhrasing(e,{before:d,after:">",...a.current()})),d+=a.move(">"),o(),n.stack=c,d}o=n.enter("link"),u=n.enter("label");let l=a.move("[");return l+=a.move(n.containerPhrasing(e,{before:l,after:"](",...a.current()})),l+=a.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=n.enter("destinationLiteral"),l+=a.move("<"),l+=a.move(n.safe(e.url,{before:l,after:">",...a.current()})),l+=a.move(">")):(u=n.enter("destinationRaw"),l+=a.move(n.safe(e.url,{before:l,after:e.title?" ":")",...a.current()}))),u(),e.title&&(u=n.enter(`title${i}`),l+=a.move(" "+s),l+=a.move(n.safe(e.title,{before:l,after:s,...a.current()})),l+=a.move(s),u()),l+=a.move(")"),o(),l}function zp(e,t,n){return xa(e,n)?"<":"["}Sa.peek=Fp;function Sa(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let a=n.enter("label");const o=n.createTracker(r);let u=o.move("[");const l=n.containerPhrasing(e,{before:u,after:"]",...o.current()});u+=o.move(l+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),{before:u,after:"]",...o.current()});return a(),n.stack=c,i(),s==="full"||!l||l!==d?u+=o.move(d+"]"):s==="shortcut"?u=u.slice(0,-1):u+=o.move("]"),u}function Fp(){return"["}function yr(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Bp(e){const t=yr(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function $p(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function ka(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function Up(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let a=e.ordered?$p(n):yr(n);const o=e.ordered?a==="."?")":".":Bp(n);let u=t&&n.bulletLastUsed?a===n.bulletLastUsed:!1;if(!e.ordered){const c=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&c&&(!c.children||!c.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(u=!0),ka(n)===a&&c){let d=-1;for(;++d<e.children.length;){const p=e.children[d];if(p&&p.type==="listItem"&&p.children&&p.children[0]&&p.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(a=o),n.bulletCurrent=a;const l=n.containerFlow(e,r);return n.bulletLastUsed=a,n.bulletCurrent=i,s(),l}function Hp(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function Kp(e,t,n,r){const s=Hp(n);let i=n.bulletCurrent||yr(n);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let a=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(a=Math.ceil(a/4)*4);const o=n.createTracker(r);o.move(i+" ".repeat(a-i.length)),o.shift(a);const u=n.enter("listItem"),l=n.indentLines(n.containerFlow(e,o.current()),c);return u(),l;function c(d,p,f){return p?(f?"":" ".repeat(a))+d:(f?i:i+" ".repeat(a-i.length))+d}}function Vp(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),a=n.containerPhrasing(e,r);return i(),s(),a}const qp=Gt(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Wp(e,t,n,r){return(e.children.some(function(a){return qp(a)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function Gp(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}wa.peek=Qp;function wa(e,t,n,r){const s=Gp(n),i=n.enter("strong"),a=n.createTracker(r),o=a.move(s+s);let u=a.move(n.containerPhrasing(e,{after:s,before:o,...a.current()}));const l=u.charCodeAt(0),c=$t(r.before.charCodeAt(r.before.length-1),l,s);c.inside&&(u=St(l)+u.slice(1));const d=u.charCodeAt(u.length-1),p=$t(r.after.charCodeAt(0),d,s);p.inside&&(u=u.slice(0,-1)+St(d));const f=a.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:p.outside,before:c.outside},o+u+f}function Qp(e,t,n){return n.options.strong||"*"}function Xp(e,t,n,r){return n.safe(e.value,r)}function Yp(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function Jp(e,t,n){const r=(ka(n)+(n.options.ruleSpaces?" ":"")).repeat(Yp(n));return n.options.ruleSpaces?r.slice(0,-1):r}const va={blockquote:kp,break:gs,code:Rp,definition:Ap,emphasis:fa,hardBreak:gs,heading:Pp,html:pa,image:ga,imageReference:ma,inlineCode:ya,link:ba,linkReference:Sa,list:Up,listItem:Kp,paragraph:Vp,root:Wp,strong:wa,text:Xp,thematicBreak:Jp};function Zp(){return{enter:{table:eg,tableData:ms,tableHeader:ms,tableRow:ng},exit:{codeText:rg,table:tg,tableData:mn,tableHeader:mn,tableRow:mn}}}function eg(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function tg(e){this.exit(e),this.data.inTable=void 0}function ng(e){this.enter({type:"tableRow",children:[]},e)}function mn(e){this.exit(e)}function ms(e){this.enter({type:"tableCell",children:[]},e)}function rg(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,sg));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function sg(e,t){return t==="|"?t:e}function ig(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
28
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:p,table:a,tableCell:u,tableRow:o}};function a(f,y,m,S){return l(c(f,m,S),f.align)}function o(f,y,m,S){const g=d(f,m,S),k=l([g]);return k.slice(0,k.indexOf(`
|
|
29
|
-
`))}function u(f,y,m,S){const g=m.enter("tableCell"),k=m.enter("phrasing"),w=m.containerPhrasing(f,{...S,before:i,after:i});return k(),g(),w}function l(f,y){return bp(f,{align:y,alignDelimiters:r,padding:n,stringLength:s})}function c(f,y,m){const S=f.children;let g=-1;const k=[],w=y.enter("table");for(;++g<S.length;)k[g]=d(S[g],y,m);return w(),k}function d(f,y,m){const S=f.children;let g=-1;const k=[],w=y.enter("tableRow");for(;++g<S.length;)k[g]=u(S[g],f,y,m);return w(),k}function p(f,y,m){let S=va.inlineCode(f,y,m);return m.stack.includes("tableCell")&&(S=S.replace(/\|/g,"\\$&")),S}}function ag(){return{exit:{taskListCheckValueChecked:ys,taskListCheckValueUnchecked:ys,paragraph:lg}}}function og(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:ug}}}function ys(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function lg(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=t.children;let i=-1,a;for(;++i<s.length;){const o=s[i];if(o.type==="paragraph"){a=o;break}}a===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function ug(e,t,n,r){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",o=n.createTracker(r);i&&o.move(a);let u=va.listItem(e,t,n,{...r,...o.current()});return i&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),u;function l(c){return c+a}}function cg(){return[Uf(),up(),fp(),Zp(),ag()]}function dg(e){return{extensions:[Hf(),cp(e),pp(),ig(e),og()]}}const hg={tokenize:xg,partial:!0},Ca={tokenize:bg,partial:!0},Ia={tokenize:Sg,partial:!0},Ta={tokenize:kg,partial:!0},fg={tokenize:wg,partial:!0},Ra={name:"wwwAutolink",tokenize:mg,previous:Aa},Ma={name:"protocolAutolink",tokenize:yg,previous:Ea},Ke={name:"emailAutolink",tokenize:gg,previous:La},Oe={};function pg(){return{text:Oe}}let Xe=48;for(;Xe<123;)Oe[Xe]=Ke,Xe++,Xe===58?Xe=65:Xe===91&&(Xe=97);Oe[43]=Ke;Oe[45]=Ke;Oe[46]=Ke;Oe[95]=Ke;Oe[72]=[Ke,Ma];Oe[104]=[Ke,Ma];Oe[87]=[Ke,Ra];Oe[119]=[Ke,Ra];function gg(e,t,n){const r=this;let s,i;return a;function a(d){return!Bn(d)||!La.call(r,r.previous)||xr(r.events)?n(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(d))}function o(d){return Bn(d)?(e.consume(d),o):d===64?(e.consume(d),u):n(d)}function u(d){return d===46?e.check(fg,c,l)(d):d===45||d===95||he(d)?(i=!0,e.consume(d),u):c(d)}function l(d){return e.consume(d),s=!0,u}function c(d){return i&&s&&ge(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):n(d)}}function mg(e,t,n){const r=this;return s;function s(a){return a!==87&&a!==119||!Aa.call(r,r.previous)||xr(r.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(hg,e.attempt(Ca,e.attempt(Ia,i),n),n)(a))}function i(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function yg(e,t,n){const r=this;let s="",i=!1;return a;function a(d){return(d===72||d===104)&&Ea.call(r,r.previous)&&!xr(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(d),e.consume(d),o):n(d)}function o(d){if(ge(d)&&s.length<5)return s+=String.fromCodePoint(d),e.consume(d),o;if(d===58){const p=s.toLowerCase();if(p==="http"||p==="https")return e.consume(d),u}return n(d)}function u(d){return d===47?(e.consume(d),i?l:(i=!0,u)):n(d)}function l(d){return d===null||zt(d)||Z(d)||Ye(d)||Vt(d)?n(d):e.attempt(Ca,e.attempt(Ia,c),n)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function xg(e,t,n){let r=0;return s;function s(a){return(a===87||a===119)&&r<3?(r++,e.consume(a),s):a===46&&r===3?(e.consume(a),i):n(a)}function i(a){return a===null?n(a):t(a)}}function bg(e,t,n){let r,s,i;return a;function a(l){return l===46||l===95?e.check(Ta,u,o)(l):l===null||Z(l)||Ye(l)||l!==45&&Vt(l)?u(l):(i=!0,e.consume(l),a)}function o(l){return l===95?r=!0:(s=r,r=void 0),e.consume(l),a}function u(l){return s||r||!i?n(l):t(l)}}function Sg(e,t){let n=0,r=0;return s;function s(a){return a===40?(n++,e.consume(a),s):a===41&&r<n?i(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(Ta,t,i)(a):a===null||Z(a)||Ye(a)?t(a):(e.consume(a),s)}function i(a){return a===41&&r++,e.consume(a),s}}function kg(e,t,n){return r;function r(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),r):o===38?(e.consume(o),i):o===93?(e.consume(o),s):o===60||o===null||Z(o)||Ye(o)?t(o):n(o)}function s(o){return o===null||o===40||o===91||Z(o)||Ye(o)?t(o):r(o)}function i(o){return ge(o)?a(o):n(o)}function a(o){return o===59?(e.consume(o),r):ge(o)?(e.consume(o),a):n(o)}}function wg(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return he(i)?n(i):t(i)}}function Aa(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Z(e)}function Ea(e){return!ge(e)}function La(e){return!(e===47||Bn(e))}function Bn(e){return e===43||e===45||e===46||e===95||he(e)}function xr(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const vg={tokenize:Lg,partial:!0};function Cg(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Mg,continuation:{tokenize:Ag},exit:Eg}},text:{91:{name:"gfmFootnoteCall",tokenize:Rg},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ig,resolveTo:Tg}}}}function Ig(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;s--;){const u=r.events[s][1];if(u.type==="labelImage"){a=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return o;function o(u){if(!a||!a._balanced)return n(u);const l=Ne(r.sliceSerialize({start:a.end,end:r.now()}));return l.codePointAt(0)!==94||!i.includes(l.slice(1))?n(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),t(u))}}function Tg(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",a,t],["exit",a,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...o),e}function Rg(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,a;return o;function o(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),u}function u(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(d){if(i>999||d===93&&!a||d===null||d===91||Z(d))return n(d);if(d===93){e.exit("chunkString");const p=e.exit("gfmFootnoteCallString");return s.includes(Ne(r.sliceSerialize(p)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return Z(d)||(a=!0),i++,e.consume(d),d===92?c:l}function c(d){return d===91||d===92||d===93?(e.consume(d),i++,l):l(d)}}function Mg(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,a=0,o;return u;function u(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(y)}function c(y){if(a>999||y===93&&!o||y===null||y===91||Z(y))return n(y);if(y===93){e.exit("chunkString");const m=e.exit("gfmFootnoteDefinitionLabelString");return i=Ne(r.sliceSerialize(m)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),p}return Z(y)||(o=!0),a++,e.consume(y),y===92?d:c}function d(y){return y===91||y===92||y===93?(e.consume(y),a++,c):c(y)}function p(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),s.includes(i)||s.push(i),X(e,f,"gfmFootnoteDefinitionWhitespace")):n(y)}function f(y){return t(y)}}function Ag(e,t,n){return e.check(Ct,t,e.attempt(vg,t,n))}function Eg(e){e.exit("gfmFootnoteDefinition")}function Lg(e,t,n){const r=this;return X(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?t(i):n(i)}}function Ng(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(a,o){let u=-1;for(;++u<a.length;)if(a[u][0]==="enter"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._close){let l=u;for(;l--;)if(a[l][0]==="exit"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._open&&a[u][1].end.offset-a[u][1].start.offset===a[l][1].end.offset-a[l][1].start.offset){a[u][1].type="strikethroughSequence",a[l][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},a[l][1].start),end:Object.assign({},a[u][1].end)},d={type:"strikethroughText",start:Object.assign({},a[l][1].end),end:Object.assign({},a[u][1].start)},p=[["enter",c,o],["enter",a[l][1],o],["exit",a[l][1],o],["enter",d,o]],f=o.parser.constructs.insideSpan.null;f&&ve(p,p.length,0,qt(f,a.slice(l+1,u),o)),ve(p,p.length,0,[["exit",d,o],["enter",a[u][1],o],["exit",a[u][1],o],["exit",c,o]]),ve(a,l-1,u-l+3,p),u=l+p.length-2;break}}for(u=-1;++u<a.length;)a[u][1].type==="strikethroughSequenceTemporary"&&(a[u][1].type="data");return a}function i(a,o,u){const l=this.previous,c=this.events;let d=0;return p;function p(y){return l===126&&c[c.length-1][1].type!=="characterEscape"?u(y):(a.enter("strikethroughSequenceTemporary"),f(y))}function f(y){const m=at(l);if(y===126)return d>1?u(y):(a.consume(y),d++,f);if(d<2&&!n)return u(y);const S=a.exit("strikethroughSequenceTemporary"),g=at(y);return S._open=!g||g===2&&!!m,S._close=!m||m===2&&!!g,o(y)}}}class Pg{constructor(){this.map=[]}add(t,n,r){jg(this,t,n,r)}consume(t){if(this.map.sort(function(i,a){return i[0]-a[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function jg(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=n,e.map[s][2].push(...r);return}s+=1}e.map.push([t,n,r])}}function Dg(e,t){let n=!1;const r=[];for(;t<e.length;){const s=e[t];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=r.length-1;r[i]=r[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function _g(){return{flow:{null:{name:"table",tokenize:Og,resolveAll:zg}}}}function Og(e,t,n){const r=this;let s=0,i=0,a;return o;function o(C){let _=r.events.length-1;for(;_>-1;){const z=r.events[_][1].type;if(z==="lineEnding"||z==="linePrefix")_--;else break}const O=_>-1?r.events[_][1].type:null,G=O==="tableHead"||O==="tableRow"?I:u;return G===I&&r.parser.lazy[r.now().line]?n(C):G(C)}function u(C){return e.enter("tableHead"),e.enter("tableRow"),l(C)}function l(C){return C===124||(a=!0,i+=1),c(C)}function c(C){return C===null?n(C):B(C)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),f):n(C):V(C)?X(e,c,"whitespace")(C):(i+=1,a&&(a=!1,s+=1),C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),a=!0,c):(e.enter("data"),d(C)))}function d(C){return C===null||C===124||Z(C)?(e.exit("data"),c(C)):(e.consume(C),C===92?p:d)}function p(C){return C===92||C===124?(e.consume(C),d):d(C)}function f(C){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(C):(e.enter("tableDelimiterRow"),a=!1,V(C)?X(e,y,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):y(C))}function y(C){return C===45||C===58?S(C):C===124?(a=!0,e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),m):M(C)}function m(C){return V(C)?X(e,S,"whitespace")(C):S(C)}function S(C){return C===58?(i+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),g):C===45?(i+=1,g(C)):C===null||B(C)?E(C):M(C)}function g(C){return C===45?(e.enter("tableDelimiterFiller"),k(C)):M(C)}function k(C){return C===45?(e.consume(C),k):C===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(C))}function w(C){return V(C)?X(e,E,"whitespace")(C):E(C)}function E(C){return C===124?y(C):C===null||B(C)?!a||s!==i?M(C):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(C)):M(C)}function M(C){return n(C)}function I(C){return e.enter("tableRow"),P(C)}function P(C){return C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),P):C===null||B(C)?(e.exit("tableRow"),t(C)):V(C)?X(e,P,"whitespace")(C):(e.enter("data"),D(C))}function D(C){return C===null||C===124||Z(C)?(e.exit("data"),P(C)):(e.consume(C),C===92?F:D)}function F(C){return C===92||C===124?(e.consume(C),D):D(C)}}function zg(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],a=[0,0,0,0],o=!1,u=0,l,c,d;const p=new Pg;for(;++n<e.length;){const f=e[n],y=f[1];f[0]==="enter"?y.type==="tableHead"?(o=!1,u!==0&&(xs(p,t,u,l,c),c=void 0,u=0),l={type:"table",start:Object.assign({},y.start),end:Object.assign({},y.end)},p.add(n,0,[["enter",l,t]])):y.type==="tableRow"||y.type==="tableDelimiterRow"?(r=!0,d=void 0,i=[0,0,0,0],a=[0,n+1,0,0],o&&(o=!1,c={type:"tableBody",start:Object.assign({},y.start),end:Object.assign({},y.end)},p.add(n,0,[["enter",c,t]])),s=y.type==="tableDelimiterRow"?2:c?3:1):s&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")?(r=!1,a[2]===0&&(i[1]!==0&&(a[0]=a[1],d=At(p,t,i,s,void 0,d),i=[0,0,0,0]),a[2]=n)):y.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(a[0]=a[1],d=At(p,t,i,s,void 0,d)),i=a,a=[i[1],n,0,0])):y.type==="tableHead"?(o=!0,u=n):y.type==="tableRow"||y.type==="tableDelimiterRow"?(u=n,i[1]!==0?(a[0]=a[1],d=At(p,t,i,s,n,d)):a[1]!==0&&(d=At(p,t,a,s,n,d)),s=0):s&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")&&(a[3]=n)}for(u!==0&&xs(p,t,u,l,c),p.consume(t.events),n=-1;++n<t.events.length;){const f=t.events[n];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=Dg(t.events,n))}return e}function At(e,t,n,r,s,i){const a=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",o="tableContent";n[0]!==0&&(i.end=Object.assign({},rt(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const u=rt(t.events,n[1]);if(i={type:a,start:Object.assign({},u),end:Object.assign({},u)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const l=rt(t.events,n[2]),c=rt(t.events,n[3]),d={type:o,start:Object.assign({},l),end:Object.assign({},c)};if(e.add(n[2],0,[["enter",d,t]]),r!==2){const p=t.events[n[2]],f=t.events[n[3]];if(p[1].end=Object.assign({},f[1].end),p[1].type="chunkText",p[1].contentType="text",n[3]>n[2]+1){const y=n[2]+1,m=n[3]-n[2]-1;e.add(y,m,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},rt(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function xs(e,t,n,r,s){const i=[],a=rt(t.events,n);s&&(s.end=Object.assign({},a),i.push(["exit",s,t])),r.end=Object.assign({},a),i.push(["exit",r,t]),e.add(n+1,0,i)}function rt(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const Fg={name:"tasklistCheck",tokenize:$g};function Bg(){return{text:{91:Fg}}}function $g(e,t,n){const r=this;return s;function s(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),i)}function i(u){return Z(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),a):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),a):n(u)}function a(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):n(u)}function o(u){return B(u)?t(u):V(u)?e.check({tokenize:Ug},t,n)(u):n(u)}}function Ug(e,t,n){return X(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function Hg(e){return Ui([pg(),Cg(),Ng(e),_g(),Bg()])}const Kg={};function Vg(e){const t=this,n=e||Kg,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(Hg(n)),i.push(cg()),a.push(dg(n))}function qg(){var e;return typeof navigator<"u"&&typeof((e=navigator.clipboard)==null?void 0:e.writeText)=="function"}function Wg(e){if(typeof document>"u")return;const t=document.getSelection();t&&(t.removeAllRanges(),e.forEach(n=>t.addRange(n)))}function bs(e){if(typeof document>"u"||!document.body)return!1;const t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t:null,r=n?{start:n.selectionStart,end:n.selectionEnd}:null,s=document.getSelection(),i=s?Array.from({length:s.rangeCount},(u,l)=>s.getRangeAt(l).cloneRange()):[],a=document.createElement("textarea");a.value=e,a.setAttribute("readonly",""),a.setAttribute("aria-hidden","true"),a.style.position="fixed",a.style.top="0",a.style.left="-9999px",a.style.opacity="0",a.style.pointerEvents="none",a.style.fontSize="12pt",document.body.appendChild(a);try{a.focus({preventScroll:!0})}catch{a.focus()}a.select(),a.setSelectionRange(0,a.value.length);let o=!1;try{o=typeof document.execCommand=="function"&&document.execCommand("copy")}catch{o=!1}if(a.remove(),t)try{t.focus({preventScroll:!0})}catch{t.focus()}return n&&r?n.setSelectionRange(r.start,r.end):Wg(i),o}async function Gg(e){if(!e)return!1;if(qg())try{return await navigator.clipboard.writeText(e),!0}catch{return bs(e)}return bs(e)}const Qg=1300;function Xg(e){const[t,n]=v.useState(!1),r=v.useCallback(async()=>{if(!e.text)return;const s=await Gg(e.text);n(!!s)},[e.text]);return v.useEffect(()=>{if(!t||typeof window>"u")return;const s=window.setTimeout(()=>n(!1),e.resetDelayMs??Qg);return()=>window.clearTimeout(s)},[t,e.resetDelayMs]),{copied:t,copy:r}}const Yg=/language-([a-z0-9-]+)/i;function Na(e){return typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Na).join(""):""}function Jg(e){const t=Na(e);return t.endsWith(`
|
|
30
|
-
`)?t.slice(0,-1):t}function Zg(e){var n;const t=e?Yg.exec(e):null;return((n=t==null?void 0:t[1])==null?void 0:n.toLowerCase())||"text"}function em(e){const t=v.useMemo(()=>Zg(e.className),[e.className]),n=v.useMemo(()=>Jg(e.children),[e.children]),{copied:r,copy:s}=Xg({text:n});return h.jsxs("div",{className:"chat-codeblock",children:[h.jsxs("div",{className:"chat-codeblock-toolbar",children:[h.jsx("span",{className:"chat-codeblock-language",children:t}),h.jsxs("button",{type:"button",className:"chat-codeblock-copy",onClick:()=>void s(),"aria-label":r?e.texts.copiedCodeLabel:e.texts.copyCodeLabel,children:[r?h.jsx(Xn,{className:"h-3.5 w-3.5"}):h.jsx(No,{className:"h-3.5 w-3.5"}),h.jsx("span",{children:r?e.texts.copiedCodeLabel:e.texts.copyCodeLabel})]})]}),h.jsx("pre",{children:h.jsx("code",{className:e.className,children:n})})]})}const Ss=14e4,tm=new Set(["http:","https:","mailto:","tel:"]);function nm(e){return e.length<=Ss?e:`${e.slice(0,Ss)}
|
|
31
|
-
|
|
32
|
-
...`}function ks(e){if(!e)return null;if(e.startsWith("#")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))return e;try{const t=new URL(e);return tm.has(t.protocol)?e:null}catch{return null}}function rm(e){return/^https?:\/\//i.test(e)}function sm(e){const t=e.role==="user",n=v.useMemo(()=>({a:({href:r,children:s,...i})=>{const a=ks(r);if(!a)return h.jsx("span",{className:"chat-link-invalid",children:s});const o=rm(a);return h.jsx("a",{...i,href:a,target:o?"_blank":void 0,rel:o?"noreferrer noopener":void 0,children:s})},table:({children:r,...s})=>h.jsx("div",{className:"chat-table-wrap",children:h.jsx("table",{...s,children:r})}),input:({type:r,checked:s,...i})=>r!=="checkbox"?h.jsx("input",{...i,type:r}):h.jsx("input",{...i,type:"checkbox",checked:s,readOnly:!0,disabled:!0,className:"chat-task-checkbox"}),img:({src:r,alt:s,...i})=>{const a=ks(r);return a?h.jsx("img",{...i,src:a,alt:s||"",loading:"lazy",decoding:"async"}):null},code:({className:r,children:s,...i})=>{const a=String(s??"");return!r&&!a.includes(`
|
|
33
|
-
`)?h.jsx("code",{...i,className:oe("chat-inline-code",r),children:s}):h.jsx(em,{className:r,texts:e.texts,children:s})}}),[e.texts]);return h.jsx("div",{className:oe("chat-markdown",t?"chat-markdown-user":"chat-markdown-assistant"),children:h.jsx(Nf,{skipHtml:!0,remarkPlugins:[Vg],components:n,children:nm(e.text)})})}function im(e){return h.jsxs("details",{className:"mt-3",open:!0,children:[h.jsx("summary",{className:oe("cursor-pointer text-xs",e.isUser?"text-primary-100":"text-gray-500"),children:e.label}),h.jsx("pre",{className:oe("mt-2 whitespace-pre-wrap break-words rounded-lg p-2 text-[11px]",e.isUser?"bg-primary-700/60":"bg-gray-100"),children:e.text})]})}const ws=220;function am(e){const t=e.toLowerCase();return t.includes("exec")||t.includes("shell")||t.includes("command")?h.jsx(Po,{className:"h-3.5 w-3.5"}):t.includes("search")?h.jsx(Wn,{className:"h-3.5 w-3.5"}):t.includes("fetch")||t.includes("http")||t.includes("web")?h.jsx(jo,{className:"h-3.5 w-3.5"}):t.includes("read")||t.includes("file")?h.jsx(Do,{className:"h-3.5 w-3.5"}):t.includes("message")||t.includes("send")?h.jsx(_o,{className:"h-3.5 w-3.5"}):t.includes("cron")||t.includes("schedule")?h.jsx(Oo,{className:"h-3.5 w-3.5"}):h.jsx(Js,{className:"h-3.5 w-3.5"})}function om({card:e}){var i;const t=((i=e.output)==null?void 0:i.trim())??"",n=t.length>ws||t.includes(`
|
|
34
|
-
`),r=n?`${t.slice(0,ws)}...`:t,s=e.kind==="result"||e.hasResult;return h.jsxs("div",{className:"rounded-xl border border-amber-200/80 bg-amber-50/60 px-3 py-2.5",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs font-semibold text-amber-800",children:[am(e.toolName),h.jsx("span",{children:e.titleLabel}),h.jsx("span",{className:"font-mono text-[11px] text-amber-900/80",children:e.toolName})]}),e.summary?h.jsx("div",{className:"mt-1 break-words font-mono text-[11px] text-amber-800/90",children:e.summary}):null,s?h.jsx("div",{className:"mt-2",children:t?n?h.jsxs("details",{className:"group",children:[h.jsx("summary",{className:"cursor-pointer text-[11px] text-amber-700",children:e.outputLabel}),h.jsx("pre",{className:"mt-2 whitespace-pre-wrap break-words rounded-lg border border-amber-200 bg-amber-100/40 p-2 text-[11px] text-amber-900",children:t})]}):h.jsx("pre",{className:"rounded-lg border border-amber-200 bg-amber-100/40 p-2 text-[11px] whitespace-pre-wrap break-words text-amber-900",children:r}):h.jsx("div",{className:"text-[11px] text-amber-700/80",children:e.emptyLabel})}):null]})}function lm(e){return h.jsxs("div",{className:"rounded-lg border border-gray-200 bg-gray-50 px-2.5 py-2 text-xs text-gray-600",children:[h.jsxs("div",{className:"font-semibold text-gray-700",children:[e.label,": ",e.rawType]}),e.text?h.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words text-[11px] text-gray-500",children:e.text}):null]})}function um(e){const{message:t,texts:n}=e,{role:r}=t,s=r==="user";return h.jsx("div",{className:oe("inline-block w-fit max-w-full rounded-2xl border px-4 py-3 shadow-sm",s?"border-primary bg-primary text-white":r==="assistant"?"border-gray-200 bg-white text-gray-900":"border-orange-200/80 bg-orange-50/70 text-gray-900"),children:h.jsx("div",{className:"space-y-2",children:t.parts.map((i,a)=>i.type==="markdown"?h.jsx(sm,{text:i.text,role:r,texts:n},`markdown-${a}`):i.type==="reasoning"?h.jsx(im,{label:i.label,text:i.text,isUser:s},`reasoning-${a}`):i.type==="tool-card"?h.jsx("div",{className:"mt-0.5",children:h.jsx(om,{card:i.card})},`tool-${a}`):i.type==="unknown"?h.jsx(lm,{label:i.label,rawType:i.rawType,text:i.text},`unknown-${a}`):null)})})}function cm(e){return h.jsxs("div",{className:oe("px-1 text-[11px] leading-4 text-gray-400",e.isUser?"text-right":"text-left"),children:[e.roleLabel," · ",e.timestampLabel]})}function dm(e){return h.jsxs("div",{className:oe("space-y-5",e.className),children:[e.messages.map(t=>{const n=t.role==="user";return h.jsxs("div",{className:oe("flex gap-3",n?"justify-end":"justify-start"),children:[n?null:h.jsx(Jt,{role:t.role}),h.jsxs("div",{className:oe("w-fit max-w-[92%] space-y-2",n&&"flex flex-col items-end"),children:[h.jsx(um,{message:t,texts:e.texts}),h.jsx(cm,{roleLabel:t.roleLabel,timestampLabel:t.timestampLabel,isUser:n})]}),n?h.jsx(Jt,{role:t.role}):null]},t.id)}),e.isSending&&!e.hasAssistantDraft?h.jsxs("div",{className:"flex justify-start gap-3",children:[h.jsx(Jt,{role:"assistant"}),h.jsx("div",{className:"rounded-2xl border border-gray-200 bg-white px-4 py-3 text-sm text-gray-500 shadow-sm",children:e.texts.typingLabel})]}):null]})}const hm=10;function vs(e){e.scrollTop=e.scrollHeight}function fm(e){const t=v.useRef(!0),n=v.useRef(!1),r=v.useRef(null),s=v.useRef(!1),i=v.useCallback(()=>{if(n.current){n.current=!1;return}const a=e.scrollRef.current;if(!a)return;const o=a.scrollHeight-a.scrollTop-a.clientHeight;t.current=o<=(e.stickyThresholdPx??hm)},[e.scrollRef,e.stickyThresholdPx]);return v.useEffect(()=>{r.current!==e.resetKey&&(r.current=e.resetKey,t.current=!0,s.current=!0)},[e.resetKey]),v.useLayoutEffect(()=>{if(!s.current||e.isLoading||!e.hasContent)return;const a=e.scrollRef.current;a&&(s.current=!1,n.current=!0,vs(a))},[e.hasContent,e.isLoading,e.scrollRef]),v.useLayoutEffect(()=>{if(!t.current||!e.hasContent)return;const a=e.scrollRef.current;a&&(n.current=!0,vs(a))},[e.contentVersion,e.hasContent,e.scrollRef]),{onScroll:i}}const je={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function pm(e){const t=/^\/([^\s]*)$/.exec(e);return t?(t[1]??"").trim().toLowerCase():null}function Et(e){return(e??"").trim().toLowerCase()}function Cs(e,t){if(!e||!t)return!1;let n=0;for(const r of t)if(r===e[n]&&(n+=1,n>=e.length))return!0;return!1}function gm(e,t){const n=Et(t);if(!n)return je.fallback;const r=Et(e.key),s=Et(e.label||e.key),i=Et(`${e.descriptionZh??""} ${e.description??""}`),a=s.split(/[\s/_-]+/).filter(Boolean);return r===n?je.exactSpec:s===n?je.exactLabel:r.startsWith(n)?je.prefixSpec:s.startsWith(n)?je.prefixLabel:a.some(o=>o.startsWith(n))?je.prefixToken:r.includes(n)?je.containsSpec:s.includes(n)?je.containsLabel:i.includes(n)?je.containsDescription:Cs(n,s)||Cs(n,r)?je.subsequence:0}function mm(e,t,n){const r=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0});return e.map((s,i)=>({record:s,order:i,score:gm(s,t)})).filter(s=>s.score>0).sort((s,i)=>{if(i.score!==s.score)return i.score-s.score;const a=(s.record.label||s.record.key).trim(),o=(i.record.label||i.record.key).trim(),u=r.compare(a,o);return u!==0?u:s.order-i.order}).map(({record:s})=>({key:`skill:${s.key}`,title:s.label||s.key,subtitle:n.slashSkillSubtitle,description:(s.descriptionZh??s.description??"").trim()||n.noSkillDescription,detailLines:[`${n.slashSkillSpecLabel}: ${s.key}`],value:s.key}))}function ym(e,t){return e.map(n=>{const r=t.find(s=>s.key===n);return{key:n,label:(r==null?void 0:r.label)||n}})}function xm(e){return e.map(t=>({key:t.key,label:t.label,description:t.descriptionZh||t.description||"",badgeLabel:t.badgeLabel}))}function bm(e){return{title:e.texts.title,searchPlaceholder:e.texts.searchPlaceholder,emptyLabel:e.texts.emptyLabel,loadingLabel:e.texts.loadingLabel,isLoading:e.isLoading,manageLabel:e.texts.manageLabel,manageHref:"/marketplace/skills",options:xm(e.skillRecords),selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}function Sm(e){return!e.isModelOptionsLoading&&!e.isModelOptionsEmpty?null:e.isModelOptionsLoading?{tone:"neutral",loading:!0}:{tone:"warning",text:e.texts.noModelOptionsLabel,actionLabel:e.texts.configureProviderLabel,onAction:e.onGoToProviders}}function km(e){const t=e.modelOptions.find(n=>n.value===e.selectedModel);return{key:"model",value:e.hasModelOptions?e.selectedModel:void 0,placeholder:e.texts.modelSelectPlaceholder,selectedLabel:t?`${t.providerLabel}/${t.modelLabel}`:void 0,icon:"sparkles",options:e.modelOptions.map(n=>({value:n.value,label:n.modelLabel,description:n.providerLabel})),disabled:!e.hasModelOptions,loading:e.isModelOptionsLoading,emptyLabel:e.texts.modelNoOptionsLabel,onValueChange:e.onValueChange}}function wm(e){var t;return e.shouldShow?{key:"session-type",value:e.selectedSessionType,placeholder:e.texts.sessionTypePlaceholder,selectedLabel:(t=e.selectedSessionTypeOption)==null?void 0:t.label,options:e.sessionTypeOptions.map(n=>({value:n.value,label:n.label})),disabled:!e.canEditSessionType,onValueChange:e.onValueChange}:null}function vm(e){const t=[];for(const n of["off",...e])t.includes(n)||t.push(n);return t}function Cm(e){if(e.supportedLevels.length===0)return null;const t=vm(e.supportedLevels),n=t.includes("off")?"off":t[0],r=e.selectedThinkingLevel&&t.includes(e.selectedThinkingLevel)&&e.selectedThinkingLevel||e.defaultThinkingLevel&&t.includes(e.defaultThinkingLevel)&&e.defaultThinkingLevel||n;return{key:"thinking",value:r,placeholder:e.texts.thinkingLabels[r],selectedLabel:e.texts.thinkingLabels[r],icon:"brain",options:t.map(s=>({value:s,label:e.texts.thinkingLabels[s]})),onValueChange:s=>e.onValueChange(s)}}function Im(e){const[t,n]=v.useState(0),[r,s]=v.useState(!1),i=e.isSlashMode&&!r,a=e.slashItems[t]??null;v.useEffect(()=>{if(!i||e.slashItems.length===0){n(0);return}n(l=>l<0?0:l>=e.slashItems.length?e.slashItems.length-1:l)},[i,e.slashItems.length]),v.useEffect(()=>{!e.isSlashMode&&r&&s(!1)},[r,e.isSlashMode]);const o=v.useCallback(l=>{e.onSelectSlashItem(l),s(!1)},[e]),u=v.useCallback(l=>{if(i&&!l.nativeEvent.isComposing&&(l.key===" "||l.code==="Space")&&s(!0),i&&e.slashItems.length>0){if(l.key==="ArrowDown"){l.preventDefault(),n(c=>(c+1)%e.slashItems.length);return}if(l.key==="ArrowUp"){l.preventDefault(),n(c=>(c-1+e.slashItems.length)%e.slashItems.length);return}if(l.key==="Enter"&&!l.shiftKey||l.key==="Tab"){l.preventDefault();const c=e.slashItems[t];c&&o(c);return}}if(l.key==="Escape"){if(i){l.preventDefault(),s(!0);return}if(e.isSending&&e.canStopGeneration){l.preventDefault(),e.onStop();return}}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),e.onSend())},[t,o,i,e]);return{isSlashPanelOpen:i,activeSlashIndex:t,activeSlashItem:a,onSelectSlashItem:o,onSlashPanelOpenChange:l=>{l||s(!0)},onSetActiveSlashIndex:n,onTextareaKeyDown:u}}const Tm={isProviderStateResolved:!1,draft:"",pendingSessionType:"native",defaultSessionType:"native",canStopGeneration:!1,stopDisabledReason:null,sendError:null,isSending:!1,modelOptions:[],selectedModel:"",selectedThinkingLevel:null,sessionTypeOptions:[],selectedSessionType:void 0,stopSupported:!1,stopReason:void 0,canEditSessionType:!1,sessionTypeUnavailable:!1,skillRecords:[],isSkillsLoading:!1,selectedSkills:[]},K=Ht(e=>({snapshot:Tm,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function Rm(){return{off:R("chatThinkingLevelOff"),minimal:R("chatThinkingLevelMinimal"),low:R("chatThinkingLevelLow"),medium:R("chatThinkingLevelMedium"),high:R("chatThinkingLevelHigh"),adaptive:R("chatThinkingLevelAdaptive"),xhigh:R("chatThinkingLevelXhigh")}}function Mm(e,t){return e.map(n=>({key:n.spec,label:n.label||n.spec,description:n.description,descriptionZh:n.descriptionZh,badgeLabel:n.origin==="builtin"?t:void 0}))}function Am(e){return e.map(t=>({value:t.value,modelLabel:t.modelLabel,providerLabel:t.providerLabel,thinkingCapability:t.thinkingCapability?{supported:t.thinkingCapability.supported,default:t.thinkingCapability.default??null}:null}))}function Em(){var P;const e=er(),{language:t}=Zn(),n=K(D=>D.snapshot),r=v.useMemo(()=>R("chatSkillsPickerOfficial"),[t]),s=v.useMemo(()=>({slashSkillSubtitle:R("chatSlashTypeSkill"),slashSkillSpecLabel:R("chatSlashSkillSpec"),noSkillDescription:R("chatSkillsPickerNoDescription")}),[t]),i=v.useMemo(()=>Mm(n.skillRecords,r),[n.skillRecords,r]),a=v.useMemo(()=>Am(n.modelOptions),[n.modelOptions]),o=a.length>0,u=!n.isProviderStateResolved&&!o,l=n.isProviderStateResolved&&!o,c=(u||l)&&!n.isSending||n.sessionTypeUnavailable,d=u?"":o?R("chatInputPlaceholder"):R("chatModelNoOptions"),p=pm(n.draft),f=v.useMemo(()=>mm(i,p??"",s),[p,i,s]),y=Im({isSlashMode:p!==null,slashItems:f,isSlashLoading:n.isSkillsLoading,onSelectSlashItem:D=>{D.value&&(n.selectedSkills.includes(D.value)||e.chatInputManager.selectSkills([...n.selectedSkills,D.value]),e.chatInputManager.setDraft(""))},onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop,isSending:n.isSending,canStopGeneration:n.canStopGeneration}),m=n.sessionTypeOptions.find(D=>D.value===n.selectedSessionType)??(n.selectedSessionType?{value:n.selectedSessionType,label:n.selectedSessionType}:null),S=n.canEditSessionType&&(n.sessionTypeOptions.length>1||!!(n.selectedSessionType&&n.selectedSessionType!=="native")),g=a.find(D=>D.value===n.selectedModel),k=g==null?void 0:g.thinkingCapability,w=(k==null?void 0:k.supported)??[],E=n.stopDisabledReason==="__preparing__"?R("chatStopPreparing"):((P=n.stopDisabledReason)==null?void 0:P.trim())||R("chatStopUnavailable"),M=[wm({selectedSessionType:n.selectedSessionType,selectedSessionTypeOption:m,sessionTypeOptions:n.sessionTypeOptions,onValueChange:e.chatInputManager.selectSessionType,canEditSessionType:n.canEditSessionType,shouldShow:S,texts:{sessionTypePlaceholder:R("chatSessionTypeLabel")}}),km({modelOptions:a,selectedModel:n.selectedModel,isModelOptionsLoading:u,hasModelOptions:o,onValueChange:e.chatInputManager.selectModel,texts:{modelSelectPlaceholder:R("chatSelectModel"),modelNoOptionsLabel:R("chatModelNoOptions")}}),Cm({supportedLevels:w,selectedThinkingLevel:n.selectedThinkingLevel,defaultThinkingLevel:(k==null?void 0:k.default)??null,onValueChange:D=>e.chatInputManager.selectThinkingLevel(D),texts:{thinkingLabels:Rm()}})].filter(D=>D!==null),I=bm({skillRecords:i,selectedSkills:n.selectedSkills,isLoading:n.isSkillsLoading,onSelectedKeysChange:e.chatInputManager.selectSkills,texts:{title:R("chatSkillsPickerTitle"),searchPlaceholder:R("chatSkillsPickerSearchPlaceholder"),emptyLabel:R("chatSkillsPickerEmpty"),loadingLabel:R("sessionsLoading"),manageLabel:R("chatSkillsPickerManage")}});return h.jsx(Su,{value:n.draft,placeholder:d,disabled:c,onValueChange:e.chatInputManager.setDraft,onKeyDown:y.onTextareaKeyDown,slashMenu:{isOpen:y.isSlashPanelOpen,isLoading:n.isSkillsLoading,items:f,activeIndex:y.activeSlashIndex,activeItem:y.activeSlashItem,texts:{slashLoadingLabel:R("chatSlashLoading"),slashSectionLabel:R("chatSlashSectionSkills"),slashEmptyLabel:R("chatSlashNoResult"),slashHintLabel:R("chatSlashHint"),slashSkillHintLabel:R("chatSlashSkillHint")},onSelectItem:y.onSelectSlashItem,onOpenChange:y.onSlashPanelOpenChange,onSetActiveIndex:y.onSetActiveSlashIndex},hint:Sm({isModelOptionsLoading:u,isModelOptionsEmpty:l,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:R("chatModelNoOptions"),configureProviderLabel:R("chatGoConfigureProvider")}}),selectedItems:{items:ym(n.selectedSkills,i),onRemove:D=>e.chatInputManager.selectSkills(n.selectedSkills.filter(F=>F!==D))},toolbar:{selects:M,accessories:[{key:"attach",label:R("chatInputAttachComingSoon"),icon:"paperclip",disabled:!0,tooltip:R("chatInputAttachComingSoon")}],skillPicker:I,actions:{sendError:n.sendError,isSending:n.isSending,canStopGeneration:n.canStopGeneration,sendDisabled:n.draft.trim().length===0||!o||n.sessionTypeUnavailable,stopDisabled:!n.canStopGeneration,stopHint:E,sendButtonLabel:R("chatSend"),stopButtonLabel:R("chatStop"),onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}})}function He(e){return typeof e=="function"}function Pa(e){var t=function(r){Error.call(r),r.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var yn=Pa(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
35
|
-
`+n.map(function(r,s){return s+1+") "+r.toString()}).join(`
|
|
36
|
-
`):"",this.name="UnsubscriptionError",this.errors=n}});function $n(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Xt=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,r,s,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var o=vn(a),u=o.next();!u.done;u=o.next()){var l=u.value;l.remove(this)}}catch(m){t={error:m}}finally{try{u&&!u.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}else a.remove(this);var c=this.initialTeardown;if(He(c))try{c()}catch(m){i=m instanceof yn?m.errors:[m]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var p=vn(d),f=p.next();!f.done;f=p.next()){var y=f.value;try{Is(y)}catch(m){i=i??[],m instanceof yn?i=Cn(Cn([],In(i)),In(m.errors)):i.push(m)}}}catch(m){r={error:m}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}if(i)throw new yn(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Is(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&$n(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&$n(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),ja=Xt.EMPTY;function Da(e){return e instanceof Xt||e&&"closed"in e&&He(e.remove)&&He(e.add)&&He(e.unsubscribe)}function Is(e){He(e)?e():e.unsubscribe()}var Lm={Promise:void 0},Nm={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Cn([e,t],In(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function Pm(e){Nm.setTimeout(function(){throw e})}function Ts(){}function Dt(e){e()}var _a=(function(e){kt(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Da(n)&&n.add(r)):r.destination=_m,r}return t.create=function(n,r,s){return new Un(n,r,s)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(Xt),jm=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(r){Lt(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){Lt(r)}else Lt(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Lt(n)}},e})(),Un=(function(e){kt(t,e);function t(n,r,s){var i=e.call(this)||this,a;return He(n)||!n?a={next:n??void 0,error:r??void 0,complete:s??void 0}:a=n,i.destination=new jm(a),i}return t})(_a);function Lt(e){Pm(e)}function Dm(e){throw e}var _m={closed:!0,next:Ts,error:Dm,complete:Ts},Om=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function zm(e){return e}function Fm(e){return e.length===0?zm:e.length===1?e[0]:function(n){return e.reduce(function(r,s){return s(r)},n)}}var Ut=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,r){var s=this,i=$m(t)?t:new Un(t,n,r);return Dt(function(){var a=s,o=a.operator,u=a.source;i.add(o?o.call(i,u):u?s._subscribe(i):s._trySubscribe(i))}),i},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var r=this;return n=Rs(n),new n(function(s,i){var a=new Un({next:function(o){try{t(o)}catch(u){i(u),a.unsubscribe()}},error:i,complete:s});r.subscribe(a)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Om]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Fm(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=Rs(t),new t(function(r,s){var i;n.subscribe(function(a){return i=a},function(a){return s(a)},function(){return r(i)})})},e.create=function(t){return new e(t)},e})();function Rs(e){var t;return(t=e??Lm.Promise)!==null&&t!==void 0?t:Promise}function Bm(e){return e&&He(e.next)&&He(e.error)&&He(e.complete)}function $m(e){return e&&e instanceof _a||Bm(e)&&Da(e)}var Um=Pa(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),$e=(function(e){kt(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var r=new Ms(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new Um},t.prototype.next=function(n){var r=this;Dt(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var a=vn(r.currentObservers),o=a.next();!o.done;o=a.next()){var u=o.value;u.next(n)}}catch(l){s={error:l}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(s)throw s.error}}}})},t.prototype.error=function(n){var r=this;Dt(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var s=r.observers;s.length;)s.shift().error(n)}})},t.prototype.complete=function(){var n=this;Dt(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var r=this,s=this,i=s.hasError,a=s.isStopped,o=s.observers;return i||a?ja:(this.currentObservers=null,o.push(n),new Xt(function(){r.currentObservers=null,$n(o,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,s=r.hasError,i=r.thrownError,a=r.isStopped;s?n.error(i):a&&n.complete()},t.prototype.asObservable=function(){var n=new Ut;return n.source=this,n},t.create=function(n,r){return new Ms(n,r)},t})(Ut),Ms=(function(e){kt(t,e);function t(n,r){var s=e.call(this)||this;return s.destination=n,s.source=r,s}return t.prototype.next=function(n){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,n)},t.prototype.error=function(n){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,n)},t.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},t.prototype._subscribe=function(n){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&s!==void 0?s:ja},t})($e),nt=(function(e){kt(t,e);function t(n){var r=e.call(this)||this;return r._value=n,r}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var r=e.prototype._subscribe.call(this,n);return!r.closed&&n.next(this._value),r},t.prototype.getValue=function(){var n=this,r=n.hasError,s=n.thrownError,i=n._value;if(r)throw s;return this._throwIfClosed(),i},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})($e);const de=[];for(let e=0;e<256;++e)de.push((e+256).toString(16).slice(1));function Hm(e,t=0){return(de[e[t+0]]+de[e[t+1]]+de[e[t+2]]+de[e[t+3]]+"-"+de[e[t+4]]+de[e[t+5]]+"-"+de[e[t+6]]+de[e[t+7]]+"-"+de[e[t+8]]+de[e[t+9]]+"-"+de[e[t+10]]+de[e[t+11]]+de[e[t+12]]+de[e[t+13]]+de[e[t+14]]+de[e[t+15]]).toLowerCase()}let xn;const Km=new Uint8Array(16);function Vm(){if(!xn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");xn=crypto.getRandomValues.bind(crypto)}return xn(Km)}const qm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),As={randomUUID:qm};function Hn(e,t,n){var s;if(As.randomUUID&&!e)return As.randomUUID();e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??Vm();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Hm(r)}var ae=(e=>(e.CALL="call",e.RESULT="result",e.PARTIAL_CALL="partial-call",e.ERROR="error",e.CANCELLED="cancelled",e))(ae||{}),W=(e=>(e.TEXT_START="TEXT_START",e.TEXT_DELTA="TEXT_DELTA",e.TEXT_END="TEXT_END",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_ARGS_DELTA="TOOL_CALL_ARGS_DELTA",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.RUN_METADATA="RUN_METADATA",e.REASONING_START="REASONING_START",e.REASONING_DELTA="REASONING_DELTA",e.REASONING_END="REASONING_END",e))(W||{});function Wm(e){return!e||e.remoteStopCapable&&e.remoteRunId?null:e.remoteStopCapable?"__preparing__":e.remoteStopReason??""}const Gm=e=>{try{return JSON.parse(e)}catch{return}},Es=e=>({toolCallId:e.id,toolName:e.function.name,args:e.function.arguments,parsedArgs:Gm(e.function.arguments),status:ae.CALL});function Qm(e,t){const n={error:"tool_call_interrupted",note:"User continued before tool produced a result."};return e.map(r=>{var s;return(s=r.parts)!=null&&s.length?{...r,parts:r.parts.map(i=>{if(i.type!=="tool-invocation"||![ae.CALL,ae.PARTIAL_CALL].includes(i.toolInvocation.status))return i;let a;if(typeof i.toolInvocation.args=="string")try{a=JSON.parse(i.toolInvocation.args)}catch{return{...i,toolInvocation:{...i.toolInvocation,args:JSON.stringify({}),parsedArgs:a,status:ae.RESULT,result:{error:"invalid_args",raw:i.toolInvocation.args}}}}return{...i,toolInvocation:{...i.toolInvocation,args:i.toolInvocation.args,parsedArgs:a,status:ae.RESULT,result:n}}})}:r})}function Kn(e){if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e instanceof Error){if(e.name==="AbortError")return!0;const t=e.message.toLowerCase();return t.includes("aborted")||t.includes("abort")}return!1}function Ls(e){if(e instanceof Error){const n=e.message.trim();if(n)return n}return String(e??"").trim()||"Failed to send message"}function Ns(e,t){return{id:`local-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,role:"assistant",parts:[{type:"text",text:e}],meta:{source:"local",status:(t==null?void 0:t.status)??"final",sessionKey:t==null?void 0:t.sessionKey,timestamp:new Date().toISOString()}}}class Xm{constructor(t){j(this,"currentMessageId");j(this,"currentReasoningMessageId");j(this,"currentReasoningContent","");j(this,"currentToolCallId");j(this,"currentToolCallMessageId");j(this,"currentToolCallName");j(this,"currentToolCallArgs","");j(this,"emittedToolCallIds",new Set);this.sessionManager=t}findAssistantMessageById(t){const n=t==null?void 0:t.trim();return n?this.sessionManager.getMessages().find(s=>s.role==="assistant"&&s.id===n)??null:null}findAssistantMessageByToolCallId(t){var r;if(!t)return null;const n=this.sessionManager.getMessages();for(let s=n.length-1;s>=0;s-=1){const i=n[s];if(i.role!=="assistant")continue;if((r=i.parts)==null?void 0:r.some(o=>o.type==="tool-invocation"&&o.toolInvocation.toolCallId===t))return i}return null}findAssistantMessageForCurrentTool(t){var r;const n=this.findAssistantMessageById(this.currentToolCallMessageId);return(r=n==null?void 0:n.parts)!=null&&r.some(s=>s.type==="tool-invocation"&&s.toolInvocation.toolCallId===t)?n:this.findAssistantMessageByToolCallId(t)}reset(){this.currentMessageId=void 0,this.currentReasoningMessageId=void 0,this.currentReasoningContent="",this.currentToolCallId=void 0,this.currentToolCallMessageId=void 0,this.currentToolCallName=void 0,this.currentToolCallArgs="",this.emittedToolCallIds.clear()}emitToolCallEvents(){const t=this.sessionManager.getMessages();for(const n of t)if(!(n.role!=="assistant"||!n.parts))for(const r of n.parts){if(r.type!=="tool-invocation")continue;const s=r.toolInvocation;s.status===ae.CALL&&!this.emittedToolCallIds.has(s.toolCallId)&&(this.emittedToolCallIds.add(s.toolCallId),this.sessionManager.toolCall$.next({toolCall:{id:s.toolCallId,type:"function",function:{name:s.toolName,arguments:s.args}}}))}}handleEvent(t){switch(t.type){case W.RUN_STARTED:break;case W.TEXT_START:this.handleTextStart(t);break;case W.TEXT_DELTA:this.handleTextContent(t);break;case W.TEXT_END:this.handleTextEnd();break;case W.REASONING_START:this.handleReasoningStart(t);break;case W.REASONING_DELTA:this.handleReasoningContent(t);break;case W.REASONING_END:this.handleReasoningEnd();break;case W.TOOL_CALL_START:this.handleToolCallStart(t);break;case W.TOOL_CALL_ARGS_DELTA:this.handleToolCallArgsDelta(t);break;case W.TOOL_CALL_ARGS:this.handleToolCallArgs(t);break;case W.TOOL_CALL_END:this.handleToolCallEnd(),this.emitToolCallEvents();break;case W.TOOL_CALL_RESULT:this.handleToolCallResult(t);break}}handleTextStart(t){this.currentMessageId=t.messageId}appendTextDelta(t,n){const r=[...t.parts||[]],s=r[r.length-1];return s&&s.type==="text"?{...t,parts:[...r.slice(0,-1),{type:"text",text:`${s.text}${n}`}]}:{...t,parts:[...r,{type:"text",text:n}]}}handleTextContent(t){if(!t.delta||this.currentMessageId!==t.messageId)return;const r=this.sessionManager.getMessages().find(s=>s.role==="assistant"&&s.id===this.currentMessageId);r?this.sessionManager.updateMessage(this.appendTextDelta(r,t.delta)):this.sessionManager.addMessages([{id:this.currentMessageId,role:"assistant",parts:[{type:"text",text:t.delta}]}])}handleTextEnd(){this.currentMessageId=void 0}updateReasoningPart(t,n){var i;const r=[...t.parts||[]];let s=-1;for(let a=r.length-1;a>=0;a-=1)if(((i=r[a])==null?void 0:i.type)==="reasoning"){s=a;break}return s>=0?{...t,parts:[...r.slice(0,s),{type:"reasoning",reasoning:n,details:[]},...r.slice(s+1)]}:{...t,parts:[...r,{type:"reasoning",reasoning:n,details:[]}]}}handleReasoningStart(t){this.currentReasoningMessageId=t.messageId,this.currentReasoningContent=""}handleReasoningContent(t){if(!t.delta||this.currentReasoningMessageId!==t.messageId)return;this.currentReasoningContent+=t.delta;const n=this.currentReasoningContent,r=this.currentReasoningMessageId,i=this.sessionManager.getMessages().find(a=>a.role==="assistant"&&a.id===r);i?this.sessionManager.updateMessage(this.updateReasoningPart(i,n)):this.sessionManager.addMessages([{id:r,role:"assistant",parts:[{type:"reasoning",reasoning:n,details:[]}]}])}handleReasoningEnd(){this.currentReasoningMessageId=void 0,this.currentReasoningContent=""}handleToolCallStart(t){var u;this.currentToolCallId=t.toolCallId,this.currentToolCallName=t.toolName,this.currentToolCallArgs="",this.currentToolCallMessageId=t.messageId;const n={type:"tool-invocation",toolInvocation:{status:ae.PARTIAL_CALL,toolCallId:this.currentToolCallId,toolName:this.currentToolCallName,args:""}},r=this.sessionManager.getMessages(),s=(u=t.messageId)==null?void 0:u.trim(),i=this.findAssistantMessageById(s);if(i){this.currentToolCallMessageId=i.id;const l=i.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);if(l&&l.type==="tool-invocation"){this.currentToolCallArgs=l.toolInvocation.args;return}this.sessionManager.updateMessage({...i,parts:[...i.parts||[],n]});return}if(s){this.currentToolCallMessageId=s,this.sessionManager.addMessages([{id:s,role:"assistant",parts:[n]}]);return}const a=this.findAssistantMessageByToolCallId(this.currentToolCallId);if(a){this.currentToolCallMessageId=a.id;const l=a.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);this.currentToolCallArgs=(l==null?void 0:l.type)==="tool-invocation"?l.toolInvocation.args:"";return}const o=r[r.length-1];if(o&&o.role==="assistant")this.currentToolCallMessageId=o.id,this.sessionManager.updateMessage({...o,parts:[...o.parts||[],n]});else{const l=Hn();this.currentToolCallMessageId=l,this.sessionManager.addMessages([{id:l,role:"assistant",parts:[n]}])}}handleToolCallArgsDelta(t){var s;if(this.currentToolCallId!==t.toolCallId)return;this.currentToolCallArgs+=t.argsDelta;const n=this.findAssistantMessageForCurrentTool(t.toolCallId);if(!n||n.role!=="assistant"||!((s=n.parts)!=null&&s.length))return;const r=[...n.parts];for(let i=r.length-1;i>=0;i--){const a=r[i];if(a.type==="tool-invocation"&&a.toolInvocation.toolCallId===t.toolCallId){let o;try{o=JSON.parse(this.currentToolCallArgs)}catch{}r[i]={...a,toolInvocation:{...a.toolInvocation,status:ae.PARTIAL_CALL,args:this.currentToolCallArgs,parsedArgs:o}};break}}this.sessionManager.updateMessage({...n,parts:r})}handleToolCallArgs(t){this.currentToolCallId===t.toolCallId&&(this.currentToolCallArgs=t.args,this.handleToolCallArgsDelta({type:W.TOOL_CALL_ARGS_DELTA,toolCallId:t.toolCallId,argsDelta:""}))}handleToolCallEnd(){var t;if(!(!this.currentToolCallId||!this.currentToolCallName)){try{const n={id:this.currentToolCallId,type:"function",function:{name:this.currentToolCallName,arguments:this.currentToolCallArgs}},r=this.findAssistantMessageForCurrentTool(this.currentToolCallId);if(r&&r.role==="assistant"){const s=[...r.parts||[]];for(let i=s.length-1;i>=0;i--){const a=s[i];if(a.type==="tool-invocation"&&a.toolInvocation.toolCallId===this.currentToolCallId){s[i]={...a,toolInvocation:{...Es(n),status:ae.CALL}};break}}this.sessionManager.updateMessage({...r,parts:s})}else{const s=((t=this.currentToolCallMessageId)==null?void 0:t.trim())||Hn();this.sessionManager.addMessages([{id:s,role:"assistant",parts:[{type:"tool-invocation",toolInvocation:{...Es(n),status:ae.CALL}}]}])}}catch{}this.currentToolCallId=void 0,this.currentToolCallMessageId=void 0,this.currentToolCallName=void 0,this.currentToolCallArgs=""}}handleToolCallResult(t){this.sessionManager.addToolResult({toolCallId:t.toolCallId,result:t.content,status:ae.RESULT})}}class Ym{constructor(){j(this,"disposables",[]);j(this,"addDisposable",t=>{this.disposables.push(t)});j(this,"dispose",()=>{this.disposables.forEach(t=>t()),this.disposables=[]})}}class Jm extends Ym{constructor(n=null,r){super();j(this,"_messages$",new nt([]));j(this,"messages$");j(this,"threadId$",new nt(null));j(this,"isAgentResponding$",new nt(!1));j(this,"activeRun$",new nt(null));j(this,"lastError$",new nt(null));j(this,"isAwaitingResponse$",new nt(!1));j(this,"runCompleted$",new $e);j(this,"runError$",new $e);j(this,"runMetadata$",new $e);j(this,"activeSubscription",null);j(this,"addMessagesEvent$",new $e);j(this,"updateMessageEvent$",new $e);j(this,"setMessagesEvent$",new $e);j(this,"toolCall$",new $e);j(this,"eventHandler",new Xm(this));j(this,"runIdCounter",0);j(this,"metadataParsers");j(this,"callbacks");j(this,"getMessages",()=>this._messages$.getValue());j(this,"setMessages",n=>{this._messages$.next(n),this.setMessagesEvent$.next({messages:n})});j(this,"handleEvent",n=>{this.eventHandler.handleEvent(n)});j(this,"setCallbacks",n=>{this.callbacks=n});j(this,"reset",()=>{this.abortAgentRun(),this._messages$.next([]),this.eventHandler.reset(),this.threadId$.next(null),this.isAgentResponding$.next(!1),this.activeRun$.next(null),this.lastError$.next(null),this.isAwaitingResponse$.next(!1),this.runIdCounter+=1});j(this,"addMessages",n=>{const s=[...this.getMessages()];for(const i of n){const a=s.findIndex(o=>o.id===i.id);a>=0?s[a]=i:s.push(i)}this._messages$.next(s),this.addMessagesEvent$.next({messages:n}),this.isAwaitingResponse$.getValue()&&n.some(i=>i.role==="assistant")&&this.isAwaitingResponse$.next(!1)});j(this,"removeMessages",n=>{n.length!==0&&this._messages$.next(this.getMessages().filter(r=>!n.includes(r.id)))});j(this,"updateMessage",n=>{this._messages$.next(this.getMessages().map(r=>r.id===n.id?n:r)),this.updateMessageEvent$.next({message:n}),this.isAwaitingResponse$.getValue()&&n.role==="assistant"&&this.isAwaitingResponse$.next(!1)});j(this,"addToolResult",(n,r)=>{const s=this.getMessages().find(a=>a.parts.find(o=>o.type==="tool-invocation"&&o.toolInvocation.toolCallId===n.toolCallId));if(!s)return;const i={...s,parts:s.parts.map(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===n.toolCallId?{...a,toolInvocation:{...a.toolInvocation,result:n.result??void 0,status:n.status,error:n.error??void 0,cancelled:n.cancelled??void 0}}:a)};this.updateMessage(i)});j(this,"send",async n=>{(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun(),this.lastError$.next(null);const r=n.message.trim();r&&(this.addMessages([{id:Hn(),role:"user",parts:[{type:"text",text:r}]}]),await this.runAgent({metadata:n.metadata,sessionId:n.sessionId,agentId:n.agentId,stopCapable:n.stopCapable,stopReason:n.stopReason,sourceMessage:r,restoreDraftOnError:n.restoreDraftOnError}))});j(this,"resume",async n=>{var a,o;const r=(a=n.remoteRunId)==null?void 0:a.trim(),s=(o=n.sessionId)==null?void 0:o.trim();if(!r)return;const i=this.activeRun$.getValue();(i==null?void 0:i.remoteRunId)!==r&&(i||(this.lastError$.next(null),await this.runAgent({metadata:n.metadata,sessionId:s,agentId:n.agentId,stopCapable:n.stopCapable,stopReason:n.stopReason})))});j(this,"stop",async()=>{var s,i;const n=this.activeRun$.getValue();if(!n)return;const r=n.sessionId;this.abortAgentRun(),r&&await((i=(s=this.callbacks).onRunSettled)==null?void 0:i.call(s,{sourceSessionId:r}))});j(this,"handleAgentResponse",n=>{this.activeSubscription&&this.activeSubscription.unsubscribe(),this.activeSubscription=n.subscribe(r=>{var s,i,a,o,u,l,c,d,p;if(r.type===W.RUN_METADATA){const f=r,y=this.activeRun$.getValue(),m=((s=f.runId)==null?void 0:s.trim())||(y?`ui-${y.localRunId}`:"");this.metadataParsers&&y&&this.isMatchingRun(y,m)&&this.processRunMetadata(y,f.metadata),this.runMetadata$.next({runId:m,metadata:f.metadata});return}if(this.handleEvent(r),r.type===W.RUN_FINISHED){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),y=((i=r.runId)==null?void 0:i.trim())||(f?`ui-${f.localRunId}`:"");if(!f||!this.isMatchingRun(f,y))return;const m=f.sessionId;this.activeRun$.next(null),m&&((o=(a=this.callbacks).onRunSettled)==null||o.call(a,{sourceSessionId:m}))}else if(r.type===W.RUN_ERROR){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),y=((u=r.runId)==null?void 0:u.trim())||(f?`ui-${f.localRunId}`:""),m=Kn(r.error);if(this.runError$.next({runId:y,error:r.error,isAbort:m}),!f||!this.isMatchingRun(f,y)){this.activeRun$.next(null);return}const S=f.sessionId;if(m){this.activeRun$.next(null),S&&((c=(l=this.callbacks).onRunSettled)==null||c.call(l,{sourceSessionId:S}));return}const g=Ls(r.error);this.lastError$.next(g),this.activeRun$.next(null),S&&this.addMessages([Ns(g,{sessionKey:S,status:"error"})]),(p=(d=this.callbacks).onRunError)==null||p.call(d,{error:g,sourceMessage:f.sourceMessage,restoreDraft:f.restoreDraftOnError})}})});j(this,"abortAgentRun",()=>{var n,r,s;(s=(n=this.agentProvider)==null?void 0:(r=n.agent).abortRun)==null||s.call(r),this.activeSubscription&&(this.activeSubscription.unsubscribe(),this.activeSubscription=null,this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1)),this.activeRun$.next(null)});j(this,"runAgent",async n=>{var a,o,u,l;if(!this.agentProvider)return;(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun();const r=++this.runIdCounter,s=`ui-${r}`,i={localRunId:r,sessionId:n==null?void 0:n.sessionId,...n!=null&&n.agentId?{agentId:n.agentId}:{},remoteStopCapable:!!(n!=null&&n.stopCapable),...n!=null&&n.stopReason?{remoteStopReason:n.stopReason}:{},sourceMessage:n==null?void 0:n.sourceMessage,restoreDraftOnError:n==null?void 0:n.restoreDraftOnError};this.activeRun$.next(i),this.isAgentResponding$.next(!0),this.isAwaitingResponse$.next(!0);try{const c=Qm(this.getMessages()),d=typeof(n==null?void 0:n.threadId)=="string"&&n.threadId.trim()?n.threadId:this.threadId$.getValue()??"",p=await this.agentProvider.agent.run({threadId:d,runId:s,messages:c,tools:this.agentProvider.getToolDefs(),context:this.agentProvider.getContexts(),...n!=null&&n.metadata?{metadata:n.metadata}:{}});this.handleAgentResponse(p)}catch(c){const d=Kn(c);d?console.info("Agent run aborted"):console.error("Error running agent:",c),this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1);const p=this.activeRun$.getValue();if(this.activeRun$.next(null),this.runError$.next({runId:s,error:c,isAbort:d}),!d&&p){const f=Ls(c);this.lastError$.next(f),p.sessionId&&this.addMessages([Ns(f,{sessionKey:p.sessionId,status:"error"})]),(o=(a=this.callbacks).onRunError)==null||o.call(a,{error:f,sourceMessage:p.sourceMessage,restoreDraft:p.restoreDraftOnError})}else d&&(p!=null&&p.sessionId)&&((l=(u=this.callbacks).onRunSettled)==null||l.call(u,{sourceSessionId:p.sessionId}))}});j(this,"processRunMetadata",(n,r)=>{if(!this.metadataParsers)return;const s=this.metadataParsers.parseReady(r);if(s){this.applyReadyMetadata(n,s);return}const i=this.metadataParsers.parseFinal(r);i&&this.applyFinalMetadata(n,i)});j(this,"applyReadyMetadata",(n,r)=>{var i,a,o,u,l;const s={...n};(i=r.remoteRunId)!=null&&i.trim()&&(s.remoteRunId=r.remoteRunId.trim()),typeof r.stopCapable=="boolean"&&(s.remoteStopCapable=r.stopCapable),(a=r.stopReason)!=null&&a.trim()&&(s.remoteStopReason=r.stopReason.trim()),(o=r.sessionId)!=null&&o.trim()&&(s.sessionId=r.sessionId.trim(),(l=(u=this.callbacks).onSessionChanged)==null||l.call(u,s.sessionId)),this.activeRun$.next(s)});j(this,"applyFinalMetadata",(n,r)=>{var a,o,u,l;const s=n.sessionId,i=r.sessionId;i&&i!==s&&((o=(a=this.callbacks).onSessionChanged)==null||o.call(a,i)),this.activeRun$.next(null),s&&((l=(u=this.callbacks).onRunSettled)==null||l.call(u,{sourceSessionId:s,resultSessionId:i}))});j(this,"isMatchingRun",(n,r)=>r.trim()?r===`ui-${n.localRunId}`:!1);j(this,"connectToolExecutor",()=>{const n=this.toolCall$.subscribe(async({toolCall:r})=>{var i;const s=(i=this.agentProvider)==null?void 0:i.getToolExecutor(r.function.name);if(s)try{const a=JSON.parse(r.function.arguments),o=await s(a);this.addToolResult({toolCallId:r.id,result:o,status:ae.RESULT}),this.runAgent()}catch(a){console.error("[AgentChatController] handleAddToolResult error",a),this.addToolResult({toolCallId:r.id,error:a instanceof Error?a.message:String(a),status:ae.ERROR}),this.runAgent()}});return()=>n.unsubscribe()});this.agentProvider=n;const{initialMessages:s=[],metadataParsers:i,callbacks:a={}}=r||{};this.metadataParsers=i??null,this.callbacks=a,this._messages$.next(s),this.messages$=this._messages$.asObservable(),this.agentProvider&&this.addDisposable(this.connectToolExecutor())}}function Zm(e){return typeof e=="object"&&e!==null}function ey(e){return e.type==="text"&&typeof e.text=="string"}function ty(e){return e.type==="reasoning"&&typeof e.reasoning=="string"}function ny(e){return e.type!=="tool-invocation"||!Zm(e.toolInvocation)?!1:typeof e.toolInvocation.toolName=="string"}function ry(e){var n;const t=(n=e.meta)==null?void 0:n.timestamp;return t&&Number.isFinite(Date.parse(t))?t:new Date().toISOString()}function sy(e,t){return e==="user"?t.user:e==="assistant"?t.assistant:e==="tool"?t.tool:e==="system"?t.system:t.fallback}function iy(e){return e==="user"||e==="assistant"||e==="tool"||e==="system"?e:"message"}function ay(e,t){return{kind:e.kind,toolName:e.name,summary:e.detail,output:e.text,hasResult:!!e.hasResult,titleLabel:e.kind==="call"?t.toolCallLabel:t.toolResultLabel,outputLabel:t.toolOutputLabel,emptyLabel:t.toolNoOutputLabel}}function oy(e){return e.uiMessages.map(t=>{var n;return{id:t.id,role:iy(t.role),roleLabel:sy(t.role,e.texts.roleLabels),timestampLabel:e.formatTimestamp(ry(t)),status:(n=t.meta)==null?void 0:n.status,parts:t.parts.map(r=>{if(ey(r)){const s=r.text.trim();return s?{type:"markdown",text:s}:null}if(ty(r)){const s=r.reasoning.trim();return s?{type:"reasoning",text:s,label:e.texts.reasoningLabel}:null}if(ny(r)){const s=r.toolInvocation,i=yl(s.parsedArgs??s.args),a=typeof s.error=="string"&&s.error.trim()?s.error.trim():s.result!=null?Tr(s.result).trim():"",o=s.status==="result"||s.status==="error"||s.status==="cancelled",u={kind:o?"result":"call",name:s.toolName,detail:i,text:a||void 0,callId:s.toolCallId||void 0,hasResult:o};return{type:"tool-card",card:ay(u,e.texts)}}return{type:"unknown",label:e.texts.unknownPartLabel,rawType:typeof r.type=="string"?r.type:"unknown",text:Tr(r)}}).filter(r=>r!==null)}})}function ly(e){const{language:t}=Zn(),n=v.useMemo(()=>e.uiMessages.map(s=>{var i,a;return{id:s.id,role:s.role,meta:{timestamp:(i=s.meta)==null?void 0:i.timestamp,status:(a=s.meta)==null?void 0:a.status},parts:s.parts}}),[e.uiMessages]),r=v.useMemo(()=>oy({uiMessages:n,formatTimestamp:s=>Kt(s,t),texts:{roleLabels:{user:R("chatRoleUser"),assistant:R("chatRoleAssistant"),tool:R("chatRoleTool"),system:R("chatRoleSystem"),fallback:R("chatRoleMessage")},reasoningLabel:R("chatReasoning"),toolCallLabel:R("chatToolCall"),toolResultLabel:R("chatToolResult"),toolNoOutputLabel:R("chatToolNoOutput"),toolOutputLabel:R("chatToolOutput"),unknownPartLabel:R("chatUnknownPart")}}),[t,n]);return h.jsx(dm,{messages:r,isSending:e.isSending,hasAssistantDraft:e.uiMessages.some(s=>{var i,a;return s.role==="assistant"&&(((i=s.meta)==null?void 0:i.status)==="streaming"||((a=s.meta)==null?void 0:a.status)==="pending")}),className:e.className,texts:{copyCodeLabel:R("chatCodeCopy"),copiedCodeLabel:R("chatCodeCopied"),typingLabel:R("chatTyping")}})}const uy=[{icon:zo,titleKey:"chatWelcomeCapability1Title",descKey:"chatWelcomeCapability1Desc"},{icon:Qn,titleKey:"chatWelcomeCapability2Title",descKey:"chatWelcomeCapability2Desc"},{icon:Gn,titleKey:"chatWelcomeCapability3Title",descKey:"chatWelcomeCapability3Desc"}];function cy({onCreateSession:e}){return h.jsx("div",{className:"h-full flex items-center justify-center p-8",children:h.jsxs("div",{className:"max-w-lg w-full text-center",children:[h.jsx("div",{className:"mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:h.jsx(Zs,{className:"h-8 w-8 text-primary"})}),h.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:R("chatWelcomeTitle")}),h.jsx("p",{className:"text-sm text-gray-500 mb-8",children:R("chatWelcomeSubtitle")}),h.jsx("div",{className:"grid grid-cols-3 gap-3",children:uy.map(t=>{const n=t.icon;return h.jsxs("button",{onClick:e,className:"rounded-2xl border border-gray-200 bg-white p-4 text-left shadow-card hover:shadow-card-hover transition-shadow cursor-pointer",children:[h.jsx("div",{className:"h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3",children:h.jsx(n,{className:"h-4.5 w-4.5 text-primary"})}),h.jsx("div",{className:"text-sm font-semibold text-gray-900 mb-1",children:R(t.titleKey)}),h.jsx("div",{className:"text-[11px] text-gray-500 leading-relaxed",children:R(t.descKey)})]},t.titleKey)})})]})})}const dy={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,selectedSessionKey:null,sessionDisplayName:void 0,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,uiMessages:[],isSending:!1,isAwaitingAssistantOutput:!1},Ue=Ht(e=>({snapshot:dy,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function hy(){return h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsxs("div",{className:"space-y-4",children:[h.jsx("div",{className:"h-6 w-48 animate-pulse rounded bg-gray-200"}),h.jsx("div",{className:"h-24 w-[78%] animate-pulse rounded-2xl bg-gray-200/80"}),h.jsx("div",{className:"h-20 w-[62%] animate-pulse rounded-2xl bg-gray-200/80"}),h.jsx("div",{className:"h-28 w-[84%] animate-pulse rounded-2xl bg-gray-200/80"})]})})}),h.jsx("div",{className:"border-t border-gray-200/80 bg-white p-4",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)]",children:h.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white shadow-card p-4",children:[h.jsx("div",{className:"h-16 w-full animate-pulse rounded-xl bg-gray-200/80"}),h.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[h.jsx("div",{className:"h-8 w-36 animate-pulse rounded-lg bg-gray-200/80"}),h.jsx("div",{className:"h-8 w-20 animate-pulse rounded-lg bg-gray-200/80"})]})]})})})]})}function fy(){var l;const e=er(),t=Ue(c=>c.snapshot),n=v.useRef(null),r=t.threadRef??n,s=!t.selectedSessionKey&&t.uiMessages.length===0&&!t.isSending,i=t.modelOptions.length>0,a=t.isProviderStateResolved&&!i,o=t.isHistoryLoading&&t.uiMessages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:u}=fm({scrollRef:r,resetKey:t.selectedSessionKey,isLoading:t.isHistoryLoading,hasContent:t.uiMessages.length>0,contentVersion:t.uiMessages});return t.isProviderStateResolved?h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsxs("div",{className:Le("px-5 border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200",t.selectedSessionKey?"py-3 opacity-100":"h-0 py-0 opacity-0 border-b-0"),children:[h.jsx("div",{className:"min-w-0 flex-1",children:h.jsx("span",{className:"text-sm font-medium text-gray-700 truncate",children:t.sessionDisplayName||t.selectedSessionKey})}),h.jsx(st,{variant:"ghost",size:"icon",className:"rounded-lg shrink-0 text-gray-400 hover:text-destructive",onClick:e.chatThreadManager.deleteSession,disabled:!t.canDeleteSession||t.isDeletePending,children:h.jsx(ti,{className:"h-4 w-4"})})]}),a&&h.jsxs("div",{className:"px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 flex items-center justify-between gap-3 shrink-0",children:[h.jsx("span",{className:"text-xs text-amber-800",children:R("chatModelNoOptions")}),h.jsx("button",{type:"button",onClick:e.chatThreadManager.goToProviders,className:"text-xs font-semibold text-amber-900 underline-offset-2 hover:underline",children:R("chatGoConfigureProvider")})]}),t.sessionTypeUnavailable&&((l=t.sessionTypeUnavailableMessage)==null?void 0:l.trim())&&h.jsx("div",{className:"px-5 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0",children:h.jsx("span",{className:"text-xs text-amber-800",children:t.sessionTypeUnavailableMessage})}),h.jsx("div",{ref:r,onScroll:u,className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:s?h.jsx(cy,{onCreateSession:e.chatThreadManager.createSession}):o?h.jsx("div",{className:"h-full"}):t.uiMessages.length===0?h.jsx("div",{className:"px-5 py-5 text-sm text-gray-500",children:R("chatNoMessages")}):h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(ly,{uiMessages:t.uiMessages,isSending:t.isSending&&t.isAwaitingAssistantOutput})})}),h.jsx(Em,{})]}):h.jsx(hy,{})}function Ps(e){return Kt(e??void 0)}function py(e){return typeof e!="number"||!Number.isFinite(e)?"-":Kt(new Date(e))}function gy(e){if(typeof e!="number"||!Number.isFinite(e))return"-";const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const r=Math.round(n/60);return r<24?`${r}h`:`${Math.round(r/24)}d`}function my(e){const t=e.schedule;return t.kind==="cron"?t.expr?`cron ${t.expr}`:"cron":t.kind==="every"?`every ${gy(t.everyMs)}`:t.kind==="at"?`at ${py(t.atMs)}`:"-"}function yy(e){if(!e.payload.deliver)return"-";const t=e.payload.channel??"-",n=e.payload.to??"-";return`${t}:${n}`}function xy(e,t){const n=t.trim().toLowerCase();return n?[e.id,e.name,e.payload.message,e.payload.channel??"",e.payload.to??""].join(" ").toLowerCase().includes(n):!0}function by(e,t){return t==="all"?!0:t==="enabled"?e.enabled:!e.enabled}function Sy(){var y;const[e,t]=v.useState(""),[n,r]=v.useState("all"),s=Yo({all:!0}),i=Jo(),a=Zo(),o=el(),{confirm:u,ConfirmDialog:l}=Jn(),c=v.useMemo(()=>{var S;return(((S=s.data)==null?void 0:S.jobs)??[]).filter(g=>xy(g,e)).filter(g=>by(g,n))},[s.data,e,n]),d=async m=>{await u({title:`${R("cronDeleteConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,variant:"destructive",confirmLabel:R("delete")})&&i.mutate({id:m.id})},p=async m=>{const S=!m.enabled;await u({title:S?`${R("cronEnableConfirm")}?`:`${R("cronDisableConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,variant:S?"default":"destructive",confirmLabel:S?R("cronEnable"):R("cronDisable")})&&a.mutate({id:m.id,enabled:S})},f=async m=>{const S=!m.enabled;await u({title:S?`${R("cronRunForceConfirm")}?`:`${R("cronRunConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,confirmLabel:R("cronRunNow")})&&o.mutate({id:m.id,force:S})};return h.jsxs(Ll,{fullHeight:!0,children:[h.jsx(Nl,{title:R("cronPageTitle"),description:R("cronPageDescription"),actions:h.jsx(st,{variant:"ghost",size:"icon",className:"h-9 w-9 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100",onClick:()=>s.refetch(),children:h.jsx(Fo,{className:Le("h-4 w-4",s.isFetching&&"animate-spin")})})}),h.jsx("div",{className:"mb-6",children:h.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[h.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[h.jsx(ai,{value:e,onChange:m=>t(m.target.value),placeholder:R("cronSearchPlaceholder"),className:"pl-9"}),h.jsx(Gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"})]}),h.jsx("div",{className:"min-w-[180px]",children:h.jsxs(Tn,{value:n,onValueChange:m=>r(m),children:[h.jsx(Rn,{className:"w-full",children:h.jsx(tl,{placeholder:R("cronStatusLabel")})}),h.jsxs(Mn,{children:[h.jsx(gt,{value:"all",children:R("cronStatusAll")}),h.jsx(gt,{value:"enabled",children:R("cronStatusEnabled")}),h.jsx(gt,{value:"disabled",children:R("cronStatusDisabled")})]})]})}),h.jsxs("div",{className:"text-xs text-gray-500 ml-auto",children:[R("cronTotalLabel"),": ",((y=s.data)==null?void 0:y.total)??0," / ",c.length]})]})}),h.jsx("div",{className:"flex-1 overflow-auto custom-scrollbar",children:s.isLoading?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:R("cronLoading")}):c.length===0?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:R("cronEmpty")}):h.jsx("div",{className:"space-y-4",children:c.map(m=>h.jsx(nl,{className:"border border-gray-200",children:h.jsx(rl,{className:"pt-5 pb-5",children:h.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[h.jsxs("div",{className:"min-w-[220px] flex-1",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:m.name||m.id}),h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500",children:m.id}),h.jsx("span",{className:Le("text-[10px] font-semibold px-2 py-0.5 rounded-full",m.enabled?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"),children:m.enabled?R("enabled"):R("disabled")}),m.deleteAfterRun&&h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:R("cronOneShot")})]}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[R("cronScheduleLabel"),": ",my(m)]}),h.jsx("div",{className:"mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words",children:m.payload.message}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[R("cronDeliverTo"),": ",yy(m)]})]}),h.jsxs("div",{className:"min-w-[220px] text-xs text-gray-500 space-y-2",children:[h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[R("cronNextRun"),":"]})," ",Ps(m.state.nextRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[R("cronLastRun"),":"]})," ",Ps(m.state.lastRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[R("cronLastStatus"),":"]})," ",m.state.lastStatus??"-"]}),m.state.lastError&&h.jsx("div",{className:"text-[11px] text-red-500 break-words",children:m.state.lastError})]}),h.jsxs("div",{className:"flex items-start gap-2 flex-wrap justify-end",children:[h.jsxs(st,{variant:"subtle",size:"sm",onClick:()=>f(m),className:"gap-1",children:[h.jsx(Bo,{className:"h-3.5 w-3.5"}),R("cronRunNow")]}),h.jsxs(st,{variant:m.enabled?"outline":"primary",size:"sm",onClick:()=>p(m),className:"gap-1",children:[h.jsx($o,{className:"h-3.5 w-3.5"}),m.enabled?R("cronDisable"):R("cronEnable")]}),h.jsxs(st,{variant:"destructive",size:"sm",onClick:()=>d(m),className:"gap-1",children:[h.jsx(ti,{className:"h-3.5 w-3.5"}),R("delete")]})]})]})})},m.id))})}),h.jsx(l,{})]})}function Oa(e){const{view:t,routeSessionKey:n,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:i,setSelectedAgentId:a,selectedSessionKeyRef:o,resetStreamState:u,resolveAgentIdFromSessionKey:l}=e;v.useEffect(()=>{if(t==="chat"){if(n){r!==n&&i(n);return}r!==null&&(i(null),u())}},[u,n,r,i,t]),v.useEffect(()=>{const c=r?l(r):null;c&&s!==c&&a(c)},[l,s,r,a]),v.useEffect(()=>{o.current=r},[r,o])}function za({view:e,confirmDialog:t}){return h.jsxs("div",{className:"h-full flex",children:[h.jsx(Wl,{}),e==="chat"?h.jsx(fy,{}):h.jsx("section",{className:"flex-1 min-h-0 overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:e==="cron"?h.jsx("div",{className:"h-full overflow-auto custom-scrollbar",children:h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Sy,{})})}):h.jsx("div",{className:"h-full overflow-hidden",children:h.jsx("div",{className:"mx-auto flex h-full min-h-0 w-full max-w-[min(1120px,100%)] flex-col px-6 py-5",children:h.jsx(Tl,{forcedType:"skills"})})})}),t]})}const Vn="sid_";function Fa(e){var r;const t=/^agent:([^:]+):/i.exec(e.trim());if(!t)return null;const n=(r=t[1])==null?void 0:r.trim();return n||null}function ky(e){const t=Math.random().toString(36).slice(2,8);return`agent:${e}:ui:direct:web-${Date.now().toString(36)}${t}`}function wy(e){const t=new TextEncoder().encode(e);let n="";for(const s of t)n+=String.fromCharCode(s);const r=btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");return`${Vn}${r}`}function vy(e){if(!e.startsWith(Vn))return null;const t=e.slice(Vn.length).replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?"":"=".repeat(4-t.length%4);try{const r=atob(t+n),s=Uint8Array.from(r,i=>i.charCodeAt(0));return new TextDecoder().decode(s)}catch{return null}}function Ba(e){if(!e)return null;const t=vy(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function Cy(e){return`/chat/${wy(e)}`}class Iy{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=K.getState().snapshot;for(const[i,a]of Object.entries(r))if(!Object.is(s[i],a))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.syncSnapshot=r=>{if(this.hasSnapshotChanges(r)&&(K.getState().setSnapshot(r),Object.prototype.hasOwnProperty.call(r,"modelOptions")||Object.prototype.hasOwnProperty.call(r,"selectedModel")||Object.prototype.hasOwnProperty.call(r,"selectedThinkingLevel"))){const s=K.getState().snapshot;this.reconcileThinkingForModel(s.selectedModel)}},this.setDraft=r=>{const s=K.getState().snapshot.draft,i=this.resolveUpdateValue(s,r);i!==s&&K.getState().setSnapshot({draft:i})},this.setPendingSessionType=r=>{const s=K.getState().snapshot.pendingSessionType,i=this.resolveUpdateValue(s,r);i!==s&&K.getState().setSnapshot({pendingSessionType:i})},this.send=async()=>{const r=K.getState().snapshot,s=re.getState().snapshot,i=r.draft.trim();if(!i)return;const a=r.selectedSkills,o=!!s.selectedSessionKey,u=s.selectedSessionKey??ky(s.selectedAgentId);o||this.uiManager.goToSession(u,{replace:!0}),this.setDraft(""),this.setSelectedSkills([]),await this.streamActionsManager.sendMessage({message:i,sessionKey:u,agentId:s.selectedAgentId,sessionType:r.selectedSessionType,model:r.selectedModel||void 0,thinkingLevel:r.selectedThinkingLevel??void 0,stopSupported:r.stopSupported,stopReason:r.stopReason,requestedSkills:a,restoreDraftOnError:!0})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=r=>{const s=K.getState().snapshot.selectedModel,i=this.resolveUpdateValue(s,r);i!==s&&(K.getState().setSnapshot({selectedModel:i}),this.reconcileThinkingForModel(i))},this.setSelectedThinkingLevel=r=>{const s=K.getState().snapshot.selectedThinkingLevel,i=this.resolveUpdateValue(s,r);i!==s&&K.getState().setSnapshot({selectedThinkingLevel:i})},this.selectSessionType=r=>{const s=qe(r);K.getState().setSnapshot({selectedSessionType:s,pendingSessionType:s}),this.syncRemoteSessionType(s)},this.setSelectedSkills=r=>{const s=K.getState().snapshot.selectedSkills,i=this.resolveUpdateValue(s,r);Object.is(i,s)||K.getState().setSnapshot({selectedSkills:i})},this.selectModel=r=>{this.setSelectedModel(r)},this.selectThinkingLevel=r=>{this.setSelectedThinkingLevel(r)},this.selectSkills=r=>{this.setSelectedSkills(r)},this.syncRemoteSessionType=async r=>{const s=re.getState().snapshot,i=s.selectedSessionKey;if(!i)return;const a=s.sessions.find(o=>o.key===i);a!=null&&a.sessionTypeMutable&&qe(a.sessionType)!==r&&await sl(i,{sessionType:r})}}resolveThinkingForModel(t,n){const r=t==null?void 0:t.thinkingCapability;return!r||r.supported.length===0?null:n==="off"?"off":n&&r.supported.includes(n)?n:r.default&&r.supported.includes(r.default)?r.default:"off"}reconcileThinkingForModel(t){const n=K.getState().snapshot,r=n.modelOptions.find(i=>i.value===t),s=this.resolveThinkingForModel(r,n.selectedThinkingLevel);s!==n.selectedThinkingLevel&&K.getState().setSnapshot({selectedThinkingLevel:s})}}const Ty={parseReady:e=>e.driver!=="nextbot-stream"||e.kind!=="ready"?null:{remoteRunId:typeof e.backendRunId=="string"?e.backendRunId:void 0,sessionId:typeof e.sessionKey=="string"?e.sessionKey:void 0,stopCapable:typeof e.stopSupported=="boolean"?e.stopSupported:void 0,stopReason:typeof e.stopReason=="string"?e.stopReason:void 0},parseFinal:e=>e.driver!=="nextbot-stream"||e.kind!=="final"?null:{sessionId:typeof e.sessionKey=="string"?e.sessionKey:void 0,hasOutput:!!e.hasAssistantSessionEvent}};function Ry(e,t){return{driver:"nextbot-stream",mode:"send",payload:e,requestedSkills:t}}function My(e){const t=Number.isFinite(e.eventCount)&&e.eventCount>0?Math.max(0,Math.trunc(e.eventCount)):void 0;return{driver:"nextbot-stream",mode:"resume",runId:e.runId,...typeof t=="number"?{fromEventIndex:t}:{},sessionKey:e.sessionKey,...e.agentId?{agentId:e.agentId}:{},stopSupported:e.stopSupported,...e.stopReason?{stopReason:e.stopReason}:{}}}function Ay(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const[n,r]of e.entries())if(!Object.is(r,t.get(n)))return!1;return!0}class $a{constructor(){this.syncSnapshot=t=>{const n=An.getState().snapshot,r=t.sessionRunStatusByKey;(!r||Ay(n.sessionRunStatusByKey,r))&&(t.isLocallyRunning===void 0||Object.is(n.isLocallyRunning,t.isLocallyRunning))&&(t.activeBackendRunId===void 0||Object.is(n.activeBackendRunId,t.activeBackendRunId))||An.getState().setSnapshot(t)}}}class Ua{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=re.getState().snapshot;for(const[i,a]of Object.entries(r))if(!Object.is(s[i],a))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.syncSnapshot=r=>{this.hasSnapshotChanges(r)&&re.getState().setSnapshot(r)},this.setSelectedAgentId=r=>{const s=re.getState().snapshot.selectedAgentId,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({selectedAgentId:i})},this.setSelectedSessionKey=r=>{const s=re.getState().snapshot.selectedSessionKey,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({selectedSessionKey:i})},this.createSession=()=>{const r=K.getState().snapshot.defaultSessionType||"native";this.streamActionsManager.resetStreamState(),this.setSelectedSessionKey(null),K.getState().setSnapshot({pendingSessionType:r}),this.uiManager.goToChatRoot()},this.selectSession=r=>{this.setSelectedSessionKey(r),this.uiManager.goToSession(r)},this.setQuery=r=>{const s=re.getState().snapshot.query,i=this.resolveUpdateValue(s,r);i!==s&&re.getState().setSnapshot({query:i})}}}const bn=async()=>{},js=()=>{};class Ha{constructor(){this.actions={sendMessage:bn,stopCurrentRun:bn,resumeRun:bn,resetStreamState:js,applyHistoryMessages:js},this.bind=t=>{this.actions={...this.actions,...t}},this.sendMessage=t=>this.actions.sendMessage(t),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=t=>this.actions.resumeRun(t),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(t,n)=>this.actions.applyHistoryMessages(t,n)}}const Ey=async()=>{};class Ly{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:Ey},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=Ue.getState().snapshot;for(const[a,o]of Object.entries(s))if(!Object.is(i[a],o))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&Ue.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=re.getState();if(!(!s||!await this.uiManager.confirm({title:R("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:R("delete")}))){Ue.getState().setSnapshot({isDeletePending:!0});try{await il(s),this.streamActionsManager.resetStreamState(),re.getState().setSnapshot({selectedSessionKey:null}),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{Ue.getState().setSnapshot({isDeletePending:!1})}}}}}const Ny=async e=>!1;class Ka{constructor(){this.state={pathname:""},this.actions={navigate:null,confirm:Ny},this.syncState=t=>{this.state={...this.state,...t}},this.bindActions=t=>{this.actions={...this.actions,...t}},this.confirm=async t=>this.actions.confirm(t),this.navigateTo=(t,n)=>{this.actions.navigate&&(this.state.pathname===t&&!(n!=null&&n.replace)||(this.actions.navigate(t,n),this.state.pathname=t))},this.goToProviders=()=>{this.navigateTo("/providers")},this.goToChatRoot=t=>{this.navigateTo("/chat",t)},this.goToSession=(t,n)=>{this.navigateTo(Cy(t),n)}}}function Py(e){return e.delta?e.started?[{type:W.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[{type:W.TEXT_START,messageId:e.messageId},{type:W.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[]}function jy(e){return!1}function Dy(e){var n,r;return((r=(n=e.message)==null?void 0:n.role)==null?void 0:r.toLowerCase().trim())==="assistant"}function _y(e){var a;const{event:t,messageId:n}=e,r=t.message;if(!r)return[];const s=(a=r.role)==null?void 0:a.toLowerCase().trim();if(!s)return[];const i=[];if(typeof r.reasoning_content=="string"&&r.reasoning_content.trim()&&(i.push({type:W.REASONING_START,messageId:n}),i.push({type:W.REASONING_DELTA,messageId:n,delta:r.reasoning_content.trim()}),i.push({type:W.REASONING_END,messageId:n})),Array.isArray(r.tool_calls))for(let o=0;o<r.tool_calls.length;o+=1){const u=r.tool_calls[o];if(!u||typeof u!="object")continue;const l=u,c=l.function,d=typeof c=="object"&&c?c:null,p=typeof t.seq=="number"?String(t.seq):"unknown",f=typeof l.id=="string"?l.id:`tool-${p}-${o}`,y=typeof(d==null?void 0:d.name)=="string"?d.name:typeof l.name=="string"?l.name:"tool",m=(d==null?void 0:d.arguments)??l.arguments??"",S=typeof m=="string"?m:JSON.stringify(m??{});i.push({type:W.TOOL_CALL_START,messageId:n,toolCallId:f,toolName:y}),i.push({type:W.TOOL_CALL_ARGS,toolCallId:f,args:S}),i.push({type:W.TOOL_CALL_END,toolCallId:f})}if(s==="tool"||s==="tool_result"||s==="toolresult"||s==="function"){const o=typeof r.tool_call_id=="string"?r.tool_call_id.trim():"";o&&i.push({type:W.TOOL_CALL_RESULT,toolCallId:o,content:r.content})}return i}function Va(){return`stream-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Oy(e,t){const n={};return e.sessionType&&(n.session_type=e.sessionType),e.thinkingLevel&&(n.thinking=e.thinkingLevel),t.length>0&&(n.requested_skills=t),{message:e.message,...e.runId?{runId:e.runId}:{},sessionKey:e.sessionKey,agentId:e.agentId,...e.model?{model:e.model}:{},...Object.keys(n).length>0?{metadata:n}:{},channel:"ui",chatId:"web-ui"}}async function zy(e){return al(Oy(e.item,e.requestedSkills),{signal:e.signal,onReady:e.onReady,onDelta:e.onDelta,onSessionEvent:e.onSessionEvent})}async function Fy(e){return ol({runId:e.runId,...typeof e.fromEventIndex=="number"?{fromEventIndex:e.fromEventIndex}:{}},{signal:e.signal,onReady:e.onReady,onDelta:e.onDelta,onSessionEvent:e.onSessionEvent})}async function By(e){var t;if(e.backendStopSupported)try{const n=new Set,r=(t=e.backendRunId)==null?void 0:t.trim();if(r&&(n.add(r),await Sn(r)))return;const s=await $y(e);for(const i of s){if(n.has(i))continue;if(n.add(i),await Sn(i))return}if(r&&await Sn(r))return}catch{}}async function Sn(e){const t=e.trim();if(!t)return!1;try{return(await ll({runId:t})).stopped===!0}catch{return!1}}async function $y(e){var s;const t=(s=e.sessionKey)==null?void 0:s.trim();if(!t)return[];const n=8,r=120;for(let i=0;i<n;i+=1){const a=await Uy(e,t);if(a.length>0)return a;i<n-1&&await Hy(r)}return[]}async function Uy(e,t){try{const n=await ul({sessionKey:t,states:["queued","running"],limit:50}),r=n.runs.filter(s=>{var i;return((i=s.runId)==null?void 0:i.trim())&&s.sessionKey===t&&s.agentId===e.agentId}).map(s=>s.runId.trim());return r.length>0?r:n.runs.filter(s=>{var i;return((i=s.runId)==null?void 0:i.trim())&&s.sessionKey===t}).map(s=>s.runId.trim())}catch{return[]}}function Hy(e){return new Promise(t=>{window.setTimeout(t,e)})}function qa(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const r=n.trim();r&&t.add(r)}return[...t]}function Ky(e){var m;const t=new Set(["tool","tool_result","toolresult","function"]),n=[];let r=0,s=0,i=null;const a=(S,g)=>(r+=1,`history-${S}-${g||"unknown"}-${r}`),o=S=>{const g=typeof S=="string"?S:JSON.stringify(S??{});try{return{args:g,parsedArgs:JSON.parse(g)}}catch{return{args:g}}},u=(S,g)=>{for(let k=S.length-1;k>=0;k-=1){const w=S[k];if(w.type==="tool-invocation"&&w.toolInvocation.toolCallId===g)return k}return-1},l=S=>i?(i={...i,meta:{...i.meta,timestamp:S}},i):(s+=1,i={id:`history-assistant-${s}-${S||"unknown"}`,role:"assistant",parts:[],meta:{source:"history",status:"final",timestamp:S}},i),c=()=>{i&&(i.parts.length>0&&n.push(i),i=null)},d=(S,g)=>{if(!g)return;const k=l(S);k.parts=[...k.parts,{type:"text",text:g}]},p=(S,g)=>{if(!g)return;const k=l(S);k.parts=[...k.parts,{type:"reasoning",reasoning:g,details:[]}]},f=S=>{const g=l(S.timestamp),k=u(g.parts,S.toolCallId),w={type:"tool-invocation",toolInvocation:{status:ae.CALL,toolCallId:S.toolCallId,toolName:S.toolName,args:S.args,parsedArgs:S.parsedArgs}};if(k>=0){g.parts=[...g.parts.slice(0,k),w,...g.parts.slice(k+1)];return}g.parts=[...g.parts,w]},y=S=>{if(!S.toolCallId)return;const g=l(S.timestamp),k=u(g.parts,S.toolCallId);if(k<0){g.parts=[...g.parts,{type:"tool-invocation",toolInvocation:{status:ae.RESULT,toolCallId:S.toolCallId,toolName:S.toolName,args:"{}",parsedArgs:void 0,result:S.result}}];return}const w=g.parts[k];w.type==="tool-invocation"&&(g.parts=[...g.parts.slice(0,k),{...w,toolInvocation:{...w.toolInvocation,status:ae.RESULT,result:S.result}},...g.parts.slice(k+1)])};for(const S of e){const g=(m=S.role)==null?void 0:m.toLowerCase().trim();if(!g)continue;const k=S.timestamp;if(g==="user"||g==="system"||g==="data"){c();const w=Rr(S.content).trim();if(!w)continue;n.push({id:a(g,k),role:g,parts:[{type:"text",text:w}],meta:{source:"history",status:"final",timestamp:k}});continue}if(g==="assistant"){const w=Rr(S.content).trim();if(w&&d(k,w),typeof S.reasoning_content=="string"&&S.reasoning_content.trim()&&p(k,S.reasoning_content.trim()),Array.isArray(S.tool_calls))for(const E of S.tool_calls){if(!E||typeof E!="object")continue;const M=E,I=M.function,P=typeof I=="object"&&I?I:null,D=typeof M.id=="string"?M.id.trim():"";if(!D)continue;const F=typeof(P==null?void 0:P.name)=="string"?P.name:typeof M.name=="string"?M.name:"tool",C=o((P==null?void 0:P.arguments)??M.arguments??"");f({timestamp:k,toolCallId:D,toolName:F,args:C.args,parsedArgs:C.parsedArgs})}continue}if(t.has(g)){const w=typeof S.tool_call_id=="string"?S.tool_call_id.trim():"",E=typeof S.name=="string"&&S.name.trim()?S.name.trim():"tool";y({timestamp:k,toolCallId:w,toolName:E,result:S.content})}}return c(),n}function Vy(){const e=Date.now().toString(36),t=Math.random().toString(36).slice(2,10);return`run-${e}-${t}`}function qy(e){const t=e.metadata;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(n.driver!=="nextbot-stream")return null;const r=n.mode;if(r==="send"){const s=n.payload;if(!s||typeof s!="object"||Array.isArray(s))return null;const i=Array.isArray(n.requestedSkills)?n.requestedSkills.filter(a=>typeof a=="string"):[];return{driver:"nextbot-stream",mode:"send",payload:s,requestedSkills:i}}if(r==="resume"){const s=typeof n.runId=="string"?n.runId.trim():"";if(!s)return null;const i=typeof n.fromEventIndex=="number"&&Number.isFinite(n.fromEventIndex)?Math.max(0,Math.trunc(n.fromEventIndex)):void 0,a=typeof n.sessionKey=="string"?n.sessionKey.trim():"",o=typeof n.agentId=="string"?n.agentId.trim():"",u=typeof n.stopSupported=="boolean"?n.stopSupported:void 0,l=typeof n.stopReason=="string"?n.stopReason.trim():"";return{driver:"nextbot-stream",mode:"resume",runId:s,...typeof i=="number"?{fromEventIndex:i}:{},...a?{sessionKey:a}:{},...o?{agentId:o}:{},...typeof u=="boolean"?{stopSupported:u}:{},...l?{stopReason:l}:{}}}return null}function Wy(e){var t;if(e.mode==="send"){const n=((t=e.payload.runId)==null?void 0:t.trim())||"";return{localRunId:0,sessionKey:e.payload.sessionKey,...e.payload.agentId?{agentId:e.payload.agentId}:{},...n?{backendRunId:n}:{},backendStopSupported:!!e.payload.stopSupported,...e.payload.stopReason?{backendStopReason:e.payload.stopReason}:{}}}return{localRunId:0,sessionKey:e.sessionKey??"",...e.agentId?{agentId:e.agentId}:{},backendRunId:e.runId,backendStopSupported:!!e.stopSupported,...e.stopReason?{backendStopReason:e.stopReason}:{}}}function Gy(e){var n;return e.mode!=="send"||((n=e.payload.runId)==null?void 0:n.trim())?e:{...e,payload:{...e.payload,runId:Vy()}}}function Qy(e,t){var n,r,s;e.backendRunId=((n=t.runId)==null?void 0:n.trim())||e.backendRunId,e.backendStopSupported=typeof t.stopSupported=="boolean"?t.stopSupported:e.backendStopSupported,(r=t.stopReason)!=null&&r.trim()&&(e.backendStopReason=t.stopReason.trim()),(s=t.sessionKey)!=null&&s.trim()&&(e.sessionKey=t.sessionKey.trim())}function Xy(){return{deltaMessageId:Va(),deltaStarted:!1,deltaClosed:!1,hasAssistantSessionEvent:!1,hasAssistantOutput:!1}}function Yy(e){var t,n,r;return{driver:"nextbot-stream",kind:"ready",...(t=e.sessionKey)!=null&&t.trim()?{sessionKey:e.sessionKey.trim()}:{},...(n=e.runId)!=null&&n.trim()?{backendRunId:e.runId.trim()}:{},...typeof e.stopSupported=="boolean"?{stopSupported:e.stopSupported}:{},...(r=e.stopReason)!=null&&r.trim()?{stopReason:e.stopReason.trim()}:{},...e.requestedAt?{requestedAt:e.requestedAt}:{}}}function Jy(e,t){return{driver:"nextbot-stream",kind:"final",sessionKey:e.sessionKey,reply:e.reply,hasAssistantSessionEvent:t}}function Ds(e,t,n){e({type:W.RUN_METADATA,runId:t,metadata:n})}function _s(e,t){!e.deltaStarted||e.deltaClosed||(t({type:W.TEXT_END,messageId:e.deltaMessageId}),e.deltaClosed=!0)}function Zy(e,t,n){const r=Py({messageId:e.deltaMessageId,delta:n.delta,started:e.deltaStarted});r.length>0&&(e.deltaStarted=!0,e.deltaClosed=!1,e.hasAssistantOutput=!0);for(const s of r)t(s)}function ex(e,t,n){jy(n.data),Dy(n.data)&&(e.hasAssistantSessionEvent=!0);for(const r of _y({event:n.data,messageId:e.deltaMessageId}))t(r)}function tx(e,t,n){const r=n.trim();if(e.hasAssistantOutput||!r)return;const s=Va();t({type:W.TEXT_START,messageId:s}),t({type:W.TEXT_DELTA,messageId:s,delta:r}),t({type:W.TEXT_END,messageId:s})}class nx{constructor(){this.activeAbortController=null,this.activeRunState=null,this.buildMissingMetadataObservable=t=>new Ut(n=>{n.next({type:W.RUN_ERROR,runId:t,error:"nextbot runtime metadata is required"}),n.complete()}),this.openRunStream=t=>{const{metadata:n,signal:r,onReady:s,onDelta:i,onSessionEvent:a}=t;return n.mode==="send"?zy({item:n.payload,requestedSkills:n.requestedSkills,signal:r,onReady:s,onDelta:i,onSessionEvent:a}):Fy({runId:n.runId,fromEventIndex:n.fromEventIndex,signal:r,onReady:s,onDelta:i,onSessionEvent:a})},this.finalizeRunState=(t,n)=>{this.activeAbortController===t&&(this.activeAbortController=null),this.activeRunState===n&&(this.activeRunState=null)},this.createRunObservable=({metadata:t,clientRunId:n,abortController:r,runState:s})=>new Ut(i=>{const a=Xy();let o=!1;const u=c=>{o||i.next(c)};return u({type:W.RUN_STARTED,runId:n}),this.openRunStream({metadata:t,signal:r.signal,onReady:c=>{this.activeRunState&&Qy(this.activeRunState,c),Ds(u,n,Yy(c))},onDelta:c=>{Zy(a,u,c)},onSessionEvent:c=>{ex(a,u,c)}}).then(c=>{_s(a,u),tx(a,u,c.reply),Ds(u,n,Jy(c,a.hasAssistantSessionEvent)),u({type:W.RUN_FINISHED,runId:n}),i.complete()}).catch(c=>{_s(a,u),Kn(c)||u({type:W.RUN_ERROR,runId:n,error:c instanceof Error?c.message:String(c)}),i.complete()}).finally(()=>{this.finalizeRunState(r,s)}),()=>{o=!0,r.abort(),this.activeAbortController===r&&(this.activeAbortController=null)}}),this.abortRun=()=>{var n;const t=this.activeRunState;t!=null&&t.backendStopSupported&&By(t),(n=this.activeAbortController)==null||n.abort(),this.activeAbortController=null,this.activeRunState=null},this.run=t=>{const n=qy(t),r=typeof t.runId=="string"&&t.runId.trim()?t.runId:`run-${Date.now()}`;if(!n)return this.buildMissingMetadataObservable(r);const s=Gy(n);this.abortRun();const i=new AbortController;this.activeAbortController=i;const a=Wy(s);return this.activeRunState=a,this.createRunObservable({metadata:s,clientRunId:r,abortController:i,runState:a})}}}class rx{constructor(){this.chatUiManager=new Ka,this.runtimeAgent=new nx,this.chatController=new Jm({agent:this.runtimeAgent,getToolDefs:()=>[],getContexts:()=>[],getToolExecutor:()=>{}},{metadataParsers:Ty}),this.chatStreamActionsManager=new Ha,this.chatInputManager=new Iy(this.chatUiManager,this.chatStreamActionsManager),this.chatSessionListManager=new Ua(this.chatUiManager,this.chatStreamActionsManager),this.chatRunStatusManager=new $a,this.chatThreadManager=new Ly(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}}function Nt(e){const[t,n]=v.useState(e.getValue());return v.useEffect(()=>{const r=e.subscribe(n);return()=>r.unsubscribe()},[e]),t}function sx(e,t){const[n,r]=v.useState(t);return v.useEffect(()=>{const s=e.subscribe(r);return()=>s.unsubscribe()},[e]),n}function ix(e,t){const n=v.useRef(e);v.useEffect(()=>{n.current=e});const r=v.useRef(null);v.useEffect(()=>{t.setCallbacks({onRunSettled:async({sourceSessionId:g,resultSessionId:k})=>{const w=n.current;await w.refetchSessions();const E=w.selectedSessionKeyRef.current;(!E||E===g||k&&E===k)&&await w.refetchHistory()},onRunError:({sourceMessage:g,restoreDraft:k})=>{k&&n.current.setDraft(w=>w.trim().length===0&&g?g:w)},onSessionChanged:g=>{n.current.setSelectedSessionKey(k=>k===g?k:g)}})},[t]);const s=sx(t.messages$,t.getMessages()),i=Nt(t.isAgentResponding$),a=Nt(t.isAwaitingResponse$),o=Nt(t.activeRun$),u=Nt(t.lastError$),l=(o==null?void 0:o.remoteRunId)??null,c=Wm(o),d=!!(o&&(c===null||o.remoteStopCapable&&!l)),p=v.useCallback(async g=>{const k=qa(g.requestedSkills),w=Ry(g,k);await t.send({message:g.message,sessionId:g.sessionKey,agentId:g.agentId,metadata:w,restoreDraftOnError:g.restoreDraftOnError,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),f=v.useCallback(async g=>{var M,I;const k=(M=g.runId)==null?void 0:M.trim(),w=(I=g.sessionKey)==null?void 0:I.trim();if(!k||!w)return;const E=My(g);await t.resume({remoteRunId:k,sessionId:w,agentId:g.agentId,metadata:E,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),y=v.useCallback(async()=>{await t.stop()},[t]),m=v.useCallback(()=>{r.current=null,t.reset()},[t]),S=v.useCallback((g,k)=>{if(!!(t.activeRun$.getValue()||t.isAgentResponding$.getValue()))return;const E=n.current.selectedSessionKeyRef.current;if(E!==r.current&&(r.current=E,t.getMessages().length>0&&t.setMessages([])),!E){t.getMessages().length>0&&t.setMessages([]);return}k!=null&&k.isLoading&&g.length===0||t.setMessages(Ky(g))},[t]);return{uiMessages:s,isSending:i,isAwaitingAssistantOutput:a,canStopCurrentRun:d,stopDisabledReason:c,lastSendError:u,activeBackendRunId:l,sendMessage:p,stopCurrentRun:y,resumeRun:f,resetStreamState:m,applyHistoryMessages:S}}function ax({view:e}){var Te,Pe;const[t]=v.useState(()=>new rx),n=re($=>$.snapshot.query),r=re($=>$.snapshot.selectedSessionKey),s=re($=>$.snapshot.selectedAgentId),i=K($=>$.snapshot.pendingSessionType),{confirm:a,ConfirmDialog:o}=Jn(),u=Yn(),l=ni(),{sessionId:c}=ri(),d=v.useRef(null),p=v.useRef(r),f=v.useRef(null),y=v.useMemo(()=>Ba(c),[c]),{sessionsQuery:m,installedSkillsQuery:S,chatCapabilitiesQuery:g,historyQuery:k,isProviderStateResolved:w,modelOptions:E,sessions:M,skillRecords:I,selectedSession:P,historyMessages:D,selectedSessionThinkingLevel:F,sessionTypeOptions:C,defaultSessionType:_,selectedSessionType:O,canEditSessionType:G,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:N}=Fl({query:n,selectedSessionKey:r,selectedAgentId:s,pendingSessionType:i,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel}),{uiMessages:q,isSending:Y,isAwaitingAssistantOutput:le,canStopCurrentRun:me,stopDisabledReason:x,lastSendError:ue,activeBackendRunId:se,sendMessage:b,stopCurrentRun:ce,resumeRun:Se,resetStreamState:ne,applyHistoryMessages:Ce}=ix({selectedSessionKeyRef:p,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setDraft:t.chatInputManager.setDraft,refetchSessions:m.refetch,refetchHistory:k.refetch},t.chatController);v.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:b,stopCurrentRun:ce,resumeRun:Se,resetStreamState:ne,applyHistoryMessages:Ce})},[Ce,t,ne,Se,b,ce]);const{sessionRunStatusByKey:ye}=Dl({view:e,selectedSessionKey:r,activeBackendRunId:se,isLocallyRunning:Y||!!se,resumeRun:t.chatStreamActionsManager.resumeRun});Oa({view:e,routeSessionKey:y,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:p,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Fa}),v.useEffect(()=>{t.chatStreamActionsManager.applyHistoryMessages(D,{isLoading:k.isLoading})},[D,k.isLoading,t]),v.useEffect(()=>{t.chatUiManager.syncState({pathname:u.pathname}),t.chatUiManager.bindActions({navigate:l,confirm:a})},[a,u.pathname,l,t]);const Ie=P?gi(P):void 0;return v.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:m.refetch})},[t,m.refetch]),v.useEffect(()=>{var pe,Me;const $=!Y&&!le&&!k.isLoading&&r!==f.current;t.chatInputManager.syncSnapshot({isProviderStateResolved:w,defaultSessionType:_,canStopGeneration:me,stopDisabledReason:x,stopSupported:((pe=g.data)==null?void 0:pe.stopSupported)??!1,stopReason:(Me=g.data)==null?void 0:Me.stopReason,sendError:ue,isSending:Y,modelOptions:E,sessionTypeOptions:C,selectedSessionType:O,...$?{selectedThinkingLevel:F}:{},canEditSessionType:G,sessionTypeUnavailable:z,skillRecords:I,isSkillsLoading:S.isLoading}),$&&(f.current=r),r||(f.current=null),t.chatSessionListManager.syncSnapshot({sessions:M,query:n,isLoading:m.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:ye,isLocallyRunning:Y||!!se,activeBackendRunId:se}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:w,modelOptions:E,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:N,selectedSessionKey:r,sessionDisplayName:Ie,canDeleteSession:!!P,threadRef:d,isHistoryLoading:k.isLoading,uiMessages:q,isSending:Y,isAwaitingAssistantOutput:le})},[se,G,me,Ie,(Te=g.data)==null?void 0:Te.stopReason,(Pe=g.data)==null?void 0:Pe.stopSupported,_,k.isLoading,S.isLoading,le,w,Y,ue,E,t,n,P,r,F,O,ye,C,z,N,M,m.isLoading,I,x,d,q]),h.jsx(yi,{presenter:t,children:h.jsx(za,{view:e,confirmDialog:h.jsx(o,{})})})}var te=(e=>(e.EndpointReady="endpoint.ready",e.EndpointError="endpoint.error",e.MessageRequest="message.request",e.MessageStreamRequest="message.stream-request",e.MessageSent="message.sent",e.MessageAccepted="message.accepted",e.MessageIncoming="message.incoming",e.MessageCompleted="message.completed",e.MessageFailed="message.failed",e.MessageAbort="message.abort",e.MessageTextStart="message.text-start",e.MessageTextDelta="message.text-delta",e.MessageTextEnd="message.text-end",e.MessageReasoningStart="message.reasoning-start",e.MessageReasoningDelta="message.reasoning-delta",e.MessageReasoningEnd="message.reasoning-end",e.MessageToolCallStart="message.tool-call-start",e.MessageToolCallArgs="message.tool-call-args",e.MessageToolCallArgsDelta="message.tool-call-args-delta",e.MessageToolCallEnd="message.tool-call-end",e.MessageToolCallResult="message.tool-call-result",e.MessageRead="message.read",e.MessageDelivered="message.delivered",e.MessageRecalled="message.recalled",e.MessageReaction="message.reaction",e.RunStarted="run.started",e.RunFinished="run.finished",e.RunError="run.error",e.RunMetadata="run.metadata",e.TypingStart="typing.start",e.TypingEnd="typing.end",e.PresenceUpdated="presence.updated",e))(te||{}),Os=/\[\[\s*reply_to_current\s*\]\]/gi,zs=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function qn(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function ox(e,t){var i;let n=e,r;Os.test(n)&&(r=qn(t),n=n.replace(Os,"").trim());const s=(i=n.match(zs))==null?void 0:i[1];return s&&(r=qn(s),n=n.replace(zs,"").trim()),r?{content:n,replyTo:r}:{content:n}}function lx(e,t=e.id){if(e.role!=="assistant")return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};const n=e.parts.findIndex(c=>c.type==="text"),r=e.metadata?{...e.metadata}:void 0,s=qn(r==null?void 0:r.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};const i=e.parts[n];if(!i||i.type!=="text")return{...e,parts:[...e.parts],metadata:r};const{content:a,replyTo:o}=ox(i.text,t),u=o??s,l=e.parts.flatMap((c,d)=>d!==n||c.type!=="text"?[c]:a.length===0?[]:[{...c,text:a}]);return u?{...e,parts:l,metadata:{...r,reply_to:u}}:{...e,parts:l,metadata:r}}function Fs(e){const t=e.split(/\r?\n/);let n="message";const r=[];for(const s of t){const i=s.trimEnd();if(!(!i||i.startsWith(":"))){if(i.startsWith("event:")){n=i.slice(6).trim()||"message";continue}i.startsWith("data:")&&r.push(i.slice(5).trimStart())}}return r.length===0?null:{event:n,data:r.join(`
|
|
37
|
-
`)}}async function*ux(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{value:i,done:a}=await t.read();if(a)break;r+=n.decode(i,{stream:!0});const{frames:o,rest:u}=Bs(r);r=u;for(const l of o)yield l}r+=n.decode();const{frames:s}=Bs(r,!0);for(const i of s)yield i}finally{t.releaseLock()}}function Bs(e,t=!1){const n=e.split(/\r?\n\r?\n/),r=n.pop()??"",s=[];for(const i of n){const a=Fs(i);a&&s.push(a)}if(t&&r.trim()){const i=Fs(r);return i&&s.push(i),{frames:s,rest:""}}return{frames:s,rest:r}}var $s="/ncp/agent",cx="ncp-http-agent-client",Wa=class extends Error{constructor(t,n=!1){super(t.message);j(this,"ncpError");j(this,"alreadyPublished");this.name=`NcpHttpAgentClientError(${t.code})`,this.ncpError=t,this.alreadyPublished=n}};function dx(e){const t=e.trim();if(!t)throw new Error("NcpHttpAgentClient requires a non-empty baseUrl.");return new URL(t)}function hx(e){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("No fetch implementation found. Pass options.fetchImpl explicitly.")}function fx(e){const t=(e??$s).trim();if(!t)return $s;const n=t.startsWith("/")?t:`/${t}`;return n.endsWith("/")?n.slice(0,-1):n}async function Us(e){try{return(await e.text()).trim()}catch{return""}}function Hs(e){if(Ga(e))return e.ncpError;if(px(e))return e;const t=e instanceof Error?e.message:String(e??"Unknown error");return{code:Qa(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function kn(e,t={}){return new Wa(e,t.alreadyPublished??!1)}function px(e){return br(e)&&typeof e.code=="string"&&typeof e.message=="string"}function br(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ga(e){return e instanceof Wa}var gx={"config-error":"config-error","auth-error":"auth-error","runtime-error":"runtime-error","timeout-error":"timeout-error","abort-error":"abort-error"};function Qa(e){if(!e)return"runtime-error";const t=gx[e];if(t)return t;const n=e.toLowerCase();return n.includes("timeout")?"timeout-error":n.includes("abort")||n.includes("cancel")?"abort-error":n.includes("auth")?"auth-error":n.includes("config")?"config-error":"runtime-error"}function mx(e){const t=Xa(e);return!t||typeof t.type!="string"||!t.type.trim()?null:t}function yx(e){const t=Xa(e);if(!t)return{code:"runtime-error",message:e||"Unknown stream error."};const n=typeof t.code=="string"?t.code:void 0,r=Qa(n),s=br(t.details)?t.details:{};return n&&n!==r&&(s.originalCode=n),{code:r,message:typeof t.message=="string"&&t.message?t.message:"Unknown stream error.",...Object.keys(s).length>0?{details:s}:{}}}function Xa(e){try{const t=JSON.parse(e);return br(t)?t:null}catch{return null}}var xx=["text","file","source","step-start","reasoning","tool-invocation","card","rich-text","action","extension"],bx=class{constructor(e){j(this,"manifest");j(this,"baseUrl");j(this,"basePath");j(this,"fetchImpl");j(this,"defaultHeaders");j(this,"subscribers",new Set);j(this,"activeControllers",new Set);j(this,"started",!1);var t;this.baseUrl=dx(e.baseUrl),this.basePath=fx(e.basePath),this.fetchImpl=hx(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:"custom",endpointId:((t=e.endpointId)==null?void 0:t.trim())||cx,version:"0.1.0",supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:xx,expectedLatency:"seconds",metadata:{transport:"http+sse",scope:"agent"}}}async start(){this.started||(this.started=!0,this.publish({type:te.EndpointReady}))}async stop(){if(this.started){this.started=!1;for(const e of this.activeControllers)e.abort();this.activeControllers.clear()}}async emit(e){switch(e.type){case"message.request":await this.send(e.payload);return;case"message.stream-request":await this.stream(e.payload);return;case"message.abort":await this.abort(e.payload);return;default:this.publish(e);return}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}async send(e){await this.ensureStarted(),await this.streamRequest({path:"/send",method:"POST",body:e})}async stream(e){await this.ensureStarted();const t=new URLSearchParams({sessionId:e.sessionId});await this.streamRequest({path:`/stream?${t.toString()}`,method:"GET"})}async abort(e){await this.ensureStarted();const t=new AbortController;this.activeControllers.add(t);try{const n=await this.fetchImpl(this.resolveUrl("/abort"),{method:"POST",headers:{...this.defaultHeaders,"content-type":"application/json",accept:"application/json"},body:JSON.stringify(e),signal:t.signal});if(!n.ok)throw new Error(`Abort request failed with HTTP ${n.status}: ${await Us(n)}`)}catch(n){if(t.signal.aborted)return;const r=Hs(n);throw this.publish({type:te.EndpointError,payload:r}),kn(r)}finally{this.activeControllers.delete(t)}}async ensureStarted(){this.started||await this.start()}publish(e){for(const t of this.subscribers)t(e)}resolveUrl(e){return new URL(`${this.basePath}${e}`,this.baseUrl)}async streamRequest(e){const t=new AbortController;this.activeControllers.add(t);try{const n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,accept:"text/event-stream",...e.body!==void 0?{"content-type":"application/json"}:{}},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw new Error(`NCP stream request failed with HTTP ${n.status}: ${await Us(n)}`);if(!n.body)throw new Error("NCP stream response has no body.");for await(const r of ux(n.body)){if(t.signal.aborted)return;this.handleSseFrame(r)}}catch(n){if(t.signal.aborted)return;if(Ga(n))throw n;const r=Hs(n);throw this.publish({type:te.EndpointError,payload:r}),kn(r)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event==="ncp-event"){const t=mx(e.data);if(!t){this.publish({type:te.EndpointError,payload:{code:"runtime-error",message:"Received malformed ncp-event frame."}});return}this.publish(t);return}if(e.event==="error"){const t=yx(e.data);throw this.publish({type:te.EndpointError,payload:t}),kn(t,{alreadyPublished:!0})}}};function _t(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function wn(e){return _t(lx(e))}var Sx="assistant",kx=e=>{var n;const t=(n=e.error)==null?void 0:n.trim();return{code:"runtime-error",message:t&&t.length>0?t:"Agent run failed.",details:{sessionId:e.sessionId,messageId:e.messageId,threadId:e.threadId,runId:e.runId}}},wx=class{constructor(){j(this,"messages",[]);j(this,"streamingMessage",null);j(this,"error",null);j(this,"activeRun",null);j(this,"listeners",new Set);j(this,"toolCallMessageIdByCallId",new Map);j(this,"toolCallArgsRawByCallId",new Map);j(this,"snapshotCache",null);j(this,"snapshotVersion",-1);j(this,"stateVersion",0)}getSnapshot(){if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;const e={messages:this.messages.map(t=>_t(t)),streamingMessage:this.streamingMessage?_t(this.streamingMessage):null,error:this.error?{...this.error,details:this.error.details?{...this.error.details}:void 0}:null,activeRun:this.activeRun?{...this.activeRun}:null};return this.snapshotCache=e,this.snapshotVersion=this.stateVersion,e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}reset(){this.messages.length===0&&!this.streamingMessage&&!this.error&&!this.activeRun&&this.toolCallMessageIdByCallId.size===0&&this.toolCallArgsRawByCallId.size===0||(this.messages=[],this.streamingMessage=null,this.error=null,this.activeRun=null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.stateVersion+=1,this.notifyListeners())}hydrate(e){this.messages=e.messages.map(t=>wn(t)),this.streamingMessage=null,this.error=null,this.activeRun=e.activeRun?{...e.activeRun,sessionId:e.activeRun.sessionId??e.sessionId,abortDisabledReason:e.activeRun.abortDisabledReason??null}:null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.stateVersion+=1,this.notifyListeners()}async dispatch(e){const t=this.stateVersion;switch(e.type){case te.MessageSent:this.handleMessageSent(e.payload);break;case te.MessageAbort:this.handleMessageAbort(e.payload);break;case te.MessageTextStart:this.handleMessageTextStart(e.payload);break;case te.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case te.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case te.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case te.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case te.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case te.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case te.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case te.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case te.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case te.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case te.RunStarted:this.handleRunStarted(e.payload);break;case te.RunFinished:this.handleRunFinished(e.payload);break;case te.RunError:this.handleRunError(e.payload);break;case te.RunMetadata:this.handleRunMetadata(e.payload);break;case te.EndpointError:this.handleEndpointError(e.payload);break}this.stateVersion!==t&&this.notifyListeners()}handleMessageSent(e){this.upsertMessage(e.message),this.setError(null)}handleMessageAbort(e){var n;const t=(n=e.messageId)==null?void 0:n.trim();if(this.clearActiveRun(),this.setError(null),this.streamingMessage&&(!t||this.streamingMessage.id===t)){const r=this.streamingMessage.id;this.upsertMessage({...this.streamingMessage,status:"final"}),this.replaceStreamingMessage(null),t?this.clearToolCallTrackingByMessageId(t):this.clearToolCallTrackingByMessageId(r)}}handleMessageTextStart(e){this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming"),this.setError(null)}handleMessageTextDelta(e){if(!e.delta)return;const t=this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming"),n=[...t.parts],r=n[n.length-1];(r==null?void 0:r.type)==="text"?n[n.length-1]={type:"text",text:`${r.text}${e.delta}`}:n.push({type:"text",text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:"streaming"})}handleMessageTextEnd(e){var t;((t=this.streamingMessage)==null?void 0:t.id)===e.messageId&&this.streamingMessage.status==="streaming"&&this.replaceStreamingMessage({...this.streamingMessage,status:"pending"})}handleMessageReasoningStart(e){this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming")}handleMessageReasoningDelta(e){if(!e.delta)return;const t=this.ensureStreamingMessage(e.sessionId,e.messageId,"streaming"),n=[...t.parts],r=n[n.length-1];(r==null?void 0:r.type)==="reasoning"?n[n.length-1]={type:"reasoning",text:`${r.text}${e.delta}`}:n.push({type:"reasoning",text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:"streaming"})}handleMessageReasoningEnd(e){var t;(t=this.streamingMessage)==null||t.id,e.messageId}handleMessageToolCallStart(e){const t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId,e.messageId);this.toolCallArgsRawByCallId.set(e.toolCallId,"");const n=this.upsertToolInvocationPart(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:e.toolName,state:"partial-call",args:""});this.replaceStreamingMessage({...t,parts:n,status:"streaming"}),this.setError(null)}handleMessageToolCallArgs(e){this.toolCallArgsRawByCallId.set(e.toolCallId,e.args),this.applyToolCallArgs(e.sessionId,e.toolCallId,e.args)}handleMessageToolCallArgsDelta(e){const n=`${this.toolCallArgsRawByCallId.get(e.toolCallId)??""}${e.delta}`;this.toolCallArgsRawByCallId.set(e.toolCallId,n),this.applyToolCallArgs(e.sessionId,e.toolCallId,n,e.messageId)}handleMessageToolCallEnd(e){const t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=this.toolCallArgsRawByCallId.get(e.toolCallId)??"",r=this.upsertToolInvocationPart(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:this.findToolNameByCallId(t.parts,e.toolCallId)??"unknown",state:"call",args:n});this.replaceStreamingMessage({...t,parts:r,status:"streaming"})}handleMessageToolCallResult(e){if(!this.updateMessageContainingToolCall(e.toolCallId,(n,r)=>{const s={type:"tool-invocation",toolCallId:e.toolCallId,toolName:r.toolName,state:"result",args:r.args,result:e.content};return this.upsertToolInvocationPart(n.parts,s)})){const n=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),r=this.upsertToolInvocationPart(n.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:"unknown",state:"result",result:e.content});this.replaceStreamingMessage({...n,parts:r,status:"streaming"})}}handleRunStarted(e){this.setError(null),this.activeRun={runId:e.runId??null,sessionId:e.sessionId},this.stateVersion+=1}handleRunFinished(e){if(this.streamingMessage){const t={...this.streamingMessage,status:"final"};this.upsertMessage(t),this.replaceStreamingMessage(null),this.clearToolCallTrackingByMessageId(t.id)}this.setError(null),this.clearActiveRun()}handleRunError(e){if(this.streamingMessage){const t={...this.streamingMessage,status:"error"};this.upsertMessage(t),this.replaceStreamingMessage(null),this.clearToolCallTrackingByMessageId(t.id)}this.setError(kx(e)),this.clearActiveRun()}handleRunMetadata(e){var n,r;const t=e.metadata;if((t==null?void 0:t.kind)==="ready"){const s=t;this.activeRun={runId:s.runId??((n=this.activeRun)==null?void 0:n.runId)??null,sessionId:s.sessionId??((r=this.activeRun)==null?void 0:r.sessionId),abortDisabledReason:s.supportsAbort===!1?s.abortDisabledReason??"Unsupported":null},this.stateVersion+=1}else(t==null?void 0:t.kind)==="final"&&this.clearActiveRun()}handleEndpointError(e){this.setError(e)}applyToolCallArgs(e,t,n,r){const s=this.resolveToolCallTargetMessage(e,t,r),i=this.findToolNameByCallId(s.parts,t)??"unknown",a=this.upsertToolInvocationPart(s.parts,{type:"tool-invocation",toolCallId:t,toolName:i,state:"partial-call",args:n});this.replaceStreamingMessage({...s,parts:a,status:"streaming"})}ensureStreamingMessage(e,t,n){var i;if(((i=this.streamingMessage)==null?void 0:i.id)===t){if(this.streamingMessage.status===n)return this.streamingMessage;const a={...this.streamingMessage,status:n};return this.replaceStreamingMessage(a),a}const r=this.messages.findIndex(a=>a.id===t);if(r>=0){const a=_t(this.messages[r]),o=[...this.messages];o.splice(r,1),this.messages=o,this.stateVersion+=1;const u={...a,sessionId:e,status:n};return this.replaceStreamingMessage(u),u}const s={id:t,sessionId:e,role:Sx,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(s),s}resolveToolCallTargetMessage(e,t,n){var s;const r=(n==null?void 0:n.trim())||this.toolCallMessageIdByCallId.get(t)||((s=this.streamingMessage)==null?void 0:s.id)||`tool-${t}`;return this.toolCallMessageIdByCallId.set(t,r),this.ensureStreamingMessage(e,r,"streaming")}updateMessageContainingToolCall(e,t){if(this.streamingMessage){const n=this.findToolInvocationPart(this.streamingMessage.parts,e);if(n){const r=t(this.streamingMessage,n);return this.replaceStreamingMessage({...this.streamingMessage,parts:r}),!0}}for(let n=this.messages.length-1;n>=0;n-=1){const r=this.messages[n],s=this.findToolInvocationPart(r.parts,e);if(!s)continue;const i=[...this.messages];return i[n]={...r,parts:t(r,s)},this.messages=i,this.stateVersion+=1,!0}return!1}findToolInvocationPart(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r.type==="tool-invocation"&&r.toolCallId===t)return r}return null}findToolNameByCallId(e,t){const n=this.findToolInvocationPart(e,t);return(n==null?void 0:n.toolName)??null}upsertToolInvocationPart(e,t){const n=[...e];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s.type==="tool-invocation"&&s.toolCallId===t.toolCallId)return n[r]={...s,...t},n}return n.push(t),n}upsertMessage(e){const t=wn(e),n=this.messages.findIndex(s=>s.id===t.id);if(n<0){this.messages=[...this.messages,t],this.stateVersion+=1;return}const r=[...this.messages];r[n]=t,this.messages=r,this.stateVersion+=1}replaceStreamingMessage(e){!e&&!this.streamingMessage||(this.streamingMessage=e?wn(e):null,this.stateVersion+=1)}setError(e){var n,r,s,i;((n=this.error)==null?void 0:n.code)===(e==null?void 0:e.code)&&((r=this.error)==null?void 0:r.message)===(e==null?void 0:e.message)&&((s=this.error)==null?void 0:s.details)===(e==null?void 0:e.details)&&((i=this.error)==null?void 0:i.cause)===(e==null?void 0:e.cause)||(this.error=e?{...e,details:e.details?{...e.details}:void 0}:null,this.stateVersion+=1)}clearActiveRun(){this.activeRun&&(this.activeRun=null,this.stateVersion+=1)}clearToolCallTrackingByMessageId(e){for(const[t,n]of this.toolCallMessageIdByCallId)n===e&&(this.toolCallMessageIdByCallId.delete(t),this.toolCallArgsRawByCallId.delete(t))}notifyListeners(){const e=this.getSnapshot();for(const t of this.listeners)t(e)}};function vx(e,t){const n="payload"in e?e.payload:null;return!n||typeof n!="object"||!("sessionId"in n)||typeof n.sessionId!="string"?!0:n.sessionId===t}function Cx(e){return e.parts.some(t=>t.type==="text"||t.type==="rich-text"||t.type==="reasoning"?t.text.trim().length>0:!0)}function Ix(e,t){if(typeof e=="string"){const n=e.trim();return n?{sessionId:t,message:{id:`user-${Date.now().toString(36)}`,sessionId:t,role:"user",status:"final",parts:[{type:"text",text:n}],timestamp:new Date().toISOString()}}:null}return Cx(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function Tx(e,t){return{sessionId:e,messages:t.messages,activeRun:t.activeRun}}function Rx(e){const t=v.useRef();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new wx}),t.current.manager}function Mx({sessionId:e,client:t,manager:n}){var p;const r=v.useSyncExternalStore(f=>n.subscribe(()=>f()),()=>n.getSnapshot(),()=>n.getSnapshot()),[s,i]=v.useState(!1);v.useEffect(()=>{i(!1)},[e]),v.useEffect(()=>{const f=t.subscribe(y=>{vx(y,e)&&n.dispatch(y)});return()=>{f(),t.stop()}},[t,n,e]);const a=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,o=((p=r.activeRun)==null?void 0:p.runId)??null,u=!!r.activeRun;return{snapshot:r,visibleMessages:a,activeRunId:o,isRunning:u,isSending:s,send:async f=>{if(s||u)return;const y=Ix(f,e);if(!y)return;i(!0);const m=n.getSnapshot();await n.dispatch({type:te.MessageSent,payload:{sessionId:e,message:y.message,metadata:y.metadata}});try{await t.send(y)}catch(S){throw n.hydrate(Tx(e,m)),S}finally{i(!1)}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{r.activeRun&&await t.stream({sessionId:e})}}}function Ks(e){return e instanceof Error?e:new Error(String(e))}function Ax({sessionId:e,client:t,loadSeed:n,autoResumeRunningSession:r=!0}){const s=Rx(e),i=Mx({sessionId:e,client:t,manager:s}),[a,o]=v.useState(!0),[u,l]=v.useState(null),c=v.useRef({requestId:0,controller:null}),d=v.useCallback(async()=>{var y;(y=c.current.controller)==null||y.abort();const p=new AbortController,f=c.current.requestId+1;c.current={requestId:f,controller:p},await t.stop(),s.reset(),l(null),o(!0);try{const m=await n(e,p.signal);if(p.signal.aborted||c.current.requestId!==f)return;s.hydrate({sessionId:e,messages:m.messages,activeRun:m.status==="running"?{runId:null,sessionId:e,abortDisabledReason:null}:null}),l(null),o(!1),m.status==="running"&&r&&t.stream({sessionId:e}).catch(S=>{c.current.requestId===f&&l(Ks(S))})}catch(m){if(p.signal.aborted||c.current.requestId!==f)return;l(Ks(m)),o(!1)}finally{c.current.controller===p&&(c.current.controller=null)}},[r,t,n,s,e]);return v.useEffect(()=>(d(),()=>{var p;(p=c.current.controller)==null||p.abort(),c.current.controller=null}),[d]),{...i,isHydrating:a,hydrateError:u,reloadSeed:d}}const Ex=new Set(["off","minimal","low","medium","high","adaptive","xhigh"]);function Lx(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return String(e??"")}}function _e(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Yt(e){const{metadata:t}=e;return!t||typeof t!="object"||Array.isArray(t)?null:t}function Nx(e){const t=Yt(e);return t?_e(t.preferred_model)??_e(t.preferredModel)??_e(t.model):null}function Px(e){const t=Yt(e);if(!t)return null;const n=_e(t.preferred_thinking)??_e(t.thinking)??_e(t.thinking_level)??_e(t.thinkingLevel);if(!n)return null;const r=n.toLowerCase();return Ex.has(r)?r:null}function jx(e){const t=Yt(e);return t?_e(t.label):null}function Dx(e){const t=Yt(e);return t?_e(t.session_type)??_e(t.sessionType)??"native":"native"}function _x(e){return e.state==="result"?ae.RESULT:e.state==="partial-call"?ae.PARTIAL_CALL:ae.CALL}function Ox(e){const t=[];for(const n of e){if(n.type==="text"){t.push({type:"text",text:n.text});continue}if(n.type==="rich-text"){t.push({type:"text",text:n.text});continue}if(n.type==="reasoning"){t.push({type:"reasoning",reasoning:n.text,details:[]});continue}if(n.type==="source"){t.push({type:"source",source:{sourceType:"url",id:n.url??n.title??Math.random().toString(36).slice(2,8),url:n.url??"",...n.title?{title:n.title}:{}}});continue}if(n.type==="file"&&n.contentBase64){t.push({type:"file",mimeType:n.mimeType??"application/octet-stream",data:n.contentBase64});continue}if(n.type==="step-start"){t.push({type:"step-start"});continue}n.type==="tool-invocation"&&t.push({type:"tool-invocation",toolInvocation:{status:_x(n),toolCallId:n.toolCallId??`${n.toolName}-${Math.random().toString(36).slice(2,8)}`,toolName:n.toolName,args:Lx(n.args),result:n.result}})}return t}function zx(e){return e==="service"?"system":e==="tool"?"assistant":e}function Fx(e){return{id:e.id,role:zx(e.role),parts:Ox(e.parts),meta:{source:"stream",status:e.status,sessionKey:e.sessionId,timestamp:e.timestamp}}}function Bx(e){return e.map(Fx)}function $x(e){const t=jx(e),n=Nx(e);return{key:e.sessionId,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{label:t}:{},...n?{preferredModel:n}:{},sessionType:Dx(e),sessionTypeMutable:!1,messageCount:e.messageCount}}function Ux(e){return e.map($x)}function Vs(){return`ncp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Hx(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>r.key.toLowerCase().includes(n)):e}function Kx(e){var m,S,g;const t=si(),n=ii(),r=cl({limit:200}),s=oi("skill"),i=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),a=v.useMemo(()=>{const k=ui({meta:n.data,config:t.data,onlyConfigured:!0}),w=new Set,E=[];for(const M of k)for(const I of M.models){const P=ci(M.prefix,I);!P||w.has(P)||(w.add(P),E.push({value:P,modelLabel:I,providerLabel:M.displayName,thinkingCapability:di(M.modelThinking,I,M.aliases)}))}return E.sort((M,I)=>{const P=M.providerLabel.localeCompare(I.providerLabel);return P!==0?P:M.modelLabel.localeCompare(I.modelLabel)})},[n.data,t.data]),o=v.useMemo(()=>{var k;return((k=r.data)==null?void 0:k.sessions)??[]},[(m=r.data)==null?void 0:m.sessions]),u=v.useMemo(()=>Ux(o),[o]),l=v.useMemo(()=>Hx(u,e.query),[u,e.query]),c=v.useMemo(()=>u.find(k=>k.key===e.selectedSessionKey)??null,[u,e.selectedSessionKey]),d=v.useMemo(()=>o.find(k=>k.sessionId===e.selectedSessionKey)??null,[e.selectedSessionKey,o]),p=v.useMemo(()=>{var k;return((k=s.data)==null?void 0:k.records)??[]},[(S=s.data)==null?void 0:S.records]),f=v.useMemo(()=>d?Px(d):null,[d]),y=pi({selectedSession:c,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:null});return fi({modelOptions:a,selectedSessionPreferredModel:c==null?void 0:c.preferredModel,defaultModel:(g=t.data)==null?void 0:g.agents.defaults.model,setSelectedModel:e.setSelectedModel}),{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,isProviderStateResolved:i,modelOptions:a,sessionSummaries:o,sessions:l,skillRecords:p,selectedSession:c,selectedSessionThinkingLevel:f,...y}}class Vx{constructor(t,n,r){this.uiManager=t,this.streamActionsManager=n,this.getDraftSessionId=r,this.hasSnapshotChanges=s=>{const i=K.getState().snapshot;for(const[a,o]of Object.entries(s))if(!Object.is(i[a],o))return!0;return!1},this.resolveUpdateValue=(s,i)=>typeof i=="function"?i(s):i,this.syncSnapshot=s=>{if(this.hasSnapshotChanges(s)&&(K.getState().setSnapshot(s),Object.prototype.hasOwnProperty.call(s,"modelOptions")||Object.prototype.hasOwnProperty.call(s,"selectedModel")||Object.prototype.hasOwnProperty.call(s,"selectedThinkingLevel"))){const i=K.getState().snapshot;this.reconcileThinkingForModel(i.selectedModel)}},this.setDraft=s=>{const i=K.getState().snapshot.draft,a=this.resolveUpdateValue(i,s);a!==i&&K.getState().setSnapshot({draft:a})},this.setPendingSessionType=s=>{const i=K.getState().snapshot.pendingSessionType,a=this.resolveUpdateValue(i,s);a!==i&&K.getState().setSnapshot({pendingSessionType:a})},this.send=async()=>{const s=K.getState().snapshot,i=re.getState().snapshot,a=s.draft.trim();if(!a)return;const o=s.selectedSkills,u=i.selectedSessionKey??this.getDraftSessionId();i.selectedSessionKey||this.uiManager.goToSession(u,{replace:!0}),this.setDraft(""),this.setSelectedSkills([]),await this.streamActionsManager.sendMessage({message:a,sessionKey:u,agentId:i.selectedAgentId,sessionType:s.selectedSessionType,model:s.selectedModel||void 0,thinkingLevel:s.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:o,restoreDraftOnError:!0})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=s=>{const i=K.getState().snapshot.selectedModel,a=this.resolveUpdateValue(i,s);a!==i&&(K.getState().setSnapshot({selectedModel:a}),this.reconcileThinkingForModel(a))},this.setSelectedThinkingLevel=s=>{const i=K.getState().snapshot.selectedThinkingLevel,a=this.resolveUpdateValue(i,s);a!==i&&K.getState().setSnapshot({selectedThinkingLevel:a})},this.selectSessionType=s=>{const i=qe(s);K.getState().setSnapshot({selectedSessionType:i,pendingSessionType:i})},this.setSelectedSkills=s=>{const i=K.getState().snapshot.selectedSkills,a=this.resolveUpdateValue(i,s);Object.is(a,i)||K.getState().setSnapshot({selectedSkills:a})},this.selectModel=s=>{this.setSelectedModel(s)},this.selectThinkingLevel=s=>{this.setSelectedThinkingLevel(s)},this.selectSkills=s=>{this.setSelectedSkills(s)}}resolveThinkingForModel(t,n){const r=t==null?void 0:t.thinkingCapability;return!r||r.supported.length===0?null:n==="off"?"off":n&&r.supported.includes(n)?n:r.default&&r.supported.includes(r.default)?r.default:"off"}reconcileThinkingForModel(t){const n=K.getState().snapshot,r=n.modelOptions.find(i=>i.value===t),s=this.resolveThinkingForModel(r,n.selectedThinkingLevel);s!==n.selectedThinkingLevel&&K.getState().setSnapshot({selectedThinkingLevel:s})}}const qx=async()=>{};class Wx{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:qx},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=Ue.getState().snapshot;for(const[a,o]of Object.entries(s))if(!Object.is(i[a],o))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&Ue.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=re.getState();if(!(!s||!await this.uiManager.confirm({title:R("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:R("delete")}))){Ue.getState().setSnapshot({isDeletePending:!0});try{await dl(s),this.streamActionsManager.resetStreamState(),re.getState().setSnapshot({selectedSessionKey:null}),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{Ue.getState().setSnapshot({isDeletePending:!1})}}}}}class Gx{constructor(){this.chatUiManager=new Ka,this.chatStreamActionsManager=new Ha,this.chatSessionListManager=new Ua(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new Vx(this.chatUiManager,this.chatStreamActionsManager,()=>this.getDraftSessionId()),this.chatRunStatusManager=new $a,this.chatThreadManager=new Wx(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager),this.draftSessionId="",this.setDraftSessionId=t=>{this.draftSessionId=t}}getDraftSessionId(){return this.draftSessionId}}function Qx(){return(e,t)=>fetch(e,{credentials:"include",...t})}function Xx(e){var r,s,i;const t={};(r=e.model)!=null&&r.trim()&&(t.model=e.model.trim(),t.preferred_model=e.model.trim()),(s=e.thinkingLevel)!=null&&s.trim()&&(t.thinking=e.thinkingLevel.trim(),t.preferred_thinking=e.thinkingLevel.trim()),(i=e.sessionType)!=null&&i.trim()&&(t.session_type=e.sessionType.trim());const n=qa(e.requestedSkills);return n.length>0&&(t.requested_skills=n),t}function Yx(e){return e instanceof Error?e.message.includes("ncp session not found:"):!1}function Jx({view:e}){var Te,Pe;const[t]=v.useState(()=>new Gx),[n,r]=v.useState(()=>Vs()),s=re($=>$.snapshot.query),i=re($=>$.snapshot.selectedSessionKey),a=re($=>$.snapshot.selectedAgentId),o=K($=>$.snapshot.pendingSessionType),{confirm:u,ConfirmDialog:l}=Jn(),c=Yn(),d=ni(),{sessionId:p}=ri(),f=v.useRef(null),y=v.useRef(i),m=v.useRef(null),S=v.useMemo(()=>Ba(p),[p]),{sessionsQuery:g,installedSkillsQuery:k,isProviderStateResolved:w,modelOptions:E,sessionSummaries:M,sessions:I,skillRecords:P,selectedSession:D,selectedSessionThinkingLevel:F,sessionTypeOptions:C,defaultSessionType:_,selectedSessionType:O,canEditSessionType:G,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:N}=Kx({query:s,selectedSessionKey:i,pendingSessionType:o,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel}),q=i??n,Y=v.useRef(M);v.useEffect(()=>{Y.current=M},[M]);const[le]=v.useState(()=>new bx({baseUrl:hl,basePath:"/api/ncp/agent",fetchImpl:Qx()})),me=v.useCallback(async($,pe)=>{pe.throwIfAborted();let Me=null;try{Me=await fl($,300)}catch(Ge){if(!Yx(Ge))throw Ge}pe.throwIfAborted();const ze=Y.current.find(Ge=>Ge.sessionId===$)??null;return{messages:(Me==null?void 0:Me.messages)??[],status:(ze==null?void 0:ze.status)==="running"?"running":"idle"}},[]),x=Ax({sessionId:q,client:le,loadSeed:me});v.useEffect(()=>{t.setDraftSessionId(n)},[n,t]),v.useEffect(()=>{if(i===null){const $=Vs();r($),t.setDraftSessionId($)}},[t,i]);const ue=v.useMemo(()=>Bx(x.visibleMessages),[x.visibleMessages]),se=x.isSending||x.isRunning,b=x.isRunning,ce=x.isRunning,Se=x.isRunning?null:"__preparing__",ne=((Te=x.hydrateError)==null?void 0:Te.message)??((Pe=x.snapshot.error)==null?void 0:Pe.message)??null,Ce=x.activeRunId,ye=v.useMemo(()=>{const $=new Map;for(const pe of M)pe.status==="running"&&$.set(pe.sessionId,"running");return $},[M]);v.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:async $=>{if($.sessionKey!==q)return;const pe=Xx({model:$.model,thinkingLevel:$.thinkingLevel,sessionType:$.sessionType,requestedSkills:$.requestedSkills});try{g.refetch(),await x.send({sessionId:$.sessionKey,message:{id:`user-${Date.now().toString(36)}`,sessionId:$.sessionKey,role:"user",status:"final",parts:[{type:"text",text:$.message}],timestamp:new Date().toISOString(),...Object.keys(pe).length>0?{metadata:pe}:{}},...Object.keys(pe).length>0?{metadata:pe}:{}}),await g.refetch()}catch(Me){throw $.restoreDraftOnError&&t.chatInputManager.setDraft(ze=>ze.trim().length===0?$.message:ze),Me}},stopCurrentRun:async()=>{await x.abort(),await g.refetch()},resumeRun:async $=>{$.sessionKey===q&&await x.streamRun()},resetStreamState:()=>{y.current=null},applyHistoryMessages:()=>{}})},[q,x,t,g]),Oa({view:e,routeSessionKey:S,selectedSessionKey:i,selectedAgentId:a,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:y,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Fa}),v.useEffect(()=>{t.chatUiManager.syncState({pathname:c.pathname}),t.chatUiManager.bindActions({navigate:d,confirm:u})},[u,c.pathname,d,t]);const Ie=D?gi(D):void 0;return v.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:g.refetch})},[t,g.refetch]),v.useEffect(()=>{const $=!se&&!b&&!x.isHydrating&&i!==m.current;t.chatInputManager.syncSnapshot({isProviderStateResolved:w,defaultSessionType:_,canStopGeneration:ce,stopDisabledReason:Se,stopSupported:!0,stopReason:void 0,sendError:ne,isSending:se,modelOptions:E,sessionTypeOptions:C,selectedSessionType:O,...$?{selectedThinkingLevel:F}:{},canEditSessionType:G,sessionTypeUnavailable:z,skillRecords:P,isSkillsLoading:k.isLoading}),$&&(m.current=i),i||(m.current=null),t.chatSessionListManager.syncSnapshot({sessions:I,query:s,isLoading:g.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:ye,isLocallyRunning:se||!!Ce,activeBackendRunId:Ce}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:w,modelOptions:E,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:N,selectedSessionKey:i,sessionDisplayName:Ie,canDeleteSession:!!D,threadRef:f,isHistoryLoading:x.isHydrating,uiMessages:ue,isSending:se,isAwaitingAssistantOutput:b})},[Ce,x.isHydrating,G,ce,Ie,_,k.isLoading,b,w,se,ne,E,t,s,D,i,F,O,ye,C,z,N,I,g.isLoading,P,Se,f,ue]),h.jsx(yi,{presenter:t,children:h.jsx(za,{view:e,confirmDialog:h.jsx(l,{})})})}function db({view:e}){const t=Yn();return jl(t.search)==="ncp"?h.jsx(Jx,{view:e}):h.jsx(ax,{view:e})}export{db as ChatPage};
|