nextclaw 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/package.json +8 -8
  2. package/ui-dist/assets/{ChannelsList-C7F_As4r.js → ChannelsList-B-6m17e8.js} +1 -1
  3. package/ui-dist/assets/ChatPage-BZ6B6_pW.js +38 -0
  4. package/ui-dist/assets/{DocBrowser-Dsd8Dlq8.js → DocBrowser-B3Mn7Pr1.js} +1 -1
  5. package/ui-dist/assets/{LogoBadge-2ChEc_oz.js → LogoBadge-DunBd0Md.js} +1 -1
  6. package/ui-dist/assets/{MarketplacePage-BXck6-X3.js → MarketplacePage-GfyaFoSx.js} +2 -2
  7. package/ui-dist/assets/{ModelConfig-CgHRSD0b.js → ModelConfig-BQHpKPOV.js} +1 -1
  8. package/ui-dist/assets/{ProvidersList-PPfZucvS.js → ProvidersList-a_cTcyUa.js} +1 -1
  9. package/ui-dist/assets/{RuntimeConfig-ClLEKNTN.js → RuntimeConfig-ocF1z2ge.js} +1 -1
  10. package/ui-dist/assets/{SearchConfig-CuXVCbrf.js → SearchConfig-CuVwE1pL.js} +1 -1
  11. package/ui-dist/assets/{SecretsConfig-udJz6Ake.js → SecretsConfig-BNNNBC9B.js} +2 -2
  12. package/ui-dist/assets/{SessionsConfig-C1XnFfiC.js → SessionsConfig-NLh9dU5C.js} +2 -2
  13. package/ui-dist/assets/{chat-message-BETwXLD4.js → chat-message-D6cd8Vub.js} +1 -1
  14. package/ui-dist/assets/index-C98Y7H0s.css +1 -0
  15. package/ui-dist/assets/{index-COJdlL0e.js → index-DUrka-gK.js} +1 -1
  16. package/ui-dist/assets/{index-CsvP4CER.js → index-DhtQmFvo.js} +3 -3
  17. package/ui-dist/assets/{label-BGL-ztxh.js → label-UZ6h2eks.js} +1 -1
  18. package/ui-dist/assets/{page-layout-aw88k7tG.js → page-layout-C4opEYpL.js} +1 -1
  19. package/ui-dist/assets/{popover-DyEvzhmV.js → popover-CBwaT0q5.js} +1 -1
  20. package/ui-dist/assets/{security-config-BuPAQn82.js → security-config-C2x64Ori.js} +1 -1
  21. package/ui-dist/assets/skeleton-C56NStvY.js +1 -0
  22. package/ui-dist/assets/{switch-BK8jIzto.js → switch-CP4z7NJz.js} +1 -1
  23. package/ui-dist/assets/{tabs-custom-Da3cEOji.js → tabs-custom-yiwRX4b7.js} +1 -1
  24. package/ui-dist/assets/{useConfirmDialog-z0CE92iS.js → useConfirmDialog-DOu_1Piu.js} +2 -2
  25. package/ui-dist/assets/{vendor-CkJHmX1g.js → vendor-CAtZFO3x.js} +70 -65
  26. package/ui-dist/index.html +3 -3
  27. package/ui-dist/assets/ChatPage-Oo7-OUsx.js +0 -37
  28. package/ui-dist/assets/index-D-bXl7qL.css +0 -1
  29. package/ui-dist/assets/skeleton-drzO_tdU.js +0 -1
@@ -0,0 +1,38 @@
1
+ var jo=Object.defineProperty;var Do=(e,t,n)=>t in e?jo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var O=(e,t,n)=>Do(e,typeof t!="symbol"?t+"":t,n);import{r as C,j as h,a2 as _o,t as Oo,c as Fo,R as zo,o as Bo,T as pi,I as $o,C as lr,P as Uo,h as gi,V as Ko,i as mi,k as Ho,l as ur,m as Vo,S as yi,f as qo,g as xi,a as Wo,a3 as Go,B as cr,s as dr,a4 as bi,a5 as Qo,a6 as Xo,q as Yo,a7 as Jo,a8 as Zo,a9 as el,aa as Si,ab as ki,ac as wi,ad as tl,ae as nl,af as rl,ag as sl,ah as il,ai as al,O as en,aj as ol,A as hr,N as Fr,ak as ll,z as ul,F as cl,D as dl,E as hl,al as Dn,am as _n,an as On,ao as Lt,M as fl,ap as vi,aq as pl,ar as gl,as as ml,J as fr,at as Ci,au as Ii,u as yl}from"./vendor-CAtZFO3x.js";import{u as pr}from"./useConfirmDialog-DOu_1Piu.js";import{i as xl,t as A,u as Ti,a as Mi,j as bl,k as Sl,l as kl,m as wl,c as Te,n as vl,o as Cl,p as gr,q as Il,T as zr,L as Br,r as Tl,B as nt,I as Ri,s as tn,S as Fn,e as zn,g as Bn,h as Ct,v as Ml,w as Rl,x as Al,y as El,f as Ll,C as Nl,z as Pl,A as $r,E as jl,F as Dl,G as _l,H as Ol,J as Fl,K as zl,M as Bl,N as $l,O as Ul,P as Kl,Q as Hl}from"./index-DhtQmFvo.js";import{b as Vl,a as ql,S as Wl,s as Gl,c as Ur,e as Kr}from"./chat-message-D6cd8Vub.js";import{u as Ai,T as Ql,a as Xl,b as Yl,c as Jl,P as Zl,R as eu,d as tu,e as nu,C as Ei,M as ru}from"./MarketplacePage-GfyaFoSx.js";import{b as Li,c as Ni,r as Pi}from"./provider-models-D3B_xWXx.js";import{R as su,A as iu,P as au,C as ji,T as ou,a as lu,b as uu,c as cu}from"./popover-CBwaT0q5.js";import{P as du,a as hu}from"./page-layout-C4opEYpL.js";import"./index-DUrka-gK.js";import"./skeleton-C56NStvY.js";import"./tabs-custom-yiwRX4b7.js";const fu="ncp";function Hr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="legacy"||t==="ncp"?t:null}function pu(e){const t=Hr(new URLSearchParams(e).get("chatChain"));return t||(Hr(void 0)??fu)}function Vr(e){return(e==null?void 0:e.trim().toLowerCase())||"native"}function _t(e,t){const n=t==null?void 0:t.trim();return n?e.some(r=>r.value===n):!1}function mr(e){var o;const{currentSelectedModel:t,modelOptions:n,selectedSessionPreferredModel:r,fallbackPreferredModel:s,defaultModel:i,preferSessionPreferredModel:a=!1}=e;return n.length===0?"":!a&&_t(n,t)?t.trim():_t(n,r)?r.trim():_t(n,s)?s.trim():_t(n,i)?i.trim():((o=n[0])==null?void 0:o.value)??""}function Di(e){var s,i;const t=Vr(e.sessionType);let n=null,r=Number.NEGATIVE_INFINITY;for(const a of e.sessions){if(a.key===e.selectedSessionKey||Vr(a.sessionType)!==t||!((s=a.preferredModel)==null?void 0:s.trim()))continue;const l=Date.parse(a.updatedAt),u=Number.isFinite(l)?l:Number.NEGATIVE_INFINITY;(!n||u>r)&&(n=a,r=u)}return(i=n==null?void 0:n.preferredModel)==null?void 0:i.trim()}function _i(e){const{modelOptions:t,selectedSessionKey:n,selectedSessionPreferredModel:r,fallbackPreferredModel:s,defaultModel:i,setSelectedModel:a}=e,o=C.useRef(void 0);C.useEffect(()=>{const l=o.current!==n;if(t.length===0){a(""),o.current=n;return}a(u=>mr({currentSelectedModel:u,modelOptions:t,selectedSessionPreferredModel:r,fallbackPreferredModel:s,defaultModel:i,preferSessionPreferredModel:l})),o.current=n},[i,s,t,n,r,a])}function gu(e){var x;const{view:t,selectedSessionKey:n,activeBackendRunId:r,isLocallyRunning:s,resumeRun:i}=e,[a,o]=C.useState(null),l=C.useRef(!1),u=C.useRef(new Map),c=C.useRef(new Map),d=C.useRef(new Map),p=C.useRef(r),f=C.useRef(new Set);C.useEffect(()=>{n&&f.current.add(n)},[n]),C.useEffect(()=>{n&&s&&f.current.delete(n)},[s,n]);const m=xl(t==="chat"?{states:["queued","running"],limit:200,syncActiveStates:!0,isLocallyRunning:s}:void 0),y=C.useMemo(()=>{var w;return Vl(((w=m.data)==null?void 0:w.runs)??[])},[(x=m.data)==null?void 0:x.runs]),S=C.useMemo(()=>{const w=ql(y);if(a){const I=y.get(a.sessionKey)??null;I&&(!a.runId||I.runId===a.runId)&&w.delete(a.sessionKey)}return w},[y,a]),g=C.useMemo(()=>{if(!n)return null;const w=y.get(n)??null;return(!w||!a||a.sessionKey!==n?!1:!a.runId||w.runId===a.runId)?null:w},[y,n,a]);return C.useEffect(()=>{r&&(p.current=r)},[r]),C.useEffect(()=>{if(t!=="chat"||!n||!g||!f.current.has(n)||s||r===g.runId||u.current.get(n)===g.runId)return;const I=c.current.get(n);if(I&&I===g.runId)return;const R=d.current.get(n);if(typeof R=="number"){const v=Date.parse(g.requestedAt??"");if(Number.isFinite(v)){if(v<=R+2e3)return}else if(Date.now()-R<=8e3)return}u.current.set(n,g.runId),f.current.delete(n),i(g)},[r,g,s,i,n,t]),C.useEffect(()=>{if(!n){u.current.clear(),c.current.clear(),d.current.clear(),f.current.clear();return}y.has(n)||(u.current.delete(n),c.current.delete(n),d.current.delete(n))},[y,n]),C.useEffect(()=>{var I,R,v;const w=l.current;if(l.current=s,!s&&w&&n){const N=((I=p.current)==null?void 0:I.trim())||((v=(R=y.get(n))==null?void 0:R.runId)==null?void 0:v.trim());N&&c.current.set(n,N),d.current.set(n,Date.now()),o({sessionKey:n,...N?{runId:N}:{}}),m.refetch()}},[y,s,n,m]),C.useEffect(()=>{if(!a)return;const w=y.get(a.sessionKey)??null;if(!w){o(null);return}a.runId&&w.runId!==a.runId&&o(null)},[y,a]),C.useEffect(()=>{s&&(a==null?void 0:a.sessionKey)===n&&o(null)},[s,n,a]),{sessionRunStatusByKey:S}}const Ee="native";function He(e){return typeof e!="string"?Ee:e.trim().toLowerCase()||Ee}function ht(e,t){return e==="native"?A("chatSessionTypeNative"):e.trim().split(/[-_]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")||e}function mu(e){var n;const t=new Map;for(const r of e){const s=He(r.value);t.set(s,{value:s,label:((n=r.label)==null?void 0:n.trim())||ht(s)})}return t.has(Ee)||t.set(Ee,{value:Ee,label:ht(Ee)}),Array.from(t.values()).sort((r,s)=>r.value===Ee?-1:s.value===Ee?1:r.value.localeCompare(s.value))}function Oi(e){const{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:s,sessionTypesData:i}=e,a=C.useMemo(()=>mu((i==null?void 0:i.options)??[]),[i==null?void 0:i.options]),o=C.useMemo(()=>{const y=[...a],S=He(t==null?void 0:t.sessionType);return y.some(g=>g.value===S)||y.push({value:S,label:ht(S)}),y.sort((g,x)=>g.value===Ee?-1:x.value===Ee?1:g.value.localeCompare(x.value))},[a,t==null?void 0:t.sessionType]),l=C.useMemo(()=>He((i==null?void 0:i.defaultType)??Ee),[i==null?void 0:i.defaultType]),u=C.useRef(null),c=C.useMemo(()=>He((t==null?void 0:t.sessionType)??r??l),[l,r,t==null?void 0:t.sessionType]);C.useEffect(()=>{if(n)return;const y=typeof r=="string"?r.trim():"",S=He(r);(y.length===0||u.current===S||u.current===null&&S===Ee)&&(u.current=l,S!==l&&s(l))},[l,r,n,s]);const d=!n||!!(t!=null&&t.sessionTypeMutable),p=C.useMemo(()=>new Set(a.map(y=>y.value)),[a]),f=!!(t&&!p.has(He(t.sessionType))),m=f?`${ht(c)} ${A("chatSessionTypeUnavailableSuffix")}`:null;return{sessionTypeOptions:o,defaultSessionType:l,selectedSessionType:c,canEditSessionType:d,sessionTypeUnavailable:f,sessionTypeUnavailableMessage:m}}const yu=new Set(["off","minimal","low","medium","high","adaptive","xhigh"]);function xu(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t&&yu.has(t)?t:null}function bu(e){var x,w,I,R,v,N;const t=Ti(),n=Mi(),r=bl({q:e.query.trim()||void 0,limit:120,activeMinutes:0}),s=Ai("skill"),i=Sl({sessionKey:e.selectedSessionKey,agentId:e.selectedAgentId}),a=kl(e.selectedSessionKey,300),o=wl(),l=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),u=C.useMemo(()=>{const P=Li({meta:n.data,config:t.data,onlyConfigured:!0}),F=new Set,T=[];for(const L of P)for(const D of L.models){const $=Ni(L.prefix,D);!$||F.has($)||(F.add($),T.push({value:$,modelLabel:D,providerLabel:L.displayName,thinkingCapability:Pi(L.modelThinking,D,L.aliases)}))}return T.sort((L,D)=>{const $=L.providerLabel.localeCompare(D.providerLabel);return $!==0?$:L.modelLabel.localeCompare(D.modelLabel)})},[n.data,t.data]),c=C.useMemo(()=>{var P;return((P=r.data)==null?void 0:P.sessions)??[]},[(x=r.data)==null?void 0:x.sessions]),d=C.useMemo(()=>{var P;return((P=s.data)==null?void 0:P.records)??[]},[(w=s.data)==null?void 0:w.records]),p=C.useMemo(()=>c.find(P=>P.key===e.selectedSessionKey)??null,[e.selectedSessionKey,c]),f=Oi({selectedSession:p,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:o.data}),m=C.useMemo(()=>Di({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]);_i({modelOptions:u,selectedSessionKey:e.selectedSessionKey,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,fallbackPreferredModel:m,defaultModel:(I=t.data)==null?void 0:I.agents.defaults.model,setSelectedModel:e.setSelectedModel});const y=C.useMemo(()=>{var P;return mr({currentSelectedModel:"",modelOptions:u,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,fallbackPreferredModel:m,defaultModel:(P=t.data)==null?void 0:P.agents.defaults.model,preferSessionPreferredModel:!0})},[(R=t.data)==null?void 0:R.agents.defaults.model,u,m,p==null?void 0:p.preferredModel]),S=C.useMemo(()=>{var P;return((P=a.data)==null?void 0:P.messages)??[]},[(v=a.data)==null?void 0:v.messages]),g=C.useMemo(()=>{var T;if(!e.selectedSessionKey)return null;const P=(T=a.data)==null?void 0:T.metadata;if(!P||typeof P!="object")return null;const F=[P.preferred_thinking,P.thinking,P.thinking_level,P.thinkingLevel];for(const L of F){const D=xu(L);if(D)return D}return null},[(N=a.data)==null?void 0:N.metadata,e.selectedSessionKey]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,chatCapabilitiesQuery:i,historyQuery:a,sessionTypesQuery:o,isProviderStateResolved:l,modelOptions:u,sessions:c,skillRecords:d,selectedSession:p,hydratedSessionModel:y,historyMessages:S,selectedSessionThinkingLevel:g,...f}}function Fi(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const Su={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 ku({status:e,className:t}){const n=Su[e],r=e==="connected"?A("connected"):e==="disconnected"?A("disconnected"):A("connecting");return h.jsx(Ql,{delayDuration:250,children:h.jsxs(Xl,{children:[h.jsx(Yl,{asChild:!0,children:h.jsx("span",{role:"status","aria-label":r,className:Te("inline-flex h-5 w-5 items-center justify-center",t),children:e==="connecting"?h.jsx(_o,{className:Te("h-3 w-3 animate-spin",n.dotClass)}):h.jsx("span",{className:Te(e==="connected"?"h-2 w-2 rounded-full":"",n.dotClass)})})}),h.jsx(Jl,{side:"bottom",className:"text-xs",children:r})]})})}const zi=C.createContext(null);function Bi({presenter:e,children:t}){return h.jsx(zi.Provider,{value:e,children:t})}function yr(){const e=C.useContext(zi);if(!e)throw new Error("usePresenter must be used inside ChatPresenterProvider");return e}const wu=e=>`[data-item-index="${e}"]`;function $i(e){const t=e.getItemSelector??wu;C.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 vu(){const e=C.useRef(null),[t,n]=C.useState(null);return C.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 ue(...e){return Oo(Fo(e))}const Ui=C.forwardRef(({className:e,type:t,...n},r)=>h.jsx("input",{type:t,className:ue("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}));Ui.displayName="ChatInput";const Cu=su,Iu=ou,Tu=iu,Ki=C.forwardRef(({className:e,sideOffset:t=8,align:n="start",...r},s)=>h.jsx(au,{children:h.jsx(ji,{ref:s,sideOffset:t,align:n,className:ue("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})}));Ki.displayName=ji.displayName;const Mu=zo,Ru=Bo,Hi=C.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(pi,{ref:r,className:ue("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($o,{asChild:!0,children:h.jsx(lr,{className:"h-4 w-4 opacity-50"})})]}));Hi.displayName=pi.displayName;const Vi=C.forwardRef(({className:e,...t},n)=>h.jsx(yi,{ref:n,className:ue("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(qo,{className:"h-4 w-4"})}));Vi.displayName=yi.displayName;const qi=C.forwardRef(({className:e,...t},n)=>h.jsx(xi,{ref:n,className:ue("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(lr,{className:"h-4 w-4"})}));qi.displayName=xi.displayName;const Wi=C.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>h.jsx(Uo,{children:h.jsxs(gi,{ref:s,className:ue("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(Vi,{}),h.jsx(Ko,{className:ue("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),h.jsx(qi,{})]})}));Wi.displayName=gi.displayName;const Gi=C.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(mi,{ref:r,className:ue("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(Ho,{children:h.jsx(ur,{className:"h-4 w-4"})})}),h.jsx(Vo,{children:t})]}));Gi.displayName=mi.displayName;const Au=Zl,Eu=eu,Lu=tu,Qi=C.forwardRef(({className:e,sideOffset:t=4,...n},r)=>h.jsx(nu,{children:h.jsx(Ei,{ref:r,sideOffset:t,className:ue("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})}));Qi.displayName=Ei.displayName;const Nt={Popover:Cu,PopoverAnchor:Tu,PopoverContent:Ki,PopoverTrigger:Iu,Input:Ui,Select:Mu,SelectContent:Wi,SelectItem:Gi,SelectTrigger:Hi,SelectValue:Ru,Tooltip:Eu,TooltipContent:Qi,TooltipProvider:Au,TooltipTrigger:Lu},Nu=680,Pu=.82,ju=560;function Du(e){const{Popover:t,PopoverAnchor:n,PopoverContent:r}=Nt,{elementRef:s,width:i}=vu(),a=C.useRef(null),{isOpen:o,isLoading:l,items:u,activeIndex:c,activeItem:d,texts:p,onSelectItem:f,onOpenChange:m,onSetActiveIndex:y}=e,S=C.useMemo(()=>{if(i)return Math.min(i>ju?i*Pu:i,Nu)},[i]);return $i({containerRef:a,activeIndex:c,itemCount:u.length,isEnabled:o&&!l,getItemSelector:g=>`[data-slash-index="${g}"]`}),h.jsxs(t,{open:o,onOpenChange:m,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:l?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}),u.length===0?h.jsx("div",{className:"px-2 text-xs text-gray-400",children:p.slashEmptyLabel}):h.jsx("div",{className:"space-y-1",children:u.map((g,x)=>{const w=x===c;return h.jsxs("button",{type:"button",role:"option","aria-selected":w,"data-slash-index":x,onMouseEnter:()=>y(x),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 _u=Wo("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"}}),Vt=C.forwardRef(({className:e,variant:t,size:n,...r},s)=>h.jsx("button",{className:ue(_u({variant:t,size:n,className:e})),ref:s,...r}));Vt.displayName="ChatButton";function qr(){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 Ou(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Nt;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(Vt,{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(qr,{})}):h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:h.jsx("span",{children:h.jsx(Vt,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,disabled:!0,children:h.jsx(qr,{})})})}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:e.stopHint})})]})}):h.jsx(Vt,{size:"icon",className:"h-8 w-8 rounded-full","aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:h.jsx(Go,{className:"h-5 w-5"})})})]})}function Fu(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 zu(e){const{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:s}=Nt,{picker:i}=e,a=C.useRef(null),o=C.useId(),[l,u]=C.useState(""),[c,d]=C.useState(0),p=C.useMemo(()=>new Set(i.selectedKeys),[i.selectedKeys]),f=i.selectedKeys.length,m=C.useMemo(()=>Fu(i.options,l),[i.options,l]);C.useEffect(()=>{d(0)},[l]),C.useEffect(()=>{d(g=>m.length===0?0:Math.min(g,m.length-1))},[m.length]),$i({containerRef:a,activeIndex:c,itemCount:m.length,isEnabled:m.length>0,getItemSelector:g=>`[data-skill-index="${g}"]`});const y=g=>{if(p.has(g)){i.onSelectedKeysChange(i.selectedKeys.filter(x=>x!==g));return}i.onSelectedKeysChange([...i.selectedKeys,g])},S=g=>{if(m.length!==0){if(g.key==="ArrowDown"){g.preventDefault(),d(x=>Math.min(x+1,m.length-1));return}if(g.key==="ArrowUp"){g.preventDefault(),d(x=>Math.max(x-1,0));return}if(g.key==="Enter"){g.preventDefault();const x=m[c];x&&y(x.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(cr,{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(dr,{className:"pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400"}),h.jsx(t,{value:l,onChange:g=>u(g.target.value),onKeyDown:S,placeholder:i.searchPlaceholder,role:"combobox","aria-controls":o,"aria-expanded":"true","aria-autocomplete":"list","aria-activedescendant":m[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}):m.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:m.map((g,x)=>{const w=p.has(g.key),I=x===c;return h.jsxs("button",{type:"button",id:`${o}-option-${x}`,role:"option","aria-selected":w,"data-skill-index":x,onClick:()=>y(g.key),onMouseEnter:()=>d(x),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${I?"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(bi,{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(ur,{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(Qo,{className:"h-3 w-3"})]})}):null]})]})}function Xi({icon:e}){return e==="sparkles"?h.jsx(Yo,{className:"h-3.5 w-3.5 shrink-0 text-primary"}):e==="brain"?h.jsx(Jo,{className:"h-3.5 w-3.5 shrink-0 text-gray-500"}):null}function Bu({icon:e}){return e==="paperclip"?h.jsx(Xo,{className:"h-4 w-4"}):h.jsx(Xi,{icon:e})}function $u(e){return e==="model"?"min-w-[220px]":e==="session-type"?"min-w-[140px]":e==="thinking"?"min-w-[150px]":""}function Uu(e){return e==="model"?"w-[320px]":e==="session-type"?"w-[220px]":e==="thinking"?"w-[180px]":""}function Ku({item:e}){const{Select:t,SelectContent:n,SelectItem:r,SelectTrigger:s,SelectValue:i}=Nt;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 ${$u(e.key)}`,children:e.selectedLabel?h.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-left",children:[h.jsx(Xi,{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:Uu(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 Hu(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Nt;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(zu,{picker:e.skillPicker}):null,e.selects.map(a=>h.jsx(Ku,{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(Bu,{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(Ou,{...e.actions})]})}const Vu="";function Yi(){return`composer-${Math.random().toString(36).slice(2,10)}`}function Rt(e=""){return{id:Yi(),type:"text",text:e}}function Ji(e){return{id:Yi(),type:"token",tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function ft(e){return e.type==="text"?e.text.length:1}function Zi(){return[Rt("")]}function qu(e){return[Rt(e)]}function nn(e){const t=[];for(const n of e){if(n.type==="text"){if(n.text.length===0)continue;const r=t[t.length-1];if((r==null?void 0:r.type)==="text"){t[t.length-1]={...r,text:r.text+n.text};continue}}t.push(n)}return t.length===0?Zi():t}function Wu(e){return e.map(t=>t.type==="text"?t.text:Vu).join("")}function Gu(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ea(e,t){const n=[],r=new Set;for(const s of e)s.type!=="token"||s.tokenKind!==t||r.has(s.tokenKey)||(r.add(s.tokenKey),n.push(s.tokenKey));return n}function Qu(e,t,n,r){const s=Math.max(0,n-t),i=Math.max(0,t+e.text.length-r),a=[];return s>0&&a.push({...e,text:e.text.slice(0,s)}),i>0&&a.push({...e,text:e.text.slice(e.text.length-i)}),a}function $n(e,t,n,r){const s=Math.max(0,t),i=Math.max(s,n),a=[];let o=0,l=!1;for(const u of e){const c=ft(u),d=o,p=o+c;if(s===i?p<s||d>i:p<=s||d>=i){!l&&d>=i&&(a.push(...r),l=!0),a.push(u),o=p;continue}if(u.type==="text"){const y=Qu(u,d,s,i);y[0]&&a.push(y[0]),l||(a.push(...r),l=!0),y[1]&&a.push(y[1])}else!l&&s<=d&&(a.push(...r),l=!0);o=p}return l||a.push(...r),nn(a)}function Xu(e,t){return nn(e.filter(n=>n.type!=="token"||!t(n)))}function at(e,t){if(!t||t.start!==t.end)return null;const n=Wu(e),r=t.end,s=n.slice(0,r),i=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(s);if(!i)return null;const a=r-i[0].length+(i[0].startsWith("/")?0:1);return{query:(i[1]??"").trim().toLowerCase(),start:a,end:r}}function Yu(e,t,n){return e?e.start<n&&e.end>t:!1}const Wr=188;function Ju(e){return e.tokenKind==="file"?Zo:bi}function ta(e){const t=new Map;let n=0;for(const r of e)t.set(r.id,n),n+=ft(r);return t}function Zu(e,t){let n=t;for(;n&&n.parentNode!==e;)n=n.parentNode;return n?Array.prototype.indexOf.call(e.childNodes,n):e.childNodes.length}function Un(e,t,n,r,s){var u,c;if(t===e){let d=0;for(let p=0;p<n;p+=1){const f=e.childNodes[p],m=(u=f==null?void 0:f.dataset)==null?void 0:u.composerNodeId;if(!m)continue;const y=r.find(S=>S.id===m);y&&(d+=ft(y))}return d}const i=t instanceof HTMLElement?t.closest("[data-composer-node-id]"):((c=t.parentElement)==null?void 0:c.closest("[data-composer-node-id]"))??null;if(!(i instanceof HTMLElement)){const d=Zu(e,t);return Un(e,e,d,r,s)}const a=i.dataset.composerNodeId;if(!a)return 0;const o=r.find(d=>d.id===a),l=s.get(a)??0;return o?o.type==="text"?t.nodeType===Node.TEXT_NODE?l+Math.min(n,o.text.length):t===i?l+(n>0?o.text.length:0):l+o.text.length:t===i?l+(n>0?1:0):l+1:l}function Gr(e,t){const n=window.getSelection();if(!n||n.rangeCount===0)return null;const r=n.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;const s=ta(t),i=Un(e,r.startContainer,r.startOffset,t,s),a=Un(e,r.endContainer,r.endOffset,t,s);return{start:Math.min(i,a),end:Math.max(i,a)}}function ec(e,t,n){if(!n)return;const r=window.getSelection();if(!r)return;const s=l=>{let u=0;for(let c=0;c<t.length;c+=1){const d=t[c],p=ft(d),f=u,m=u+p,y=e.childNodes[c];if(!y){u=m;continue}if(d.type==="text"){if(l<=m)return{container:y.firstChild??y,offset:Math.max(0,Math.min(l-f,d.text.length))}}else{if(l<=f)return{container:e,offset:c};if(l<=m)return{container:e,offset:c+1}}u=m}return{container:e,offset:e.childNodes.length}},i=s(n.start),a=s(n.end),o=document.createRange();o.setStart(i.container,i.offset),o.setEnd(a.container,a.offset),r.removeAllRanges(),r.addRange(o)}function tc(e){const t=[];for(const n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(Rt(n.textContent??""));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType==="token"){const i=n.dataset.composerTokenKind,a=n.dataset.composerTokenKey,o=n.dataset.composerLabel;i&&a&&o&&t.push({id:n.dataset.composerNodeId??Ji({tokenKind:i,tokenKey:a,label:o}).id,type:"token",tokenKind:i,tokenKey:a,label:o});continue}const s=n.textContent??"";t.push({id:n.dataset.composerNodeId??Rt(s).id,type:"text",text:s})}return nn(t)}function Qr(e,t,n){const r=t??{start:0,end:0},s=$n(e,r.start,r.end,[Rt(n)]),i=r.start+n.length;return{nodes:s,selection:{start:i,end:i}}}const nc=C.forwardRef(function(t,n){const r=C.useRef(null),s=C.useRef(null),[i,a]=C.useState(null),o=C.useMemo(()=>ea(t.nodes,"skill"),[t.nodes]),l=t.slashItems[t.activeSlashIndex]??null,u=C.useMemo(()=>ta(t.nodes),[t.nodes]),c=C.useMemo(()=>t.nodes.reduce((x,w)=>x+ft(w),0),[t.nodes]),d=C.useCallback(()=>{var I,R;const x=r.current;if(!x)return;const w=Gr(x,t.nodes);s.current=w,a(w),(R=t.onSlashQueryChange)==null||R.call(t,((I=at(t.nodes,w))==null?void 0:I.query)??null),t.onSlashOpenChange(at(t.nodes,w)!==null)},[t]);C.useLayoutEffect(()=>{const x=r.current;!x||document.activeElement!==x||ec(x,t.nodes,s.current)},[t.nodes]),C.useLayoutEffect(()=>{const x=r.current;x&&(x.style.maxHeight=`${Wr}px`,x.style.overflowY=x.scrollHeight>Wr?"auto":"hidden")},[t.nodes]);const p=C.useCallback((x,w)=>{s.current=w??s.current,a(s.current),t.onNodesChange(nn(x))},[t]),f=C.useCallback((x,w)=>{var F,T,L;if(o.includes(x))return;const I=at(t.nodes,s.current),R=(I==null?void 0:I.start)??((F=s.current)==null?void 0:F.start)??t.nodes.reduce((D,$)=>D+ft($),0),v=(I==null?void 0:I.end)??((T=s.current)==null?void 0:T.end)??R,N=$n(t.nodes,R,v,[Ji({tokenKind:"skill",tokenKey:x,label:w})]),P=R+1;p(N,{start:P,end:P}),(L=t.onSlashQueryChange)==null||L.call(t,null),t.onSlashOpenChange(!1)},[p,t,o]),m=C.useCallback((x,w)=>{const I=new Map(w.map(N=>[N.key,N])),R=x.find(N=>!o.includes(N));if(R){const N=I.get(R);f(R,(N==null?void 0:N.label)??R);return}const v=o.find(N=>!x.includes(N));if(v){const N=Xu(t.nodes,P=>P.tokenKind==="skill"&&P.tokenKey===v);p(N,s.current)}},[p,f,t.nodes,o]);C.useImperativeHandle(n,()=>({insertSlashItem:x=>{x.value&&f(x.value,x.title)},syncSelectedSkills:m}),[f,m]);const y=C.useCallback(x=>{var v,N;const w=x.currentTarget,I=tc(w),R=Gr(w,I);s.current=R,a(R),t.onNodesChange(I),(N=t.onSlashQueryChange)==null||N.call(t,((v=at(I,R))==null?void 0:v.query)??null),t.onSlashOpenChange(at(I,R)!==null)},[t]),S=C.useCallback(x=>{var R;const I=at(t.nodes,s.current)!==null;if(I&&t.slashItems.length>0){if(x.key==="ArrowDown"){x.preventDefault(),t.onSlashActiveIndexChange((t.activeSlashIndex+1)%t.slashItems.length);return}if(x.key==="ArrowUp"){x.preventDefault(),t.onSlashActiveIndexChange((t.activeSlashIndex-1+t.slashItems.length)%t.slashItems.length);return}if(x.key==="Enter"&&!x.shiftKey||x.key==="Tab"){x.preventDefault(),l&&f(l.value??l.key,l.title);return}}if(x.key==="Escape"){if(I){x.preventDefault(),(R=t.onSlashQueryChange)==null||R.call(t,null),t.onSlashOpenChange(!1);return}t.actions.isSending&&t.actions.canStopGeneration&&(x.preventDefault(),t.actions.onStop());return}if(x.key==="Enter"&&x.shiftKey){x.preventDefault();const v=Qr(t.nodes,s.current,`
2
+ `);p(v.nodes,v.selection);return}if(x.key==="Enter"){x.preventDefault(),t.actions.onSend();return}if(!x.nativeEvent.isComposing&&(x.key==="Backspace"||x.key==="Delete")){const v=s.current??{start:c,end:c},N=v.start===v.end;let P=v.start,F=v.end;if(N)if(x.key==="Backspace"&&v.start>0)P=v.start-1;else if(x.key==="Delete")F=v.end+1;else return;x.preventDefault();const T=$n(t.nodes,P,F,[]);p(T,{start:P,end:P})}},[l,p,c,f,t]),g=C.useCallback(x=>{const w=x.clipboardData.getData("text/plain");if(!w)return;x.preventDefault();const I=Qr(t.nodes,s.current,w);p(I.nodes,I.selection)},[p,t.nodes]);return h.jsx("div",{className:"px-4 py-2.5",children:h.jsx("div",{className:"min-h-[60px]",children:h.jsx("div",{ref:r,contentEditable:!t.disabled,suppressContentEditableWarning:!0,role:"textbox","aria-multiline":"true","data-placeholder":t.placeholder,onInput:y,onKeyDown:S,onKeyUp:d,onMouseUp:d,onFocus:d,onBlur:()=>{a(null),t.onSlashOpenChange(!1)},onPaste:g,className:"min-h-7 max-h-[188px] w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent py-0.5 text-sm leading-6 text-gray-800 outline-none empty:before:pointer-events-none empty:before:text-gray-400 empty:before:content-[attr(data-placeholder)]",children:t.nodes.map(x=>{if(x.type==="text")return x.text.length===0?null:h.jsx("span",{"data-composer-node-id":x.id,"data-composer-node-type":"text",children:x.text},x.id);const w=Ju(x),I=u.get(x.id)??0,R=Yu(i,I,I+1);return h.jsxs("span",{contentEditable:!1,"data-composer-node-id":x.id,"data-composer-node-type":"token","data-composer-token-kind":x.tokenKind,"data-composer-token-key":x.tokenKey,"data-composer-label":x.label,className:`mx-[2px] inline-flex h-7 max-w-full select-none items-center gap-1.5 rounded-lg border px-2 align-baseline text-[11px] font-medium transition ${R?"border-primary/30 bg-primary/18 text-primary":"border-primary/12 bg-primary/8 text-primary"}`,children:[h.jsx(w,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-primary/70"}),h.jsx("span",{className:"truncate",children:x.label})]},x.id)})})})})});function rc({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 sc(e){const t=C.useRef(null),[n,r]=C.useState(null),[s,i]=C.useState(0),a=n!==null,o=e.slashMenu.items[s]??null;C.useEffect(()=>{i(u=>e.slashMenu.items.length===0?0:Math.min(u,e.slashMenu.items.length-1))},[e.slashMenu.items.length]),C.useEffect(()=>{n!==null&&i(0)},[n]);const l=C.useMemo(()=>e.toolbar.skillPicker?{...e.toolbar,skillPicker:{...e.toolbar.skillPicker,onSelectedKeysChange:u=>{var c,d;(d=t.current)==null||d.syncSelectedSkills(u,((c=e.toolbar.skillPicker)==null?void 0:c.options)??[])}}}:e.toolbar,[e.toolbar]);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(nc,{ref:t,nodes:e.composer.nodes,placeholder:e.composer.placeholder,disabled:e.composer.disabled,slashItems:e.slashMenu.items,actions:e.toolbar.actions,activeSlashIndex:s,onNodesChange:e.composer.onNodesChange,onSlashQueryChange:u=>{var c,d;r(u),(d=(c=e.composer).onSlashQueryChange)==null||d.call(c,u)},onSlashOpenChange:u=>{u||r(null)},onSlashActiveIndexChange:i}),h.jsx(Du,{isOpen:a,isLoading:e.slashMenu.isLoading,items:e.slashMenu.items,activeIndex:s,activeItem:o,texts:e.slashMenu.texts,onSelectItem:u=>{var c;(c=t.current)==null||c.insertSlashItem(u)},onOpenChange:u=>{u||r(null)},onSetActiveIndex:i})]}),h.jsx(rc,{hint:e.hint}),h.jsx(Hu,{...l})]})})})}function dn({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(el,{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(Si,{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(ki,{className:"h-4 w-4"})})}function ic(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const ac=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oc=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,lc={};function Xr(e,t){return(lc.jsx?oc:ac).test(e)}const uc=/[ \t\n\f\r]/g;function cc(e){return typeof e=="object"?e.type==="text"?Yr(e.value):!1:Yr(e)}function Yr(e){return e.replace(uc,"")===""}class Pt{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Pt.prototype.normal={};Pt.prototype.property={};Pt.prototype.space=void 0;function na(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new Pt(n,r,t)}function Kn(e){return e.toLowerCase()}class ve{constructor(t,n){this.attribute=n,this.property=t}}ve.prototype.attribute="";ve.prototype.booleanish=!1;ve.prototype.boolean=!1;ve.prototype.commaOrSpaceSeparated=!1;ve.prototype.commaSeparated=!1;ve.prototype.defined=!1;ve.prototype.mustUseProperty=!1;ve.prototype.number=!1;ve.prototype.overloadedBoolean=!1;ve.prototype.property="";ve.prototype.spaceSeparated=!1;ve.prototype.space=void 0;let dc=0;const H=st(),oe=st(),Hn=st(),E=st(),Z=st(),dt=st(),Ie=st();function st(){return 2**++dc}const Vn=Object.freeze(Object.defineProperty({__proto__:null,boolean:H,booleanish:oe,commaOrSpaceSeparated:Ie,commaSeparated:dt,number:E,overloadedBoolean:Hn,spaceSeparated:Z},Symbol.toStringTag,{value:"Module"})),hn=Object.keys(Vn);class xr extends ve{constructor(t,n,r,s){let i=-1;if(super(t,n),Jr(this,"space",s),typeof r=="number")for(;++i<hn.length;){const a=hn[i];Jr(this,hn[i],(r&Vn[a])===Vn[a])}}}xr.prototype.defined=!0;function Jr(e,t,n){n&&(e[t]=n)}function gt(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new xr(r,e.transform(e.attributes||{},r),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[Kn(r)]=r,n[Kn(i.attribute)]=r}return new Pt(t,n,e.space)}const ra=gt({properties:{ariaActiveDescendant:null,ariaAtomic:oe,ariaAutoComplete:null,ariaBusy:oe,ariaChecked:oe,ariaColCount:E,ariaColIndex:E,ariaColSpan:E,ariaControls:Z,ariaCurrent:null,ariaDescribedBy:Z,ariaDetails:null,ariaDisabled:oe,ariaDropEffect:Z,ariaErrorMessage:null,ariaExpanded:oe,ariaFlowTo:Z,ariaGrabbed:oe,ariaHasPopup:null,ariaHidden:oe,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Z,ariaLevel:E,ariaLive:null,ariaModal:oe,ariaMultiLine:oe,ariaMultiSelectable:oe,ariaOrientation:null,ariaOwns:Z,ariaPlaceholder:null,ariaPosInSet:E,ariaPressed:oe,ariaReadOnly:oe,ariaRelevant:null,ariaRequired:oe,ariaRoleDescription:Z,ariaRowCount:E,ariaRowIndex:E,ariaRowSpan:E,ariaSelected:oe,ariaSetSize:E,ariaSort:null,ariaValueMax:E,ariaValueMin:E,ariaValueNow:E,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function sa(e,t){return t in e?e[t]:t}function ia(e,t){return sa(e,t.toLowerCase())}const hc=gt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:dt,acceptCharset:Z,accessKey:Z,action:null,allow:null,allowFullScreen:H,allowPaymentRequest:H,allowUserMedia:H,alt:null,as:null,async:H,autoCapitalize:null,autoComplete:Z,autoFocus:H,autoPlay:H,blocking:Z,capture:null,charSet:null,checked:H,cite:null,className:Z,cols:E,colSpan:null,content:null,contentEditable:oe,controls:H,controlsList:Z,coords:E|dt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:H,defer:H,dir:null,dirName:null,disabled:H,download:Hn,draggable:oe,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:H,formTarget:null,headers:Z,height:E,hidden:Hn,high:E,href:null,hrefLang:null,htmlFor:Z,httpEquiv:Z,id:null,imageSizes:null,imageSrcSet:null,inert:H,inputMode:null,integrity:null,is:null,isMap:H,itemId:null,itemProp:Z,itemRef:Z,itemScope:H,itemType:Z,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:H,low:E,manifest:null,max:null,maxLength:E,media:null,method:null,min:null,minLength:E,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:E,pattern:null,ping:Z,placeholder:null,playsInline:H,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:H,referrerPolicy:null,rel:Z,required:H,reversed:H,rows:E,rowSpan:E,sandbox:Z,scope:null,scoped:H,seamless:H,selected:H,shadowRootClonable:H,shadowRootDelegatesFocus:H,shadowRootMode:null,shape:null,size:E,sizes:null,slot:null,span:E,spellCheck:oe,src:null,srcDoc:null,srcLang:null,srcSet:null,start:E,step:null,style:null,tabIndex:E,target:null,title:null,translate:null,type:null,typeMustMatch:H,useMap:null,value:oe,width:E,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Z,axis:null,background:null,bgColor:null,border:E,borderColor:null,bottomMargin:E,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:E,leftMargin:E,link:null,longDesc:null,lowSrc:null,marginHeight:E,marginWidth:E,noResize:H,noHref:H,noShade:H,noWrap:H,object:null,profile:null,prompt:null,rev:null,rightMargin:E,rules:null,scheme:null,scrolling:oe,standby:null,summary:null,text:null,topMargin:E,valueType:null,version:null,vAlign:null,vLink:null,vSpace:E,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:H,disableRemotePlayback:H,prefix:null,property:null,results:E,security:null,unselectable:null},space:"html",transform:ia}),fc=gt({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:Ie,accentHeight:E,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:E,amplitude:E,arabicForm:null,ascent:E,attributeName:null,attributeType:null,azimuth:E,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:E,by:null,calcMode:null,capHeight:E,className:Z,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:E,diffuseConstant:E,direction:null,display:null,dur:null,divisor:E,dominantBaseline:null,download:H,dx:null,dy:null,edgeMode:null,editable:null,elevation:E,enableBackground:null,end:null,event:null,exponent:E,externalResourcesRequired:null,fill:null,fillOpacity:E,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:dt,g2:dt,glyphName:dt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:E,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:E,horizOriginX:E,horizOriginY:E,id:null,ideographic:E,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:E,k:E,k1:E,k2:E,k3:E,k4:E,kernelMatrix:Ie,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:E,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:E,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:E,overlineThickness:E,paintOrder:null,panose1:null,path:null,pathLength:E,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Z,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:E,pointsAtY:E,pointsAtZ:E,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ie,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ie,rev:Ie,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ie,requiredFeatures:Ie,requiredFonts:Ie,requiredFormats:Ie,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:E,specularExponent:E,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:E,strikethroughThickness:E,string:null,stroke:null,strokeDashArray:Ie,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:E,strokeOpacity:E,strokeWidth:null,style:null,surfaceScale:E,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ie,tabIndex:E,tableValues:null,target:null,targetX:E,targetY:E,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ie,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:E,underlineThickness:E,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:E,values:null,vAlphabetic:E,vMathematical:E,vectorEffect:null,vHanging:E,vIdeographic:E,version:null,vertAdvY:E,vertOriginX:E,vertOriginY:E,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:E,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:sa}),aa=gt({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()}}),oa=gt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:ia}),la=gt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),pc={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"},gc=/[A-Z]/g,Zr=/-[a-z]/g,mc=/^data[-\w.:]+$/i;function yc(e,t){const n=Kn(t);let r=t,s=ve;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&mc.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Zr,bc);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Zr.test(i)){let a=i.replace(gc,xc);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}s=xr}return new s(r,t)}function xc(e){return"-"+e.toLowerCase()}function bc(e){return e.charAt(1).toUpperCase()}const Sc=na([ra,hc,aa,oa,la],"html"),br=na([ra,fc,aa,oa,la],"svg");function kc(e){return e.join(" ").trim()}var ot={},fn,es;function wc(){if(es)return fn;es=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
3
+ `,u="/",c="*",d="",p="comment",f="declaration";function m(S,g){if(typeof S!="string")throw new TypeError("First argument must be a string");if(!S)return[];g=g||{};var x=1,w=1;function I(z){var _=z.match(t);_&&(x+=_.length);var W=z.lastIndexOf(l);w=~W?z.length-W:w+z.length}function R(){var z={line:x,column:w};return function(_){return _.position=new v(z),F(),_}}function v(z){this.start=z,this.end={line:x,column:w},this.source=g.source}v.prototype.content=S;function N(z){var _=new Error(g.source+":"+x+":"+w+": "+z);if(_.reason=z,_.filename=g.source,_.line=x,_.column=w,_.source=S,!g.silent)throw _}function P(z){var _=z.exec(S);if(_){var W=_[0];return I(W),S=S.slice(W.length),_}}function F(){P(n)}function T(z){var _;for(z=z||[];_=L();)_!==!1&&z.push(_);return z}function L(){var z=R();if(!(u!=S.charAt(0)||c!=S.charAt(1))){for(var _=2;d!=S.charAt(_)&&(c!=S.charAt(_)||u!=S.charAt(_+1));)++_;if(_+=2,d===S.charAt(_-1))return N("End of comment missing");var W=S.slice(2,_-2);return w+=2,I(W),S=S.slice(_),w+=2,z({type:p,comment:W})}}function D(){var z=R(),_=P(r);if(_){if(L(),!P(s))return N("property missing ':'");var W=P(i),ee=z({type:f,property:y(_[0].replace(e,d)),value:W?y(W[0].replace(e,d)):d});return P(a),ee}}function $(){var z=[];T(z);for(var _;_=D();)_!==!1&&(z.push(_),T(z));return z}return F(),$()}function y(S){return S?S.replace(o,d):d}return fn=m,fn}var ts;function vc(){if(ts)return ot;ts=1;var e=ot&&ot.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ot,"__esModule",{value:!0}),ot.default=n;const t=e(wc());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(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;o?s(u,c,l):c&&(i=i||{},i[u]=c)}),i}return ot}var bt={},ns;function Cc(){if(ns)return bt;ns=1,Object.defineProperty(bt,"__esModule",{value:!0}),bt.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,s=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},a=function(u,c){return c.toUpperCase()},o=function(u,c){return"".concat(c,"-")},l=function(u,c){return c===void 0&&(c={}),i(u)?u:(u=u.toLowerCase(),c.reactCompat?u=u.replace(s,o):u=u.replace(r,o),u.replace(t,a))};return bt.camelCase=l,bt}var St,rs;function Ic(){if(rs)return St;rs=1;var e=St&&St.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},t=e(vc()),n=Cc();function r(s,i){var a={};return!s||typeof s!="string"||(0,t.default)(s,function(o,l){o&&l&&(a[(0,n.camelCase)(o,i)]=l)}),a}return r.default=r,St=r,St}var Tc=Ic();const Mc=wi(Tc),ua=ca("end"),Sr=ca("start");function ca(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 Rc(e){const t=Sr(e),n=ua(e);if(t&&n)return{start:t,end:n}}function It(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?ss(e.position):"start"in e||"end"in e?ss(e):"line"in e||"column"in e?qn(e):""}function qn(e){return is(e&&e.line)+":"+is(e&&e.column)}function ss(e){return qn(e&&e.start)+"-"+qn(e&&e.end)}function is(e){return e&&typeof e=="number"?e:1}class me 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 l=r.indexOf(":");l===-1?i.ruleId=r:(i.source=r.slice(0,l),i.ruleId=r.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.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=It(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}}me.prototype.file="";me.prototype.name="";me.prototype.reason="";me.prototype.message="";me.prototype.stack="";me.prototype.column=void 0;me.prototype.line=void 0;me.prototype.ancestors=void 0;me.prototype.cause=void 0;me.prototype.fatal=void 0;me.prototype.place=void 0;me.prototype.ruleId=void 0;me.prototype.source=void 0;const kr={}.hasOwnProperty,Ac=new Map,Ec=/[A-Z]/g,Lc=new Set(["table","tbody","thead","tfoot","tr"]),Nc=new Set(["td","th"]),da="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Pc(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=$c(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=Bc(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"?br:Sc,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=ha(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function ha(e,t,n){if(t.type==="element")return jc(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Dc(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Oc(e,t,n);if(t.type==="mdxjsEsm")return _c(e,t);if(t.type==="root")return Fc(e,t,n);if(t.type==="text")return zc(e,t)}function jc(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=br,e.schema=s),e.ancestors.push(t);const i=pa(e,t.tagName,!1),a=Uc(e,t);let o=vr(e,t);return Lc.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!cc(l):!0})),fa(e,a,i,t),wr(a,o),e.ancestors.pop(),e.schema=r,e.create(t,i,a,n)}function Dc(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)}At(e,t.position)}function _c(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);At(e,t.position)}function Oc(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=br,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:pa(e,t.name,!0),a=Kc(e,t),o=vr(e,t);return fa(e,a,i,t),wr(a,o),e.ancestors.pop(),e.schema=r,e.create(t,i,a,n)}function Fc(e,t,n){const r={};return wr(r,vr(e,t)),e.create(t,e.Fragment,r,n)}function zc(e,t){return t.value}function fa(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function wr(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Bc(e,t,n){return r;function r(s,i,a,o){const u=Array.isArray(a.children)?n:t;return o?u(i,a,o):u(i,a)}}function $c(e,t){return n;function n(r,s,i,a){const o=Array.isArray(i.children),l=Sr(r);return t(s,i,a,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Uc(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&kr.call(t.properties,s)){const i=Hc(e,s,t.properties[s]);if(i){const[a,o]=i;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&Nc.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 Kc(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 At(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 At(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function vr(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:Ac;for(;++r<t.children.length;){const i=t.children[r];let a;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=s.get(l)||0;a=l+"-"+u,s.set(l,u+1)}}const o=ha(e,i,a);o!==void 0&&n.push(o)}return n}function Hc(e,t,n){const r=yc(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?ic(n):kc(n)),r.property==="style"){let s=typeof n=="object"?n:Vc(e,String(n));return e.stylePropertyNameCase==="css"&&(s=qc(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&r.space?pc[r.property]||r.property:r.attribute,n]}}function Vc(e,t){try{return Mc(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,s=new me("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=da+"#cannot-parse-style-attribute",s}}function pa(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=Xr(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=Xr(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const s=r.value;return kr.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(r);At(e)}function At(e,t){const n=new me("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=da+"#cannot-handle-mdx-estrees-without-createevaluater",n}function qc(e){const t={};let n;for(n in e)kr.call(e,n)&&(t[Wc(n)]=e[n]);return t}function Wc(e){let t=e.replace(Ec,Gc);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Gc(e){return"-"+e.toLowerCase()}const pn={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"]},Qc={};function Cr(e,t){const n=Qc,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return ga(e,r,s)}function ga(e,t,n){if(Xc(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 as(e.children,t,n)}return Array.isArray(e)?as(e,t,n):""}function as(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=ga(e[s],t,n);return r.join("")}function Xc(e){return!!(e&&typeof e=="object")}const os=document.createElement("i");function Ir(e){const t="&"+e+";";os.innerHTML=t;const n=os.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Me(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 Le(e,t){return e.length>0?(Me(e,e.length,0,t),e):t}const ls={}.hasOwnProperty;function ma(e){const t={};let n=-1;for(;++n<e.length;)Yc(t,e[n]);return t}function Yc(e,t){let n;for(n in t){const s=(ls.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let a;if(i)for(a in i){ls.call(s,a)||(s[a]=[]);const o=i[a];Jc(s[a],Array.isArray(o)?o:o?[o]:[])}}}function Jc(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);Me(e,0,0,r)}function ya(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 De(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const be=Xe(/[A-Za-z]/),ge=Xe(/[\dA-Za-z]/),Zc=Xe(/[#-'*+\--9=?A-Z^-~]/);function Qt(e){return e!==null&&(e<32||e===127)}const Wn=Xe(/\d/),ed=Xe(/[\dA-Fa-f]/),td=Xe(/[!-/:-@[-`{-~]/);function B(e){return e!==null&&e<-2}function J(e){return e!==null&&(e<0||e===32)}function q(e){return e===-2||e===-1||e===32}const rn=Xe(new RegExp("\\p{P}|\\p{S}","u")),rt=Xe(/\s/);function Xe(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function mt(e){const t=[];let n=-1,r=0,s=0;for(;++n<e.length;){const i=e.charCodeAt(n);let a="";if(i===37&&ge(e.charCodeAt(n+1))&&ge(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(l){return q(l)?(e.enter(n),o(l)):t(l)}function o(l){return q(l)&&i++<s?(e.consume(l),o):(e.exit(n),t(l))}}const nd={tokenize:rd};function rd(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 l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,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 sd={tokenize:id},us={tokenize:ad};function id(e){const t=this,n=[];let r=0,s,i,a;return o;function o(w){if(r<n.length){const I=n[r];return t.containerState=I[1],e.attempt(I[0].continuation,l,u)(w)}return u(w)}function l(w){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&x();const I=t.events.length;let R=I,v;for(;R--;)if(t.events[R][0]==="exit"&&t.events[R][1].type==="chunkFlow"){v=t.events[R][1].end;break}g(r);let N=I;for(;N<t.events.length;)t.events[N][1].end={...v},N++;return Me(t.events,R+1,0,t.events.slice(I)),t.events.length=N,u(w)}return o(w)}function u(w){if(r===n.length){if(!s)return p(w);if(s.currentConstruct&&s.currentConstruct.concrete)return m(w);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(us,c,d)(w)}function c(w){return s&&x(),g(r),p(w)}function d(w){return t.parser.lazy[t.now().line]=r!==n.length,a=t.now().offset,m(w)}function p(w){return t.containerState={},e.attempt(us,f,m)(w)}function f(w){return r++,n.push([t.currentConstruct,t.containerState]),p(w)}function m(w){if(w===null){s&&x(),g(0),e.consume(w);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),y(w)}function y(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),y)}function S(w,I){const R=t.sliceStream(w);if(I&&R.push(null),w.previous=i,i&&(i.next=w),i=w,s.defineSkip(w.start),s.write(R),t.parser.lazy[w.start.line]){let v=s.events.length;for(;v--;)if(s.events[v][1].start.offset<a&&(!s.events[v][1].end||s.events[v][1].end.offset>a))return;const N=t.events.length;let P=N,F,T;for(;P--;)if(t.events[P][0]==="exit"&&t.events[P][1].type==="chunkFlow"){if(F){T=t.events[P][1].end;break}F=!0}for(g(r),v=N;v<t.events.length;)t.events[v][1].end={...T},v++;Me(t.events,P+1,0,t.events.slice(N)),t.events.length=v}}function g(w){let I=n.length;for(;I-- >w;){const R=n[I];t.containerState=R[1],R[0].exit.call(t,e)}n.length=w}function x(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function ad(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 pt(e){if(e===null||J(e)||rt(e))return 1;if(rn(e))return 2}function sn(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 Gn={name:"attention",resolveAll:od,tokenize:ld};function od(e,t){let n=-1,r,s,i,a,o,l,u,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;l=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};cs(d,-l),cs(p,l),a={type:l>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},o={type:l>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:p},i={type:l>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},s={type:l>1?"strong":"emphasis",start:{...a.start},end:{...o.end}},e[r][1].end={...a.start},e[n][1].start={...o.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Le(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Le(u,[["enter",s,t],["enter",a,t],["exit",a,t],["enter",i,t]]),u=Le(u,sn(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Le(u,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Le(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,Me(e,r-1,n-r+3,u),n=r+u.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function ld(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,s=pt(r);let i;return a;function a(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const u=e.exit("attentionSequence"),c=pt(l),d=!c||c===2&&s||n.includes(l),p=!s||s===2&&c||n.includes(r);return u._open=!!(i===42?d:d&&(s||!p)),u._close=!!(i===42?p:p&&(c||!d)),t(l)}}function cs(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const ud={name:"autolink",tokenize:cd};function cd(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 be(f)?(e.consume(f),a):f===64?n(f):u(f)}function a(f){return f===43||f===45||f===46||ge(f)?(r=1,o(f)):u(f)}function o(f){return f===58?(e.consume(f),r=0,l):(f===43||f===45||f===46||ge(f))&&r++<32?(e.consume(f),o):(r=0,u(f))}function l(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||Qt(f)?n(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),c):Zc(f)?(e.consume(f),u):n(f)}function c(f){return ge(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||ge(f))&&r++<63){const m=f===45?p:d;return e.consume(f),m}return n(f)}}const jt={partial:!0,tokenize:dd};function dd(e,t,n){return r;function r(i){return q(i)?X(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||B(i)?t(i):n(i)}}const xa={continuation:{tokenize:fd},exit:pd,name:"blockQuote",tokenize:hd};function hd(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 q(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function fd(e,t,n){const r=this;return s;function s(a){return q(a)?X(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(xa,t,n)(a)}}function pd(e){e.exit("blockQuote")}const ba={name:"characterEscape",tokenize:gd};function gd(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 td(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const Sa={name:"characterReference",tokenize:md};function md(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"),l}function l(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,a=ge,c(d))}function u(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=ed,c):(e.enter("characterReferenceValue"),i=7,a=Wn,c(d))}function c(d){if(d===59&&s){const p=e.exit("characterReferenceValue");return a===ge&&!Ir(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 ds={partial:!0,tokenize:xd},hs={concrete:!0,name:"codeFenced",tokenize:yd};function yd(e,t,n){const r=this,s={partial:!0,tokenize:R};let i=0,a=0,o;return l;function l(v){return u(v)}function u(v){const N=r.events[r.events.length-1];return i=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[1],!0).length:0,o=v,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(v)}function c(v){return v===o?(a++,e.consume(v),c):a<3?n(v):(e.exit("codeFencedFenceSequence"),q(v)?X(e,d,"whitespace")(v):d(v))}function d(v){return v===null||B(v)?(e.exit("codeFencedFence"),r.interrupt?t(v):e.check(ds,y,I)(v)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===null||B(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(v)):q(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),X(e,f,"whitespace")(v)):v===96&&v===o?n(v):(e.consume(v),p)}function f(v){return v===null||B(v)?d(v):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),m(v))}function m(v){return v===null||B(v)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(v)):v===96&&v===o?n(v):(e.consume(v),m)}function y(v){return e.attempt(s,I,S)(v)}function S(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),g}function g(v){return i>0&&q(v)?X(e,x,"linePrefix",i+1)(v):x(v)}function x(v){return v===null||B(v)?e.check(ds,y,I)(v):(e.enter("codeFlowValue"),w(v))}function w(v){return v===null||B(v)?(e.exit("codeFlowValue"),x(v)):(e.consume(v),w)}function I(v){return e.exit("codeFenced"),t(v)}function R(v,N,P){let F=0;return T;function T(_){return v.enter("lineEnding"),v.consume(_),v.exit("lineEnding"),L}function L(_){return v.enter("codeFencedFence"),q(_)?X(v,D,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):D(_)}function D(_){return _===o?(v.enter("codeFencedFenceSequence"),$(_)):P(_)}function $(_){return _===o?(F++,v.consume(_),$):F>=a?(v.exit("codeFencedFenceSequence"),q(_)?X(v,z,"whitespace")(_):z(_)):P(_)}function z(_){return _===null||B(_)?(v.exit("codeFencedFence"),N(_)):P(_)}}}function xd(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 gn={name:"codeIndented",tokenize:Sd},bd={partial:!0,tokenize:kd};function Sd(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),X(e,i,"linePrefix",5)(u)}function i(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?l(u):B(u)?e.attempt(bd,a,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||B(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function kd(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 wd={name:"codeText",previous:Cd,resolve:vd,tokenize:Id};function vd(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 Cd(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Id(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"),l(d))}function l(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),l):d===96?(i=e.enter("codeTextSequence"),s=0,c(d)):B(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||B(d)?(e.exit("codeTextData"),l(d)):(e.consume(d),u)}function c(d){return d===96?(e.consume(d),s++,c):s===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(i.type="codeTextData",u(d))}}class Td{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&&kt(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),kt(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),kt(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);kt(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);kt(this.left,n.reverse())}}}function kt(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 ka(e){const t={};let n=-1,r,s,i,a,o,l,u;const c=new Td(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"&&(l=r[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,Md(c,n)),n=t[n],u=!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 Me(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function Md(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,l=[],u={};let c,d,p=-1,f=n,m=0,y=0;const S=[y];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&&(y=p+1,S.push(y),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]),x=i.pop();l.push([x,x+g.length-1]),e.splice(x,2,g)}for(l.reverse(),p=-1;++p<l.length;)u[m+l[p][0]]=m+l[p][1],m+=l[p][1]-l[p][0]-1;return u}const Rd={resolve:Ed,tokenize:Ld},Ad={partial:!0,tokenize:Nd};function Ed(e){return ka(e),e}function Ld(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(Ad,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 Nd(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 wa(e,t,n,r,s,i,a,o,l){const u=l||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||Qt(g)?n(g):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),y(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?m:f)}function m(g){return g===60||g===62||g===92?(e.consume(g),f):f(g)}function y(g){return!c&&(g===null||g===41||J(g))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),t(g)):c<u&&g===40?(e.consume(g),c++,y):g===41?(e.consume(g),c--,y):g===null||g===32||g===40||Qt(g)?n(g):(e.consume(g),g===92?S:y)}function S(g){return g===40||g===41||g===92?(e.consume(g),y):y(g)}}function va(e,t,n,r,s,i){const a=this;let o=0,l;return u;function u(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&&!l||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),l||(l=!q(f)),f===92?p:d)}function p(f){return f===91||f===92||f===93?(e.consume(f),o++,d):d(f)}}function Ca(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,l):n(p)}function l(p){return p===a?(e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):(e.enter(i),u(p))}function u(p){return p===a?(e.exit(i),l(a)):p===null?n(p):B(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),X(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===a||p===null||B(p)?(e.exit("chunkString"),u(p)):(e.consume(p),p===92?d:c)}function d(p){return p===a||p===92?(e.consume(p),c):c(p)}}function Tt(e,t){let n;return r;function r(s){return B(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):q(s)?X(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const Pd={name:"definition",tokenize:Dd},jd={partial:!0,tokenize:_d};function Dd(e,t,n){const r=this;let s;return i;function i(f){return e.enter("definition"),a(f)}function a(f){return va.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return s=De(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):n(f)}function l(f){return J(f)?Tt(e,u)(f):u(f)}function u(f){return wa(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(jd,d,d)(f)}function d(f){return q(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 _d(e,t,n){return r;function r(o){return J(o)?Tt(e,s)(o):n(o)}function s(o){return Ca(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return q(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||B(o)?t(o):n(o)}}const Od={name:"hardBreakEscape",tokenize:Fd};function Fd(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 zd={name:"headingAtx",resolve:Bd,tokenize:$d};function Bd(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"},Me(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function $d(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||J(c)?(e.exit("atxHeadingSequence"),o(c)):n(c)}function o(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||B(c)?(e.exit("atxHeading"),t(c)):q(c)?X(e,o,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),o(c))}function u(c){return c===null||c===35||J(c)?(e.exit("atxHeadingText"),o(c)):(e.consume(c),u)}}const Ud=["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"],fs=["pre","script","style","textarea"],Kd={concrete:!0,name:"htmlFlow",resolveTo:qd,tokenize:Wd},Hd={partial:!0,tokenize:Qd},Vd={partial:!0,tokenize:Gd};function qd(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 Wd(e,t,n){const r=this;let s,i,a,o,l;return u;function u(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,y):b===63?(e.consume(b),s=3,r.interrupt?t:k):be(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,m):be(b)?(e.consume(b),s=4,r.interrupt?t:k):n(b)}function f(b){return b===45?(e.consume(b),r.interrupt?t:k):n(b)}function m(b){const ae="CDATA[";return b===ae.charCodeAt(o++)?(e.consume(b),o===ae.length?r.interrupt?t:D:m):n(b)}function y(b){return be(b)?(e.consume(b),a=String.fromCharCode(b),S):n(b)}function S(b){if(b===null||b===47||b===62||J(b)){const ae=b===47,ie=a.toLowerCase();return!ae&&!i&&fs.includes(ie)?(s=1,r.interrupt?t(b):D(b)):Ud.includes(a.toLowerCase())?(s=6,ae?(e.consume(b),g):r.interrupt?t(b):D(b)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(b):i?x(b):w(b))}return b===45||ge(b)?(e.consume(b),a+=String.fromCharCode(b),S):n(b)}function g(b){return b===62?(e.consume(b),r.interrupt?t:D):n(b)}function x(b){return q(b)?(e.consume(b),x):T(b)}function w(b){return b===47?(e.consume(b),T):b===58||b===95||be(b)?(e.consume(b),I):q(b)?(e.consume(b),w):T(b)}function I(b){return b===45||b===46||b===58||b===95||ge(b)?(e.consume(b),I):R(b)}function R(b){return b===61?(e.consume(b),v):q(b)?(e.consume(b),R):w(b)}function v(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),l=b,N):q(b)?(e.consume(b),v):P(b)}function N(b){return b===l?(e.consume(b),l=null,F):b===null||B(b)?n(b):(e.consume(b),N)}function P(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||J(b)?R(b):(e.consume(b),P)}function F(b){return b===47||b===62||q(b)?w(b):n(b)}function T(b){return b===62?(e.consume(b),L):n(b)}function L(b){return b===null||B(b)?D(b):q(b)?(e.consume(b),L):n(b)}function D(b){return b===45&&s===2?(e.consume(b),W):b===60&&s===1?(e.consume(b),ee):b===62&&s===4?(e.consume(b),pe):b===63&&s===3?(e.consume(b),k):b===93&&s===5?(e.consume(b),re):B(b)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(Hd,Se,$)(b)):b===null||B(b)?(e.exit("htmlFlowData"),$(b)):(e.consume(b),D)}function $(b){return e.check(Vd,z,Se)(b)}function z(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),_}function _(b){return b===null||B(b)?$(b):(e.enter("htmlFlowData"),D(b))}function W(b){return b===45?(e.consume(b),k):D(b)}function ee(b){return b===47?(e.consume(b),a="",de):D(b)}function de(b){if(b===62){const ae=a.toLowerCase();return fs.includes(ae)?(e.consume(b),pe):D(b)}return be(b)&&a.length<8?(e.consume(b),a+=String.fromCharCode(b),de):D(b)}function re(b){return b===93?(e.consume(b),k):D(b)}function k(b){return b===62?(e.consume(b),pe):b===45&&s===2?(e.consume(b),k):D(b)}function pe(b){return b===null||B(b)?(e.exit("htmlFlowData"),Se(b)):(e.consume(b),pe)}function Se(b){return e.exit("htmlFlow"),t(b)}}function Gd(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 Qd(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(jt,t,n)}}const Xd={name:"htmlText",tokenize:Yd};function Yd(e,t,n){const r=this;let s,i,a;return o;function o(k){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(k),l}function l(k){return k===33?(e.consume(k),u):k===47?(e.consume(k),R):k===63?(e.consume(k),w):be(k)?(e.consume(k),P):n(k)}function u(k){return k===45?(e.consume(k),c):k===91?(e.consume(k),i=0,m):be(k)?(e.consume(k),x):n(k)}function c(k){return k===45?(e.consume(k),f):n(k)}function d(k){return k===null?n(k):k===45?(e.consume(k),p):B(k)?(a=d,ee(k)):(e.consume(k),d)}function p(k){return k===45?(e.consume(k),f):d(k)}function f(k){return k===62?W(k):k===45?p(k):d(k)}function m(k){const pe="CDATA[";return k===pe.charCodeAt(i++)?(e.consume(k),i===pe.length?y:m):n(k)}function y(k){return k===null?n(k):k===93?(e.consume(k),S):B(k)?(a=y,ee(k)):(e.consume(k),y)}function S(k){return k===93?(e.consume(k),g):y(k)}function g(k){return k===62?W(k):k===93?(e.consume(k),g):y(k)}function x(k){return k===null||k===62?W(k):B(k)?(a=x,ee(k)):(e.consume(k),x)}function w(k){return k===null?n(k):k===63?(e.consume(k),I):B(k)?(a=w,ee(k)):(e.consume(k),w)}function I(k){return k===62?W(k):w(k)}function R(k){return be(k)?(e.consume(k),v):n(k)}function v(k){return k===45||ge(k)?(e.consume(k),v):N(k)}function N(k){return B(k)?(a=N,ee(k)):q(k)?(e.consume(k),N):W(k)}function P(k){return k===45||ge(k)?(e.consume(k),P):k===47||k===62||J(k)?F(k):n(k)}function F(k){return k===47?(e.consume(k),W):k===58||k===95||be(k)?(e.consume(k),T):B(k)?(a=F,ee(k)):q(k)?(e.consume(k),F):W(k)}function T(k){return k===45||k===46||k===58||k===95||ge(k)?(e.consume(k),T):L(k)}function L(k){return k===61?(e.consume(k),D):B(k)?(a=L,ee(k)):q(k)?(e.consume(k),L):F(k)}function D(k){return k===null||k===60||k===61||k===62||k===96?n(k):k===34||k===39?(e.consume(k),s=k,$):B(k)?(a=D,ee(k)):q(k)?(e.consume(k),D):(e.consume(k),z)}function $(k){return k===s?(e.consume(k),s=void 0,_):k===null?n(k):B(k)?(a=$,ee(k)):(e.consume(k),$)}function z(k){return k===null||k===34||k===39||k===60||k===61||k===96?n(k):k===47||k===62||J(k)?F(k):(e.consume(k),z)}function _(k){return k===47||k===62||J(k)?F(k):n(k)}function W(k){return k===62?(e.consume(k),e.exit("htmlTextData"),e.exit("htmlText"),t):n(k)}function ee(k){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),de}function de(k){return q(k)?X(e,re,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):re(k)}function re(k){return e.enter("htmlTextData"),a(k)}}const Tr={name:"labelEnd",resolveAll:th,resolveTo:nh,tokenize:rh},Jd={tokenize:sh},Zd={tokenize:ih},eh={tokenize:ah};function th(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&&Me(e,0,e.length,n),e}function nh(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 l={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={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",l,t],["enter",u,t]],o=Le(o,e.slice(i+1,i+r+3)),o=Le(o,[["enter",c,t]]),o=Le(o,sn(t.parser.constructs.insideSpan.null,e.slice(i+r+4,a-3),t)),o=Le(o,[["exit",c,t],e[a-2],e[a-1],["exit",u,t]]),o=Le(o,e.slice(a+1)),o=Le(o,[["exit",l,t]]),Me(e,i,e.length,o),e}function rh(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(De(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),l):n(p)}function l(p){return p===40?e.attempt(Jd,c,a?c:d)(p):p===91?e.attempt(Zd,c,a?u:d)(p):a?c(p):d(p)}function u(p){return e.attempt(eh,c,d)(p)}function c(p){return t(p)}function d(p){return i._balanced=!0,n(p)}}function sh(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 J(d)?Tt(e,i)(d):i(d)}function i(d){return d===41?c(d):wa(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return J(d)?Tt(e,l)(d):c(d)}function o(d){return n(d)}function l(d){return d===34||d===39||d===40?Ca(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return J(d)?Tt(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 ih(e,t,n){const r=this;return s;function s(o){return va.call(r,e,i,a,"reference","referenceMarker","referenceString")(o)}function i(o){return r.parser.defined.includes(De(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function a(o){return n(o)}}function ah(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 oh={name:"labelStartImage",resolveAll:Tr.resolveAll,tokenize:lh};function lh(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 uh={name:"labelStartLink",resolveAll:Tr.resolveAll,tokenize:ch};function ch(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 mn={name:"lineEnding",tokenize:dh};function dh(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),X(e,t,"linePrefix")}}const qt={name:"thematicBreak",tokenize:hh};function hh(e,t,n){let r=0,s;return i;function i(u){return e.enter("thematicBreak"),a(u)}function a(u){return s=u,o(u)}function o(u){return u===s?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||B(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===s?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),q(u)?X(e,o,"whitespace")(u):o(u))}}const we={continuation:{tokenize:mh},exit:xh,name:"list",tokenize:gh},fh={partial:!0,tokenize:bh},ph={partial:!0,tokenize:yh};function gh(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 m=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:Wn(f)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(qt,n,u)(f):u(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(f)}return n(f)}function l(f){return Wn(f)&&++a<10?(e.consume(f),l):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):n(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(jt,r.interrupt?n:c,e.attempt(fh,p,d))}function c(f){return r.containerState.initialBlankLine=!0,i++,p(f)}function d(f){return q(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 mh(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(jt,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||!q(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(ph,t,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(we,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function yh(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 xh(e){e.exit(this.containerState.type)}function bh(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!q(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const ps={name:"setextUnderline",resolveTo:Sh,tokenize:kh};function Sh(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 kh(e,t,n){const r=this;let s;return i;function i(u){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=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===s?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),q(u)?X(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||B(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const wh={tokenize:vh};function vh(e){const t=this,n=e.attempt(jt,r,e.attempt(this.parser.constructs.flowInitial,s,X(e,e.attempt(this.parser.constructs.flow,s,e.attempt(Rd,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 Ch={resolveAll:Ta()},Ih=Ia("string"),Th=Ia("text");function Ia(e){return{resolveAll:Ta(e==="text"?Mh: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 u(c)?i(c):o(c)}function o(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),i(c)):(n.consume(c),l)}function u(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 Ta(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 Mh(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,l;for(;i--;){const u=s[i];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(u===-2)l=!0,o++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(o=0),o){const u={type:n===e.length||l||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={...u.start},r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Rh={42:we,43:we,45:we,48:we,49:we,50:we,51:we,52:we,53:we,54:we,55:we,56:we,57:we,62:xa},Ah={91:Pd},Eh={[-2]:gn,[-1]:gn,32:gn},Lh={35:zd,42:qt,45:[ps,qt],60:Kd,61:ps,95:qt,96:hs,126:hs},Nh={38:Sa,92:ba},Ph={[-5]:mn,[-4]:mn,[-3]:mn,33:oh,38:Sa,42:Gn,60:[ud,Xd],91:uh,92:[Od,ba],93:Tr,95:Gn,96:wd},jh={null:[Gn,Ch]},Dh={null:[42,95]},_h={null:[]},Oh=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Dh,contentInitial:Ah,disable:_h,document:Rh,flow:Lh,flowInitial:Eh,insideSpan:jh,string:Nh,text:Ph},Symbol.toStringTag,{value:"Module"}));function Fh(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 l={attempt:N(R),check:N(v),consume:x,enter:w,exit:I,interrupt:N(v,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:m,parser:e,previous:null,sliceSerialize:p,sliceStream:f,write:d};let c=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function d(L){return a=Le(a,L),S(),a[a.length-1]!==null?[]:(P(t,0),u.events=sn(i,u.events,u),u.events)}function p(L,D){return Bh(f(L),D)}function f(L){return zh(a,L)}function m(){const{_bufferIndex:L,_index:D,line:$,column:z,offset:_}=r;return{_bufferIndex:L,_index:D,line:$,column:z,offset:_}}function y(L){s[L.line]=L.column,T()}function S(){let L;for(;r._index<a.length;){const D=a[r._index];if(typeof D=="string")for(L=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===L&&r._bufferIndex<D.length;)g(D.charCodeAt(r._bufferIndex));else g(D)}}function g(L){c=c(L)}function x(L){B(L)?(r.line++,r.column=1,r.offset+=L===-3?2:1,T()):L!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===a[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=L}function w(L,D){const $=D||{};return $.type=L,$.start=m(),u.events.push(["enter",$,u]),o.push($),$}function I(L){const D=o.pop();return D.end=m(),u.events.push(["exit",D,u]),D}function R(L,D){P(L,D.from)}function v(L,D){D.restore()}function N(L,D){return $;function $(z,_,W){let ee,de,re,k;return Array.isArray(z)?Se(z):"tokenize"in z?Se([z]):pe(z);function pe(te){return Ne;function Ne(ke){const Re=ke!==null&&te[ke],he=ke!==null&&te.null,_e=[...Array.isArray(Re)?Re:Re?[Re]:[],...Array.isArray(he)?he:he?[he]:[]];return Se(_e)(ke)}}function Se(te){return ee=te,de=0,te.length===0?W:b(te[de])}function b(te){return Ne;function Ne(ke){return k=F(),re=te,te.partial||(u.currentConstruct=te),te.name&&u.parser.constructs.disable.null.includes(te.name)?ie():te.tokenize.call(D?Object.assign(Object.create(u),D):u,l,ae,ie)(ke)}}function ae(te){return L(re,k),_}function ie(te){return k.restore(),++de<ee.length?b(ee[de]):W}}}function P(L,D){L.resolveAll&&!i.includes(L)&&i.push(L),L.resolve&&Me(u.events,D,u.events.length-D,L.resolve(u.events.slice(D),u)),L.resolveTo&&(u.events=L.resolveTo(u.events,u))}function F(){const L=m(),D=u.previous,$=u.currentConstruct,z=u.events.length,_=Array.from(o);return{from:z,restore:W};function W(){r=L,u.previous=D,u.currentConstruct=$,u.events.length=z,o=_,T()}}function T(){r.line in s&&r.column<2&&(r.column=s[r.line],r.offset+=s[r.line]-1)}}function zh(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 Bh(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=`
4
+ `;break}case-3:{a=`\r
5
+ `;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 $h(e){const r={constructs:ma([Oh,...(e||{}).extensions||[]]),content:s(nd),defined:[],document:s(sd),flow:s(wh),lazy:{},string:s(Ih),text:s(Th)};return r;function s(i){return a;function a(o){return Fh(r,i,o)}}}function Uh(e){for(;!ka(e););return e}const gs=/[\0\t\n\r]/g;function Kh(){let e=1,t="",n=!0,r;return s;function s(i,a,o){const l=[];let u,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(gs.lastIndex=d,u=gs.exec(i),p=u&&u.index!==void 0?u.index:i.length,f=i.charCodeAt(p),!u){t=i.slice(d);break}if(f===10&&d===p&&r)l.push(-3),r=void 0;else switch(r&&(l.push(-5),r=void 0),d<p&&(l.push(i.slice(d,p)),e+=p-d),f){case 0:{l.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,l.push(-2);e++<c;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:r=!0,e=1}d=p+1}return o&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Hh=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Vh(e){return e.replace(Hh,qh)}function qh(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const s=n.charCodeAt(1),i=s===120||s===88;return ya(n.slice(i?2:1),i?16:10)}return Ir(n)||e}const Ma={}.hasOwnProperty;function Wh(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),Gh(n)(Uh($h(n).document().write(Kh()(e,t,!0))))}function Gh(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Ae),autolinkProtocol:F,autolinkEmail:F,atxHeading:i(Ge),blockQuote:i(he),characterEscape:F,characterReference:F,codeFenced:i(_e),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(_e,a),codeText:i(Ye,a),codeTextData:F,data:F,codeFlowValue:F,definition:i(Je),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(Ze),hardBreakEscape:i(ce),hardBreakTrailing:i(ce),htmlFlow:i(V,a),htmlFlowData:F,htmlText:i(V,a),htmlTextData:F,image:i(ye),label:a,link:i(Ae),listItem:i(Be),listItemValue:p,listOrdered:i(xe,d),listUnordered:i(xe),paragraph:i(Eo),reference:b,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(Ge),strong:i(Lo),thematicBreak:i(Po)},exit:{atxHeading:l(),atxHeadingSequence:R,autolink:l(),autolinkEmail:Re,autolinkProtocol:ke,blockQuote:l(),characterEscapeValue:T,characterReferenceMarkerHexadecimal:ie,characterReferenceMarkerNumeric:ie,characterReferenceValue:te,characterReference:Ne,codeFenced:l(S),codeFencedFence:y,codeFencedFenceInfo:f,codeFencedFenceMeta:m,codeFlowValue:T,codeIndented:l(g),codeText:l(_),codeTextData:T,data:T,definition:l(),definitionDestinationString:I,definitionLabelString:x,definitionTitleString:w,emphasis:l(),hardBreakEscape:l(D),hardBreakTrailing:l(D),htmlFlow:l($),htmlFlowData:T,htmlText:l(z),htmlTextData:T,image:l(ee),label:re,labelText:de,lineEnding:L,link:l(W),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:ae,resourceDestinationString:k,resourceTitleString:pe,resource:Se,setextHeading:l(P),setextHeadingLineSequence:N,setextHeadingText:v,strong:l(),thematicBreak:l()}};Ra(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(M){let j={type:"root",children:[]};const U={stack:[j],tokenStack:[],config:t,enter:o,exit:u,buffer:a,resume:c,data:n},Q=[];let Y=-1;for(;++Y<M.length;)if(M[Y][1].type==="listOrdered"||M[Y][1].type==="listUnordered")if(M[Y][0]==="enter")Q.push(Y);else{const Pe=Q.pop();Y=s(M,Pe,Y)}for(Y=-1;++Y<M.length;){const Pe=t[M[Y][0]];Ma.call(Pe,M[Y][1].type)&&Pe[M[Y][1].type].call(Object.assign({sliceSerialize:M[Y][2].sliceSerialize},U),M[Y][1])}if(U.tokenStack.length>0){const Pe=U.tokenStack[U.tokenStack.length-1];(Pe[1]||ms).call(U,void 0,Pe[0])}for(j.position={start:Qe(M.length>0?M[0][1].start:{line:1,column:1,offset:0}),end:Qe(M.length>0?M[M.length-2][1].end:{line:1,column:1,offset:0})},Y=-1;++Y<t.transforms.length;)j=t.transforms[Y](j)||j;return j}function s(M,j,U){let Q=j-1,Y=-1,Pe=!1,et,$e,yt,xt;for(;++Q<=U;){const Ce=M[Q];switch(Ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ce[0]==="enter"?Y++:Y--,xt=void 0;break}case"lineEndingBlank":{Ce[0]==="enter"&&(et&&!xt&&!Y&&!yt&&(yt=Q),xt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:xt=void 0}if(!Y&&Ce[0]==="enter"&&Ce[1].type==="listItemPrefix"||Y===-1&&Ce[0]==="exit"&&(Ce[1].type==="listUnordered"||Ce[1].type==="listOrdered")){if(et){let it=Q;for($e=void 0;it--;){const Ue=M[it];if(Ue[1].type==="lineEnding"||Ue[1].type==="lineEndingBlank"){if(Ue[0]==="exit")continue;$e&&(M[$e][1].type="lineEndingBlank",Pe=!0),Ue[1].type="lineEnding",$e=it}else if(!(Ue[1].type==="linePrefix"||Ue[1].type==="blockQuotePrefix"||Ue[1].type==="blockQuotePrefixWhitespace"||Ue[1].type==="blockQuoteMarker"||Ue[1].type==="listItemIndent"))break}yt&&(!$e||yt<$e)&&(et._spread=!0),et.end=Object.assign({},$e?M[$e][1].start:Ce[1].end),M.splice($e||Q,0,["exit",et,Ce[2]]),Q++,U++}if(Ce[1].type==="listItemPrefix"){const it={type:"listItem",_spread:!1,start:Object.assign({},Ce[1].start),end:void 0};et=it,M.splice(Q,0,["enter",it,Ce[2]]),Q++,U++,yt=void 0,xt=!0}}}return M[j][1]._spread=Pe,U}function i(M,j){return U;function U(Q){o.call(this,M(Q),Q),j&&j.call(this,Q)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(M,j,U){this.stack[this.stack.length-1].children.push(M),this.stack.push(M),this.tokenStack.push([j,U||void 0]),M.position={start:Qe(j.start),end:void 0}}function l(M){return j;function j(U){M&&M.call(this,U),u.call(this,U)}}function u(M,j){const U=this.stack.pop(),Q=this.tokenStack.pop();if(Q)Q[0].type!==M.type&&(j?j.call(this,M,Q[0]):(Q[1]||ms).call(this,M,Q[0]));else throw new Error("Cannot close `"+M.type+"` ("+It({start:M.start,end:M.end})+"): it’s not open");U.position.end=Qe(M.end)}function c(){return Cr(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function p(M){if(this.data.expectingFirstListItemValue){const j=this.stack[this.stack.length-2];j.start=Number.parseInt(this.sliceSerialize(M),10),this.data.expectingFirstListItemValue=void 0}}function f(){const M=this.resume(),j=this.stack[this.stack.length-1];j.lang=M}function m(){const M=this.resume(),j=this.stack[this.stack.length-1];j.meta=M}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function S(){const M=this.resume(),j=this.stack[this.stack.length-1];j.value=M.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){const M=this.resume(),j=this.stack[this.stack.length-1];j.value=M.replace(/(\r?\n|\r)$/g,"")}function x(M){const j=this.resume(),U=this.stack[this.stack.length-1];U.label=j,U.identifier=De(this.sliceSerialize(M)).toLowerCase()}function w(){const M=this.resume(),j=this.stack[this.stack.length-1];j.title=M}function I(){const M=this.resume(),j=this.stack[this.stack.length-1];j.url=M}function R(M){const j=this.stack[this.stack.length-1];if(!j.depth){const U=this.sliceSerialize(M).length;j.depth=U}}function v(){this.data.setextHeadingSlurpLineEnding=!0}function N(M){const j=this.stack[this.stack.length-1];j.depth=this.sliceSerialize(M).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function F(M){const U=this.stack[this.stack.length-1].children;let Q=U[U.length-1];(!Q||Q.type!=="text")&&(Q=No(),Q.position={start:Qe(M.start),end:void 0},U.push(Q)),this.stack.push(Q)}function T(M){const j=this.stack.pop();j.value+=this.sliceSerialize(M),j.position.end=Qe(M.end)}function L(M){const j=this.stack[this.stack.length-1];if(this.data.atHardBreak){const U=j.children[j.children.length-1];U.position.end=Qe(M.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(j.type)&&(F.call(this,M),T.call(this,M))}function D(){this.data.atHardBreak=!0}function $(){const M=this.resume(),j=this.stack[this.stack.length-1];j.value=M}function z(){const M=this.resume(),j=this.stack[this.stack.length-1];j.value=M}function _(){const M=this.resume(),j=this.stack[this.stack.length-1];j.value=M}function W(){const M=this.stack[this.stack.length-1];if(this.data.inReference){const j=this.data.referenceType||"shortcut";M.type+="Reference",M.referenceType=j,delete M.url,delete M.title}else delete M.identifier,delete M.label;this.data.referenceType=void 0}function ee(){const M=this.stack[this.stack.length-1];if(this.data.inReference){const j=this.data.referenceType||"shortcut";M.type+="Reference",M.referenceType=j,delete M.url,delete M.title}else delete M.identifier,delete M.label;this.data.referenceType=void 0}function de(M){const j=this.sliceSerialize(M),U=this.stack[this.stack.length-2];U.label=Vh(j),U.identifier=De(j).toLowerCase()}function re(){const M=this.stack[this.stack.length-1],j=this.resume(),U=this.stack[this.stack.length-1];if(this.data.inReference=!0,U.type==="link"){const Q=M.children;U.children=Q}else U.alt=j}function k(){const M=this.resume(),j=this.stack[this.stack.length-1];j.url=M}function pe(){const M=this.resume(),j=this.stack[this.stack.length-1];j.title=M}function Se(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function ae(M){const j=this.resume(),U=this.stack[this.stack.length-1];U.label=j,U.identifier=De(this.sliceSerialize(M)).toLowerCase(),this.data.referenceType="full"}function ie(M){this.data.characterReferenceType=M.type}function te(M){const j=this.sliceSerialize(M),U=this.data.characterReferenceType;let Q;U?(Q=ya(j,U==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Q=Ir(j);const Y=this.stack[this.stack.length-1];Y.value+=Q}function Ne(M){const j=this.stack.pop();j.position.end=Qe(M.end)}function ke(M){T.call(this,M);const j=this.stack[this.stack.length-1];j.url=this.sliceSerialize(M)}function Re(M){T.call(this,M);const j=this.stack[this.stack.length-1];j.url="mailto:"+this.sliceSerialize(M)}function he(){return{type:"blockquote",children:[]}}function _e(){return{type:"code",lang:null,meta:null,value:""}}function Ye(){return{type:"inlineCode",value:""}}function Je(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Ze(){return{type:"emphasis",children:[]}}function Ge(){return{type:"heading",depth:0,children:[]}}function ce(){return{type:"break"}}function V(){return{type:"html",value:""}}function ye(){return{type:"image",title:null,url:"",alt:null}}function Ae(){return{type:"link",title:null,url:"",children:[]}}function xe(M){return{type:"list",ordered:M.type==="listOrdered",start:null,spread:M._spread,children:[]}}function Be(M){return{type:"listItem",spread:M._spread,checked:null,children:[]}}function Eo(){return{type:"paragraph",children:[]}}function Lo(){return{type:"strong",children:[]}}function No(){return{type:"text",value:""}}function Po(){return{type:"thematicBreak"}}}function Qe(e){return{line:e.line,column:e.column,offset:e.offset}}function Ra(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?Ra(e,r):Qh(e,r)}}function Qh(e,t){let n;for(n in t)if(Ma.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 ms(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+It({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+It({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+It({start:t.start,end:t.end})+") is still open")}function Xh(e){const t=this;t.parser=n;function n(r){return Wh(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function Yh(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 Jh(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
6
+ `}]}function Zh(e,t){const n=t.value?t.value+`
7
+ `:"",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 ef(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function tf(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function nf(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),s=mt(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 l={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,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function rf(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 sf(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function Aa(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 af(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return Aa(e,t);const s={src:mt(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 of(e,t){const n={src:mt(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 lf(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 uf(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return Aa(e,t);const s={href:mt(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 cf(e,t){const n={href:mt(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 df(e,t,n){const r=e.all(t),s=n?hf(n):Ea(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:`
8
+ `}),c.type==="element"&&c.tagName==="p"&&!s?a.push(...c.children):a.push(c)}const l=r[r.length-1];l&&(s||l.type!=="element"||l.tagName!=="p")&&a.push({type:"text",value:`
9
+ `});const u={type:"element",tagName:"li",properties:i,children:a};return e.patch(t,u),e.applyData(t,u)}function hf(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=Ea(n[r])}return t}function Ea(e){const t=e.spread;return t??e.children.length>1}function ff(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 pf(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function gf(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function mf(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yf(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=Sr(t.children[1]),l=ua(t.children[t.children.length-1]);o&&l&&(a.position={start:o,end:l}),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 xf(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 l=-1;const u=[];for(;++l<o;){const d=t.children[l],p={},f=a?a[l]:void 0;f&&(p.align=f);let m={type:"element",tagName:i,properties:p,children:[]};d&&(m.children=e.all(d),e.patch(d,m),m=e.applyData(d,m)),u.push(m)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,c),e.applyData(t,c)}function bf(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const ys=9,xs=32;function Sf(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),s=0;const i=[];for(;r;)i.push(bs(t.slice(s,r.index),s>0,!0),r[0]),s=r.index+r[0].length,r=n.exec(t);return i.push(bs(t.slice(s),s>0,!1)),i.join("")}function bs(e,t,n){let r=0,s=e.length;if(t){let i=e.codePointAt(r);for(;i===ys||i===xs;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(s-1);for(;i===ys||i===xs;)s--,i=e.codePointAt(s-1)}return s>r?e.slice(r,s):""}function kf(e,t){const n={type:"text",value:Sf(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function wf(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const vf={blockquote:Yh,break:Jh,code:Zh,delete:ef,emphasis:tf,footnoteReference:nf,heading:rf,html:sf,imageReference:af,image:of,inlineCode:lf,linkReference:uf,link:cf,listItem:df,list:ff,paragraph:pf,root:gf,strong:mf,table:yf,tableCell:bf,tableRow:xf,text:kf,thematicBreak:wf,toml:Ot,yaml:Ot,definition:Ot,footnoteDefinition:Ot};function Ot(){}const La=-1,an=0,Mt=1,Xt=2,Mr=3,Rr=4,Ar=5,Er=6,Na=7,Pa=8,Ss=typeof self=="object"?self:globalThis,Cf=(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 an:case La:return n(a,s);case Mt:{const o=n([],s);for(const l of a)o.push(r(l));return o}case Xt:{const o=n({},s);for(const[l,u]of a)o[r(l)]=r(u);return o}case Mr:return n(new Date(a),s);case Rr:{const{source:o,flags:l}=a;return n(new RegExp(o,l),s)}case Ar:{const o=n(new Map,s);for(const[l,u]of a)o.set(r(l),r(u));return o}case Er:{const o=n(new Set,s);for(const l of a)o.add(r(l));return o}case Na:{const{name:o,message:l}=a;return n(new Ss[o](l),s)}case Pa: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 Ss[i](a),s)};return r},ks=e=>Cf(new Map,e)(0),lt="",{toString:If}={},{keys:Tf}=Object,wt=e=>{const t=typeof e;if(t!=="object"||!e)return[an,t];const n=If.call(e).slice(8,-1);switch(n){case"Array":return[Mt,lt];case"Object":return[Xt,lt];case"Date":return[Mr,lt];case"RegExp":return[Rr,lt];case"Map":return[Ar,lt];case"Set":return[Er,lt];case"DataView":return[Mt,n]}return n.includes("Array")?[Mt,n]:n.includes("Error")?[Na,n]:[Xt,n]},Ft=([e,t])=>e===an&&(t==="function"||t==="symbol"),Mf=(e,t,n,r)=>{const s=(a,o)=>{const l=r.push(a)-1;return n.set(o,l),l},i=a=>{if(n.has(a))return n.get(a);let[o,l]=wt(a);switch(o){case an:{let c=a;switch(l){case"bigint":o=Pa,c=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return s([La],a)}return s([o,c],a)}case Mt:{if(l){let p=a;return l==="DataView"?p=new Uint8Array(a.buffer):l==="ArrayBuffer"&&(p=new Uint8Array(a)),s([l,[...p]],a)}const c=[],d=s([o,c],a);for(const p of a)c.push(i(p));return d}case Xt:{if(l)switch(l){case"BigInt":return s([l,a.toString()],a);case"Boolean":case"Number":case"String":return s([l,a.valueOf()],a)}if(t&&"toJSON"in a)return i(a.toJSON());const c=[],d=s([o,c],a);for(const p of Tf(a))(e||!Ft(wt(a[p])))&&c.push([i(p),i(a[p])]);return d}case Mr:return s([o,a.toISOString()],a);case Rr:{const{source:c,flags:d}=a;return s([o,{source:c,flags:d}],a)}case Ar:{const c=[],d=s([o,c],a);for(const[p,f]of a)(e||!(Ft(wt(p))||Ft(wt(f))))&&c.push([i(p),i(f)]);return d}case Er:{const c=[],d=s([o,c],a);for(const p of a)(e||!Ft(wt(p)))&&c.push(i(p));return d}}const{message:u}=a;return s([o,{name:l,message:u}],a)};return i},ws=(e,{json:t,lossy:n}={})=>{const r=[];return Mf(!(t||n),!!t,new Map,r)(e),r},Yt=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?ks(ws(e,t)):structuredClone(e):(e,t)=>ks(ws(e,t));function Rf(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 Af(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Ef(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Rf,r=e.options.footnoteBackLabel||Af,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const c=e.all(u),d=String(u.identifier).toUpperCase(),p=mt(d.toLowerCase());let f=0;const m=[],y=e.footnoteCounts.get(d);for(;y!==void 0&&++f<=y;){m.length>0&&m.push({type:"text",value:" "});let x=typeof n=="string"?n:n(l,f);typeof x=="string"&&(x={type:"text",value:x}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+p+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(l,f),className:["data-footnote-backref"]},children:Array.isArray(x)?x:[x]})}const S=c[c.length-1];if(S&&S.type==="element"&&S.tagName==="p"){const x=S.children[S.children.length-1];x&&x.type==="text"?x.value+=" ":S.children.push({type:"text",value:" "}),S.children.push(...m)}else c.push(...m);const g={type:"element",tagName:"li",properties:{id:t+"fn-"+p},children:e.wrap(c,!0)};e.patch(u,g),o.push(g)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Yt(a),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:`
10
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:`
11
+ `}]}}const on=(function(e){if(e==null)return jf;if(typeof e=="function")return ln(e);if(typeof e=="object")return Array.isArray(e)?Lf(e):Nf(e);if(typeof e=="string")return Pf(e);throw new Error("Expected function, string, or object as test")});function Lf(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=on(e[n]);return ln(r);function r(...s){let i=-1;for(;++i<t.length;)if(t[i].apply(this,s))return!0;return!1}}function Nf(e){const t=e;return ln(n);function n(r){const s=r;let i;for(i in e)if(s[i]!==t[i])return!1;return!0}}function Pf(e){return ln(t);function t(n){return n&&n.type===e}}function ln(e){return t;function t(n,r,s){return!!(Df(n)&&e.call(this,n,typeof r=="number"?r:void 0,s||void 0))}}function jf(){return!0}function Df(e){return e!==null&&typeof e=="object"&&"type"in e}const ja=[],_f=!0,Qn=!1,Of="skip";function Da(e,t,n,r){let s;typeof t=="function"&&typeof n!="function"?(r=n,n=t):s=t;const i=on(s),a=r?-1:1;o(e,void 0,[])();function o(l,u,c){const d=l&&typeof l=="object"?l:{};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 ("+(l.type+(f?"<"+f+">":""))+")"})}return p;function p(){let f=ja,m,y,S;if((!t||i(l,u,c[c.length-1]||void 0))&&(f=Ff(n(l,c)),f[0]===Qn))return f;if("children"in l&&l.children){const g=l;if(g.children&&f[0]!==Of)for(y=(r?g.children.length:-1)+a,S=c.concat(g);y>-1&&y<g.children.length;){const x=g.children[y];if(m=o(x,y,S)(),m[0]===Qn)return m;y=typeof m[1]=="number"?m[1]:y+a}}return f}}}function Ff(e){return Array.isArray(e)?e:typeof e=="number"?[_f,e]:e==null?ja:[e]}function Lr(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),Da(e,i,o,s);function o(l,u){const c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return a(l,d,c)}}const Xn={}.hasOwnProperty,zf={};function Bf(e,t){const n=t||zf,r=new Map,s=new Map,i=new Map,a={...vf,...n.handlers},o={all:u,applyData:Uf,definitionById:r,footnoteById:s,footnoteCounts:i,footnoteOrder:[],handlers:a,one:l,options:n,patch:$f,wrap:Hf};return Lr(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 l(c,d){const p=c.type,f=o.handlers[p];if(Xn.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:y,...S}=c,g=Yt(S);return g.children=o.all(c),g}return Yt(c)}return(o.options.unknownHandler||Kf)(o,c,d)}function u(c){const d=[];if("children"in c){const p=c.children;let f=-1;for(;++f<p.length;){const m=o.one(p[f],c);if(m){if(f&&p[f-1].type==="break"&&(!Array.isArray(m)&&m.type==="text"&&(m.value=vs(m.value)),!Array.isArray(m)&&m.type==="element")){const y=m.children[0];y&&y.type==="text"&&(y.value=vs(y.value))}Array.isArray(m)?d.push(...m):d.push(m)}}}return d}}function $f(e,t){e.position&&(t.position=Rc(e))}function Uf(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,Yt(i)),"children"in n&&n.children&&s!==null&&s!==void 0&&(n.children=s)}return n}function Kf(e,t){const n=t.data||{},r="value"in t&&!(Xn.call(n,"hProperties")||Xn.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 Hf(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:`
12
+ `});++r<e.length;)r&&n.push({type:"text",value:`
13
+ `}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
14
+ `}),n}function vs(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Cs(e,t){const n=Bf(e,t),r=n.one(e,void 0),s=Ef(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return s&&i.children.push({type:"text",value:`
15
+ `},s),i}function Vf(e,t){return e&&"run"in e?async function(n,r){const s=Cs(n,{file:r,...t});await e.run(s,r)}:function(n,r){return Cs(n,{file:r,...e||t})}}function Is(e){if(e)throw e}var yn,Ts;function qf(){if(Ts)return yn;Ts=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var c=e.call(u,"constructor"),d=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!c&&!d)return!1;var p;for(p in u);return typeof p>"u"||e.call(u,p)},a=function(u,c){n&&c.name==="__proto__"?n(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},o=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return yn=function l(){var u,c,d,p,f,m,y=arguments[0],S=1,g=arguments.length,x=!1;for(typeof y=="boolean"&&(x=y,y=arguments[1]||{},S=2),(y==null||typeof y!="object"&&typeof y!="function")&&(y={});S<g;++S)if(u=arguments[S],u!=null)for(c in u)d=o(y,c),p=o(u,c),y!==p&&(x&&p&&(i(p)||(f=s(p)))?(f?(f=!1,m=d&&s(d)?d:[]):m=d&&i(d)?d:{},a(y,{name:c,newValue:l(x,m,p)})):typeof p<"u"&&a(y,{name:c,newValue:p}));return y},yn}var Wf=qf();const xn=wi(Wf);function Yn(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 Gf(){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(l,...u){const c=e[++i];let d=-1;if(l){a(l);return}for(;++d<s.length;)(u[d]===null||u[d]===void 0)&&(u[d]=s[d]);s=u,c?Qf(c,o)(...u):a(null,...u)}}function r(s){if(typeof s!="function")throw new TypeError("Expected `middelware` to be a function, not "+s);return e.push(s),t}}function Qf(e,t){let n;return r;function r(...a){const o=e.length>a.length;let l;o&&a.push(s);try{l=e.apply(this,a)}catch(u){const c=u;if(o&&n)throw c;return s(c)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,s):l instanceof Error?s(l):i(l))}function s(a,...o){n||(n=!0,t(a,...o))}function i(a){s(null,a)}}const Fe={basename:Xf,dirname:Yf,extname:Jf,join:Zf,sep:"/"};function Xf(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Dt(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 Yf(e){if(Dt(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 Jf(e){Dt(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 Zf(...e){let t=-1,n;for(;++t<e.length;)Dt(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":ep(n)}function ep(e){Dt(e);const t=e.codePointAt(0)===47;let n=tp(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function tp(e,t){let n="",r=0,s=-1,i=0,a=-1,o,l;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(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),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 Dt(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const np={cwd:rp};function rp(){return"/"}function Jn(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function sp(e){if(typeof e=="string")e=new URL(e);else if(!Jn(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 ip(e)}function ip(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 bn=["history","path","basename","stem","extname","dirname"];class _a{constructor(t){let n;t?Jn(t)?n={path:t}:typeof t=="string"||ap(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":np.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<bn.length;){const i=bn[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)bn.includes(s)||(this[s]=n[s])}get basename(){return typeof this.path=="string"?Fe.basename(this.path):void 0}set basename(t){kn(t,"basename"),Sn(t,"basename"),this.path=Fe.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Fe.dirname(this.path):void 0}set dirname(t){Ms(this.basename,"dirname"),this.path=Fe.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Fe.extname(this.path):void 0}set extname(t){if(Sn(t,"extname"),Ms(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=Fe.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Jn(t)&&(t=sp(t)),kn(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Fe.basename(this.path,this.extname):void 0}set stem(t){kn(t,"stem"),Sn(t,"stem"),this.path=Fe.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 me(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 Sn(e,t){if(e&&e.includes(Fe.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Fe.sep+"`")}function kn(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Ms(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function ap(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const op=(function(e){const r=this.constructor.prototype,s=r[e],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,r),i}),lp={}.hasOwnProperty;class Nr extends op{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=Gf()}copy(){const t=new Nr;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(xn(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Cn("data",this.frozen),this.namespace[t]=n,this):lp.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Cn("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=zt(t),r=this.parser||this.Parser;return wn("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),wn("process",this.parser||this.Parser),vn("process",this.compiler||this.Compiler),n?s(void 0,n):new Promise(s);function s(i,a){const o=zt(t),l=r.parse(o);r.run(l,o,function(c,d,p){if(c||!d||!p)return u(c);const f=d,m=r.stringify(f,p);dp(m)?p.value=m:p.result=m,u(c,p)});function u(c,d){c||!d?a(c):i?i(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),wn("processSync",this.parser||this.Parser),vn("processSync",this.compiler||this.Compiler),this.process(t,s),As("processSync","process",n),r;function s(i,a){n=!0,Is(i),r=a}}run(t,n,r){Rs(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 l=zt(n);s.run(t,l,u);function u(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),As("runSync","run",r),s;function i(a,o){Is(a),s=o,r=!0}}stringify(t,n){this.freeze();const r=zt(n),s=this.compiler||this.Compiler;return vn("stringify",s),Rs(t),s(t,r)}use(t,...n){const r=this.attachers,s=this.namespace;if(Cn("use",this.frozen),t!=null)if(typeof t=="function")l(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(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[c,...d]=u;l(c,d)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(u){if(!("plugins"in u)&&!("settings"in u))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(u.plugins),u.settings&&(s.settings=xn(!0,s.settings,u.settings))}function o(u){let c=-1;if(u!=null)if(Array.isArray(u))for(;++c<u.length;){const d=u[c];i(d)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,c){let d=-1,p=-1;for(;++d<r.length;)if(r[d][0]===u){p=d;break}if(p===-1)r.push([u,...c]);else if(c.length>0){let[f,...m]=c;const y=r[p][1];Yn(y)&&Yn(f)&&(f=xn(!0,y,f)),r[p]=[u,f,...m]}}}}const up=new Nr().freeze();function wn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function vn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Cn(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 Rs(e){if(!Yn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function As(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function zt(e){return cp(e)?e:new _a(e)}function cp(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function dp(e){return typeof e=="string"||hp(e)}function hp(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const fp="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Es=[],Ls={allowDangerousHtml:!0},pp=/^(https?|ircs?|mailto|xmpp)$/i,gp=[{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 mp(e){const t=yp(e),n=xp(e);return bp(t.runSync(t.parse(n),n),e)}function yp(e){const t=e.rehypePlugins||Es,n=e.remarkPlugins||Es,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Ls}:Ls;return up().use(Xh).use(n).use(Vf,r).use(t)}function xp(e){const t=e.children||"",n=new _a;return typeof t=="string"&&(n.value=t),n}function bp(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,a=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||Sp;for(const c of gp)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+fp+c.id,void 0);return Lr(e,u),Pc(e,{Fragment:h.Fragment,components:s,ignoreInvalidStyle:!0,jsx:h.jsx,jsxs:h.jsxs,passKeys:!0,passNode:!0});function u(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 pn)if(Object.hasOwn(pn,f)&&Object.hasOwn(c.properties,f)){const m=c.properties[f],y=pn[f];(y===null||y.includes(c.tagName))&&(c.properties[f]=l(String(m||""),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 Sp(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||pp.test(e.slice(0,t))?e:""}function Ns(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 kp(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function wp(e,t,n){const s=on((n||{}).ignore||[]),i=vp(t);let a=-1;for(;++a<i.length;)Da(e,"text",o);function o(u,c){let d=-1,p;for(;++d<c.length;){const f=c[d],m=p?p.children:void 0;if(s(f,m?m.indexOf(f):void 0,p))return;p=f}if(p)return l(u,c)}function l(u,c){const d=c[c.length-1],p=i[a][0],f=i[a][1];let m=0;const S=d.children.indexOf(u);let g=!1,x=[];p.lastIndex=0;let w=p.exec(u.value);for(;w;){const I=w.index,R={index:w.index,input:w.input,stack:[...c,u]};let v=f(...w,R);if(typeof v=="string"&&(v=v.length>0?{type:"text",value:v}:void 0),v===!1?p.lastIndex=I+1:(m!==I&&x.push({type:"text",value:u.value.slice(m,I)}),Array.isArray(v)?x.push(...v):v&&x.push(v),m=I+w[0].length,g=!0),!p.global)break;w=p.exec(u.value)}return g?(m<u.value.length&&x.push({type:"text",value:u.value.slice(m)}),d.children.splice(S,1,...x)):x=[u],S+x.length}}function vp(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([Cp(s[0]),Ip(s[1])])}return t}function Cp(e){return typeof e=="string"?new RegExp(kp(e),"g"):e}function Ip(e){return typeof e=="function"?e:function(){return e}}const In="phrasing",Tn=["autolink","link","image","label"];function Tp(){return{transforms:[Pp],enter:{literalAutolink:Rp,literalAutolinkEmail:Mn,literalAutolinkHttp:Mn,literalAutolinkWww:Mn},exit:{literalAutolink:Np,literalAutolinkEmail:Lp,literalAutolinkHttp:Ap,literalAutolinkWww:Ep}}}function Mp(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:In,notInConstruct:Tn},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:In,notInConstruct:Tn},{character:":",before:"[ps]",after:"\\/",inConstruct:In,notInConstruct:Tn}]}}function Rp(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Mn(e){this.config.enter.autolinkProtocol.call(this,e)}function Ap(e){this.config.exit.autolinkProtocol.call(this,e)}function Ep(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 Lp(e){this.config.exit.autolinkEmail.call(this,e)}function Np(e){this.exit(e)}function Pp(e){wp(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,jp],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),Dp]],{ignore:["link","linkReference"]})}function jp(e,t,n,r,s){let i="";if(!Oa(s)||(/^w/i.test(t)&&(n=t+n,t="",i="http://"),!_p(n)))return!1;const a=Op(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 Dp(e,t,n,r){return!Oa(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function _p(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 Op(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=Ns(e,"(");let i=Ns(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 Oa(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||rt(n)||rn(n))&&(!t||n!==47)}Fa.peek=qp;function Fp(){this.buffer()}function zp(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Bp(){this.buffer()}function $p(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Up(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=De(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Kp(e){this.exit(e)}function Hp(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=De(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Vp(e){this.exit(e)}function qp(){return"["}function Fa(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 Wp(){return{enter:{gfmFootnoteCallString:Fp,gfmFootnoteCall:zp,gfmFootnoteDefinitionLabelString:Bp,gfmFootnoteDefinition:$p},exit:{gfmFootnoteCallString:Up,gfmFootnoteCall:Kp,gfmFootnoteDefinitionLabelString:Hp,gfmFootnoteDefinition:Vp}}}function Gp(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Fa},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,a){const o=i.createTracker(a);let l=o.move("[^");const u=i.enter("footnoteDefinition"),c=i.enter("label");return l+=o.move(i.safe(i.associationId(r),{before:l,after:"]"})),c(),l+=o.move("]:"),r.children&&r.children.length>0&&(o.shift(4),l+=o.move((t?`
16
+ `:" ")+i.indentLines(i.containerFlow(r,o.current()),t?za:Qp))),u(),l}}function Qp(e,t,n){return t===0?e:za(e,t,n)}function za(e,t,n){return(n?"":" ")+e}const Xp=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ba.peek=tg;function Yp(){return{canContainEols:["delete"],enter:{strikethrough:Zp},exit:{strikethrough:eg}}}function Jp(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Xp}],handlers:{delete:Ba}}}function Zp(e){this.enter({type:"delete",children:[]},e)}function eg(e){this.exit(e)}function Ba(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 tg(){return"~"}function ng(e){return e.length}function rg(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||ng,i=[],a=[],o=[],l=[];let u=0,c=-1;for(;++c<e.length;){const y=[],S=[];let g=-1;for(e[c].length>u&&(u=e[c].length);++g<e[c].length;){const x=sg(e[c][g]);if(n.alignDelimiters!==!1){const w=s(x);S[g]=w,(l[g]===void 0||w>l[g])&&(l[g]=w)}y.push(x)}a[c]=y,o[c]=S}let d=-1;if(typeof r=="object"&&"length"in r)for(;++d<u;)i[d]=Ps(r[d]);else{const y=Ps(r);for(;++d<u;)i[d]=y}d=-1;const p=[],f=[];for(;++d<u;){const y=i[d];let S="",g="";y===99?(S=":",g=":"):y===108?S=":":y===114&&(g=":");let x=n.alignDelimiters===!1?1:Math.max(1,l[d]-S.length-g.length);const w=S+"-".repeat(x)+g;n.alignDelimiters!==!1&&(x=S.length+x+g.length,x>l[d]&&(l[d]=x),f[d]=x),p[d]=w}a.splice(1,0,p),o.splice(1,0,f),c=-1;const m=[];for(;++c<a.length;){const y=a[c],S=o[c];d=-1;const g=[];for(;++d<u;){const x=y[d]||"";let w="",I="";if(n.alignDelimiters!==!1){const R=l[d]-(S[d]||0),v=i[d];v===114?w=" ".repeat(R):v===99?R%2?(w=" ".repeat(R/2+.5),I=" ".repeat(R/2-.5)):(w=" ".repeat(R/2),I=w):I=" ".repeat(R)}n.delimiterStart!==!1&&!d&&g.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&x==="")&&(n.delimiterStart!==!1||d)&&g.push(" "),n.alignDelimiters!==!1&&g.push(w),g.push(x),n.alignDelimiters!==!1&&g.push(I),n.padding!==!1&&g.push(" "),(n.delimiterEnd!==!1||d!==u-1)&&g.push("|")}m.push(n.delimiterEnd===!1?g.join("").replace(/ +$/,""):g.join(""))}return m.join(`
17
+ `)}function sg(e){return e==null?"":String(e)}function Ps(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 ig(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()),ag);return s(),a}function ag(e,t,n){return">"+(n?"":" ")+e}function og(e,t){return js(e,t.inConstruct,!0)&&!js(e,t.notInConstruct,!1)}function js(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 Ds(e,t,n,r){let s=-1;for(;++s<n.unsafe.length;)if(n.unsafe[s].character===`
18
+ `&&og(n.stack,n.unsafe[s]))return/[ \t]/.test(r.before)?"":" ";return`\\
19
+ `}function lg(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 ug(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 cg(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 dg(e,t,n,r){const s=cg(n),i=e.value||"",a=s==="`"?"GraveAccent":"Tilde";if(ug(e,n)){const d=n.enter("codeIndented"),p=n.indentLines(i,hg);return d(),p}const o=n.createTracker(r),l=s.repeat(Math.max(lg(i,s)+1,3)),u=n.enter("codeFenced");let c=o.move(l);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:`
20
+ `,encode:["`"],...o.current()})),d()}return c+=o.move(`
21
+ `),i&&(c+=o.move(i+`
22
+ `)),c+=o.move(l),u(),c}function hg(e,t,n){return(n?"":" ")+e}function Pr(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 fg(e,t,n,r){const s=Pr(n),i=s==='"'?"Quote":"Apostrophe",a=n.enter("definition");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("[");return u+=l.move(n.safe(n.associationId(e),{before:u,after:"]",...l.current()})),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(o=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":`
23
+ `,...l.current()}))),o(),e.title&&(o=n.enter(`title${i}`),u+=l.move(" "+s),u+=l.move(n.safe(e.title,{before:u,after:s,...l.current()})),u+=l.move(s),o()),a(),u}function pg(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 Et(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Jt(e,t,n){const r=pt(e),s=pt(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}}$a.peek=gg;function $a(e,t,n,r){const s=pg(n),i=n.enter("emphasis"),a=n.createTracker(r),o=a.move(s);let l=a.move(n.containerPhrasing(e,{after:s,before:o,...a.current()}));const u=l.charCodeAt(0),c=Jt(r.before.charCodeAt(r.before.length-1),u,s);c.inside&&(l=Et(u)+l.slice(1));const d=l.charCodeAt(l.length-1),p=Jt(r.after.charCodeAt(0),d,s);p.inside&&(l=l.slice(0,-1)+Et(d));const f=a.move(s);return i(),n.attentionEncodeSurroundingInfo={after:p.outside,before:c.outside},o+l+f}function gg(e,t,n){return n.options.emphasis||"*"}function mg(e,t){let n=!1;return Lr(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Qn}),!!((!e.depth||e.depth<3)&&Cr(e)&&(t.options.setext||n))}function yg(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(mg(e,n)){const c=n.enter("headingSetext"),d=n.enter("phrasing"),p=n.containerPhrasing(e,{...i.current(),before:`
24
+ `,after:`
25
+ `});return d(),c(),p+`
26
+ `+(s===1?"=":"-").repeat(p.length-(Math.max(p.lastIndexOf("\r"),p.lastIndexOf(`
27
+ `))+1))}const a="#".repeat(s),o=n.enter("headingAtx"),l=n.enter("phrasing");i.move(a+" ");let u=n.containerPhrasing(e,{before:"# ",after:`
28
+ `,...i.current()});return/^[\t ]/.test(u)&&(u=Et(u.charCodeAt(0))+u.slice(1)),u=u?a+" "+u:a,n.options.closeAtx&&(u+=" "+a),l(),o(),u}Ua.peek=xg;function Ua(e){return e.value||""}function xg(){return"<"}Ka.peek=bg;function Ka(e,t,n,r){const s=Pr(n),i=s==='"'?"Quote":"Apostrophe",a=n.enter("image");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("![");return u+=l.move(n.safe(e.alt,{before:u,after:"]",...l.current()})),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(o=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),o(),e.title&&(o=n.enter(`title${i}`),u+=l.move(" "+s),u+=l.move(n.safe(e.title,{before:u,after:s,...l.current()})),u+=l.move(s),o()),u+=l.move(")"),a(),u}function bg(){return"!"}Ha.peek=Sg;function Ha(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let a=n.enter("label");const o=n.createTracker(r);let l=o.move("![");const u=n.safe(e.alt,{before:l,after:"]",...o.current()});l+=o.move(u+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),{before:l,after:"]",...o.current()});return a(),n.stack=c,i(),s==="full"||!u||u!==d?l+=o.move(d+"]"):s==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Sg(){return"!"}Va.peek=kg;function Va(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 l;if(a.atBreak)for(;l=o.exec(r);){let u=l.index;r.charCodeAt(u)===10&&r.charCodeAt(u-1)===13&&u--,r=r.slice(0,u)+" "+r.slice(l.index+1)}}return s+r+s}function kg(){return"`"}function qa(e,t){const n=Cr(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))}Wa.peek=wg;function Wa(e,t,n,r){const s=Pr(n),i=s==='"'?"Quote":"Apostrophe",a=n.createTracker(r);let o,l;if(qa(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"),l=n.enter("label");let u=a.move("[");return u+=a.move(n.containerPhrasing(e,{before:u,after:"](",...a.current()})),u+=a.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=a.move("<"),u+=a.move(n.safe(e.url,{before:u,after:">",...a.current()})),u+=a.move(">")):(l=n.enter("destinationRaw"),u+=a.move(n.safe(e.url,{before:u,after:e.title?" ":")",...a.current()}))),l(),e.title&&(l=n.enter(`title${i}`),u+=a.move(" "+s),u+=a.move(n.safe(e.title,{before:u,after:s,...a.current()})),u+=a.move(s),l()),u+=a.move(")"),o(),u}function wg(e,t,n){return qa(e,n)?"<":"["}Ga.peek=vg;function Ga(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let a=n.enter("label");const o=n.createTracker(r);let l=o.move("[");const u=n.containerPhrasing(e,{before:l,after:"]",...o.current()});l+=o.move(u+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),{before:l,after:"]",...o.current()});return a(),n.stack=c,i(),s==="full"||!u||u!==d?l+=o.move(d+"]"):s==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function vg(){return"["}function jr(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 Cg(e){const t=jr(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 Ig(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 Qa(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 Tg(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let a=e.ordered?Ig(n):jr(n);const o=e.ordered?a==="."?")":".":Cg(n);let l=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&&(l=!0),Qa(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"){l=!0;break}}}}l&&(a=o),n.bulletCurrent=a;const u=n.containerFlow(e,r);return n.bulletLastUsed=a,n.bulletCurrent=i,s(),u}function Mg(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 Rg(e,t,n,r){const s=Mg(n);let i=n.bulletCurrent||jr(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 l=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,o.current()),c);return l(),u;function c(d,p,f){return p?(f?"":" ".repeat(a))+d:(f?i:i+" ".repeat(a-i.length))+d}}function Ag(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),a=n.containerPhrasing(e,r);return i(),s(),a}const Eg=on(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Lg(e,t,n,r){return(e.children.some(function(a){return Eg(a)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function Ng(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}Xa.peek=Pg;function Xa(e,t,n,r){const s=Ng(n),i=n.enter("strong"),a=n.createTracker(r),o=a.move(s+s);let l=a.move(n.containerPhrasing(e,{after:s,before:o,...a.current()}));const u=l.charCodeAt(0),c=Jt(r.before.charCodeAt(r.before.length-1),u,s);c.inside&&(l=Et(u)+l.slice(1));const d=l.charCodeAt(l.length-1),p=Jt(r.after.charCodeAt(0),d,s);p.inside&&(l=l.slice(0,-1)+Et(d));const f=a.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:p.outside,before:c.outside},o+l+f}function Pg(e,t,n){return n.options.strong||"*"}function jg(e,t,n,r){return n.safe(e.value,r)}function Dg(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 _g(e,t,n){const r=(Qa(n)+(n.options.ruleSpaces?" ":"")).repeat(Dg(n));return n.options.ruleSpaces?r.slice(0,-1):r}const Ya={blockquote:ig,break:Ds,code:dg,definition:fg,emphasis:$a,hardBreak:Ds,heading:yg,html:Ua,image:Ka,imageReference:Ha,inlineCode:Va,link:Wa,linkReference:Ga,list:Tg,listItem:Rg,paragraph:Ag,root:Lg,strong:Xa,text:jg,thematicBreak:_g};function Og(){return{enter:{table:Fg,tableData:_s,tableHeader:_s,tableRow:Bg},exit:{codeText:$g,table:zg,tableData:Rn,tableHeader:Rn,tableRow:Rn}}}function Fg(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 zg(e){this.exit(e),this.data.inTable=void 0}function Bg(e){this.enter({type:"tableRow",children:[]},e)}function Rn(e){this.exit(e)}function _s(e){this.enter({type:"tableCell",children:[]},e)}function $g(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Ug));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function Ug(e,t){return t==="|"?t:e}function Kg(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
29
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:p,table:a,tableCell:l,tableRow:o}};function a(f,m,y,S){return u(c(f,y,S),f.align)}function o(f,m,y,S){const g=d(f,y,S),x=u([g]);return x.slice(0,x.indexOf(`
30
+ `))}function l(f,m,y,S){const g=y.enter("tableCell"),x=y.enter("phrasing"),w=y.containerPhrasing(f,{...S,before:i,after:i});return x(),g(),w}function u(f,m){return rg(f,{align:m,alignDelimiters:r,padding:n,stringLength:s})}function c(f,m,y){const S=f.children;let g=-1;const x=[],w=m.enter("table");for(;++g<S.length;)x[g]=d(S[g],m,y);return w(),x}function d(f,m,y){const S=f.children;let g=-1;const x=[],w=m.enter("tableRow");for(;++g<S.length;)x[g]=l(S[g],f,m,y);return w(),x}function p(f,m,y){let S=Ya.inlineCode(f,m,y);return y.stack.includes("tableCell")&&(S=S.replace(/\|/g,"\\$&")),S}}function Hg(){return{exit:{taskListCheckValueChecked:Os,taskListCheckValueUnchecked:Os,paragraph:qg}}}function Vg(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Wg}}}function Os(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function qg(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 Wg(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 l=Ya.listItem(e,t,n,{...r,...o.current()});return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+a}}function Gg(){return[Tp(),Wp(),Yp(),Og(),Hg()]}function Qg(e){return{extensions:[Mp(),Gp(e),Jp(),Kg(e),Vg()]}}const Xg={tokenize:nm,partial:!0},Ja={tokenize:rm,partial:!0},Za={tokenize:sm,partial:!0},eo={tokenize:im,partial:!0},Yg={tokenize:am,partial:!0},to={name:"wwwAutolink",tokenize:em,previous:ro},no={name:"protocolAutolink",tokenize:tm,previous:so},We={name:"emailAutolink",tokenize:Zg,previous:io},ze={};function Jg(){return{text:ze}}let tt=48;for(;tt<123;)ze[tt]=We,tt++,tt===58?tt=65:tt===91&&(tt=97);ze[43]=We;ze[45]=We;ze[46]=We;ze[95]=We;ze[72]=[We,no];ze[104]=[We,no];ze[87]=[We,to];ze[119]=[We,to];function Zg(e,t,n){const r=this;let s,i;return a;function a(d){return!Zn(d)||!io.call(r,r.previous)||Dr(r.events)?n(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(d))}function o(d){return Zn(d)?(e.consume(d),o):d===64?(e.consume(d),l):n(d)}function l(d){return d===46?e.check(Yg,c,u)(d):d===45||d===95||ge(d)?(i=!0,e.consume(d),l):c(d)}function u(d){return e.consume(d),s=!0,l}function c(d){return i&&s&&be(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):n(d)}}function em(e,t,n){const r=this;return s;function s(a){return a!==87&&a!==119||!ro.call(r,r.previous)||Dr(r.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Xg,e.attempt(Ja,e.attempt(Za,i),n),n)(a))}function i(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function tm(e,t,n){const r=this;let s="",i=!1;return a;function a(d){return(d===72||d===104)&&so.call(r,r.previous)&&!Dr(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(d),e.consume(d),o):n(d)}function o(d){if(be(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),l}return n(d)}function l(d){return d===47?(e.consume(d),i?u:(i=!0,l)):n(d)}function u(d){return d===null||Qt(d)||J(d)||rt(d)||rn(d)?n(d):e.attempt(Ja,e.attempt(Za,c),n)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function nm(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 rm(e,t,n){let r,s,i;return a;function a(u){return u===46||u===95?e.check(eo,l,o)(u):u===null||J(u)||rt(u)||u!==45&&rn(u)?l(u):(i=!0,e.consume(u),a)}function o(u){return u===95?r=!0:(s=r,r=void 0),e.consume(u),a}function l(u){return s||r||!i?n(u):t(u)}}function sm(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(eo,t,i)(a):a===null||J(a)||rt(a)?t(a):(e.consume(a),s)}function i(a){return a===41&&r++,e.consume(a),s}}function im(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||J(o)||rt(o)?t(o):n(o)}function s(o){return o===null||o===40||o===91||J(o)||rt(o)?t(o):r(o)}function i(o){return be(o)?a(o):n(o)}function a(o){return o===59?(e.consume(o),r):be(o)?(e.consume(o),a):n(o)}}function am(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return ge(i)?n(i):t(i)}}function ro(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||J(e)}function so(e){return!be(e)}function io(e){return!(e===47||Zn(e))}function Zn(e){return e===43||e===45||e===46||e===95||ge(e)}function Dr(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 om={tokenize:gm,partial:!0};function lm(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:hm,continuation:{tokenize:fm},exit:pm}},text:{91:{name:"gfmFootnoteCall",tokenize:dm},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:um,resolveTo:cm}}}}function um(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;s--;){const l=r.events[s][1];if(l.type==="labelImage"){a=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!a||!a._balanced)return n(l);const u=De(r.sliceSerialize({start:a.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function cm(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 dm(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"),l}function l(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(i>999||d===93&&!a||d===null||d===91||J(d))return n(d);if(d===93){e.exit("chunkString");const p=e.exit("gfmFootnoteCallString");return s.includes(De(r.sliceSerialize(p)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return J(d)||(a=!0),i++,e.consume(d),d===92?c:u}function c(d){return d===91||d===92||d===93?(e.consume(d),i++,u):u(d)}}function hm(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,a=0,o;return l;function l(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(m)}function c(m){if(a>999||m===93&&!o||m===null||m===91||J(m))return n(m);if(m===93){e.exit("chunkString");const y=e.exit("gfmFootnoteDefinitionLabelString");return i=De(r.sliceSerialize(y)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),p}return J(m)||(o=!0),a++,e.consume(m),m===92?d:c}function d(m){return m===91||m===92||m===93?(e.consume(m),a++,c):c(m)}function p(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),s.includes(i)||s.push(i),X(e,f,"gfmFootnoteDefinitionWhitespace")):n(m)}function f(m){return t(m)}}function fm(e,t,n){return e.check(jt,t,e.attempt(om,t,n))}function pm(e){e.exit("gfmFootnoteDefinition")}function gm(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 mm(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 l=-1;for(;++l<a.length;)if(a[l][0]==="enter"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._close){let u=l;for(;u--;)if(a[u][0]==="exit"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._open&&a[l][1].end.offset-a[l][1].start.offset===a[u][1].end.offset-a[u][1].start.offset){a[l][1].type="strikethroughSequence",a[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},a[u][1].start),end:Object.assign({},a[l][1].end)},d={type:"strikethroughText",start:Object.assign({},a[u][1].end),end:Object.assign({},a[l][1].start)},p=[["enter",c,o],["enter",a[u][1],o],["exit",a[u][1],o],["enter",d,o]],f=o.parser.constructs.insideSpan.null;f&&Me(p,p.length,0,sn(f,a.slice(u+1,l),o)),Me(p,p.length,0,[["exit",d,o],["enter",a[l][1],o],["exit",a[l][1],o],["exit",c,o]]),Me(a,u-1,l-u+3,p),l=u+p.length-2;break}}for(l=-1;++l<a.length;)a[l][1].type==="strikethroughSequenceTemporary"&&(a[l][1].type="data");return a}function i(a,o,l){const u=this.previous,c=this.events;let d=0;return p;function p(m){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(m):(a.enter("strikethroughSequenceTemporary"),f(m))}function f(m){const y=pt(u);if(m===126)return d>1?l(m):(a.consume(m),d++,f);if(d<2&&!n)return l(m);const S=a.exit("strikethroughSequenceTemporary"),g=pt(m);return S._open=!g||g===2&&!!y,S._close=!y||y===2&&!!g,o(m)}}}class ym{constructor(){this.map=[]}add(t,n,r){xm(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 xm(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 bm(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 Sm(){return{flow:{null:{name:"table",tokenize:km,resolveAll:wm}}}}function km(e,t,n){const r=this;let s=0,i=0,a;return o;function o(T){let L=r.events.length-1;for(;L>-1;){const z=r.events[L][1].type;if(z==="lineEnding"||z==="linePrefix")L--;else break}const D=L>-1?r.events[L][1].type:null,$=D==="tableHead"||D==="tableRow"?v:l;return $===v&&r.parser.lazy[r.now().line]?n(T):$(T)}function l(T){return e.enter("tableHead"),e.enter("tableRow"),u(T)}function u(T){return T===124||(a=!0,i+=1),c(T)}function c(T){return T===null?n(T):B(T)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),f):n(T):q(T)?X(e,c,"whitespace")(T):(i+=1,a&&(a=!1,s+=1),T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),a=!0,c):(e.enter("data"),d(T)))}function d(T){return T===null||T===124||J(T)?(e.exit("data"),c(T)):(e.consume(T),T===92?p:d)}function p(T){return T===92||T===124?(e.consume(T),d):d(T)}function f(T){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(T):(e.enter("tableDelimiterRow"),a=!1,q(T)?X(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):m(T))}function m(T){return T===45||T===58?S(T):T===124?(a=!0,e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),y):R(T)}function y(T){return q(T)?X(e,S,"whitespace")(T):S(T)}function S(T){return T===58?(i+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),g):T===45?(i+=1,g(T)):T===null||B(T)?I(T):R(T)}function g(T){return T===45?(e.enter("tableDelimiterFiller"),x(T)):R(T)}function x(T){return T===45?(e.consume(T),x):T===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(T))}function w(T){return q(T)?X(e,I,"whitespace")(T):I(T)}function I(T){return T===124?m(T):T===null||B(T)?!a||s!==i?R(T):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(T)):R(T)}function R(T){return n(T)}function v(T){return e.enter("tableRow"),N(T)}function N(T){return T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),N):T===null||B(T)?(e.exit("tableRow"),t(T)):q(T)?X(e,N,"whitespace")(T):(e.enter("data"),P(T))}function P(T){return T===null||T===124||J(T)?(e.exit("data"),N(T)):(e.consume(T),T===92?F:P)}function F(T){return T===92||T===124?(e.consume(T),P):P(T)}}function wm(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],a=[0,0,0,0],o=!1,l=0,u,c,d;const p=new ym;for(;++n<e.length;){const f=e[n],m=f[1];f[0]==="enter"?m.type==="tableHead"?(o=!1,l!==0&&(Fs(p,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},m.start),end:Object.assign({},m.end)},p.add(n,0,[["enter",u,t]])):m.type==="tableRow"||m.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({},m.start),end:Object.assign({},m.end)},p.add(n,0,[["enter",c,t]])),s=m.type==="tableDelimiterRow"?2:c?3:1):s&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")?(r=!1,a[2]===0&&(i[1]!==0&&(a[0]=a[1],d=Bt(p,t,i,s,void 0,d),i=[0,0,0,0]),a[2]=n)):m.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(a[0]=a[1],d=Bt(p,t,i,s,void 0,d)),i=a,a=[i[1],n,0,0])):m.type==="tableHead"?(o=!0,l=n):m.type==="tableRow"||m.type==="tableDelimiterRow"?(l=n,i[1]!==0?(a[0]=a[1],d=Bt(p,t,i,s,n,d)):a[1]!==0&&(d=Bt(p,t,a,s,n,d)),s=0):s&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")&&(a[3]=n)}for(l!==0&&Fs(p,t,l,u,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=bm(t.events,n))}return e}function Bt(e,t,n,r,s,i){const a=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",o="tableContent";n[0]!==0&&(i.end=Object.assign({},ct(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const l=ct(t.events,n[1]);if(i={type:a,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const u=ct(t.events,n[2]),c=ct(t.events,n[3]),d={type:o,start:Object.assign({},u),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 m=n[2]+1,y=n[3]-n[2]-1;e.add(m,y,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},ct(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function Fs(e,t,n,r,s){const i=[],a=ct(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 ct(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const vm={name:"tasklistCheck",tokenize:Im};function Cm(){return{text:{91:vm}}}function Im(e,t,n){const r=this;return s;function s(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return J(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),a):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),a):n(l)}function a(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):n(l)}function o(l){return B(l)?t(l):q(l)?e.check({tokenize:Tm},t,n)(l):n(l)}}function Tm(e,t,n){return X(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function Mm(e){return ma([Jg(),lm(),mm(e),Sm(),Cm()])}const Rm={};function Am(e){const t=this,n=e||Rm,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(Mm(n)),i.push(Gg()),a.push(Qg(n))}function Em(){var e;return typeof navigator<"u"&&typeof((e=navigator.clipboard)==null?void 0:e.writeText)=="function"}function Lm(e){if(typeof document>"u")return;const t=document.getSelection();t&&(t.removeAllRanges(),e.forEach(n=>t.addRange(n)))}function zs(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},(l,u)=>s.getRangeAt(u).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):Lm(i),o}async function Nm(e){if(!e)return!1;if(Em())try{return await navigator.clipboard.writeText(e),!0}catch{return zs(e)}return zs(e)}const Pm=1300;function jm(e){const[t,n]=C.useState(!1),r=C.useCallback(async()=>{if(!e.text)return;const s=await Nm(e.text);n(!!s)},[e.text]);return C.useEffect(()=>{if(!t||typeof window>"u")return;const s=window.setTimeout(()=>n(!1),e.resetDelayMs??Pm);return()=>window.clearTimeout(s)},[t,e.resetDelayMs]),{copied:t,copy:r}}const Dm=/language-([a-z0-9-]+)/i;function ao(e){return typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(ao).join(""):""}function _m(e){const t=ao(e);return t.endsWith(`
31
+ `)?t.slice(0,-1):t}function Om(e){var n;const t=e?Dm.exec(e):null;return((n=t==null?void 0:t[1])==null?void 0:n.toLowerCase())||"text"}function Fm(e){const t=C.useMemo(()=>Om(e.className),[e.className]),n=C.useMemo(()=>_m(e.children),[e.children]),{copied:r,copy:s}=jm({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(ur,{className:"h-3.5 w-3.5"}):h.jsx(tl,{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 Bs=14e4,zm=new Set(["http:","https:","mailto:","tel:"]);function Bm(e){return e.length<=Bs?e:`${e.slice(0,Bs)}
32
+
33
+ ...`}function $s(e){if(!e)return null;if(e.startsWith("#")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))return e;try{const t=new URL(e);return zm.has(t.protocol)?e:null}catch{return null}}function $m(e){return/^https?:\/\//i.test(e)}function Um(e){const t=e.role==="user",n=C.useMemo(()=>({a:({href:r,children:s,...i})=>{const a=$s(r);if(!a)return h.jsx("span",{className:"chat-link-invalid",children:s});const o=$m(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=$s(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(`
34
+ `)?h.jsx("code",{...i,className:ue("chat-inline-code",r),children:s}):h.jsx(Fm,{className:r,texts:e.texts,children:s})}}),[e.texts]);return h.jsx("div",{className:ue("chat-markdown",t?"chat-markdown-user":"chat-markdown-assistant"),children:h.jsx(mp,{skipHtml:!0,remarkPlugins:[Am],components:n,children:Bm(e.text)})})}function Km(e){return h.jsxs("details",{className:"mt-3",open:!0,children:[h.jsx("summary",{className:ue("cursor-pointer text-xs",e.isUser?"text-primary-100":"text-gray-500"),children:e.label}),h.jsx("pre",{className:ue("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 Us=220;function Hm(e){const t=e.toLowerCase();return t.includes("exec")||t.includes("shell")||t.includes("command")?h.jsx(nl,{className:"h-3.5 w-3.5"}):t.includes("search")?h.jsx(dr,{className:"h-3.5 w-3.5"}):t.includes("fetch")||t.includes("http")||t.includes("web")?h.jsx(rl,{className:"h-3.5 w-3.5"}):t.includes("read")||t.includes("file")?h.jsx(sl,{className:"h-3.5 w-3.5"}):t.includes("message")||t.includes("send")?h.jsx(il,{className:"h-3.5 w-3.5"}):t.includes("cron")||t.includes("schedule")?h.jsx(al,{className:"h-3.5 w-3.5"}):h.jsx(Si,{className:"h-3.5 w-3.5"})}function Vm({card:e}){var i;const t=((i=e.output)==null?void 0:i.trim())??"",n=t.length>Us||t.includes(`
35
+ `),r=n?`${t.slice(0,Us)}...`: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:[Hm(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 qm(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 Wm(e){const{message:t,texts:n}=e,{role:r}=t,s=r==="user";return h.jsx("div",{className:ue("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(Um,{text:i.text,role:r,texts:n},`markdown-${a}`):i.type==="reasoning"?h.jsx(Km,{label:i.label,text:i.text,isUser:s},`reasoning-${a}`):i.type==="tool-card"?h.jsx("div",{className:"mt-0.5",children:h.jsx(Vm,{card:i.card})},`tool-${a}`):i.type==="unknown"?h.jsx(qm,{label:i.label,rawType:i.rawType,text:i.text},`unknown-${a}`):null)})})}function Gm(e){return h.jsxs("div",{className:ue("px-1 text-[11px] leading-4 text-gray-400",e.isUser?"text-right":"text-left"),children:[e.roleLabel," · ",e.timestampLabel]})}const Qm=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Xm(e){const t=e.trim();return t?t.replace(Qm,"").trim().length>0:!1}function Ym(e){return e.parts.some(t=>t.type==="markdown"||t.type==="reasoning"?Xm(t.text):!0)}function Jm(e){const t=e.messages.filter(Ym),n=t.some(r=>r.role==="assistant"&&(r.status==="streaming"||r.status==="pending"));return h.jsxs("div",{className:ue("space-y-5",e.className),children:[t.map(r=>{const s=r.role==="user";return h.jsxs("div",{className:ue("flex gap-3",s?"justify-end":"justify-start"),children:[s?null:h.jsx(dn,{role:r.role}),h.jsxs("div",{className:ue("w-fit max-w-[92%] space-y-2",s&&"flex flex-col items-end"),children:[h.jsx(Wm,{message:r,texts:e.texts}),h.jsx(Gm,{roleLabel:r.roleLabel,timestampLabel:r.timestampLabel,isUser:s})]}),s?h.jsx(dn,{role:r.role}):null]},r.id)}),e.isSending&&!n?h.jsxs("div",{className:"flex justify-start gap-3",children:[h.jsx(dn,{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 Zm=10;function Ks(e){e.scrollTop=e.scrollHeight}function ey(e){const t=C.useRef(!0),n=C.useRef(!1),r=C.useRef(null),s=C.useRef(!1),i=C.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??Zm)},[e.scrollRef,e.stickyThresholdPx]);return C.useEffect(()=>{r.current!==e.resetKey&&(r.current=e.resetKey,t.current=!0,s.current=!0)},[e.resetKey]),C.useLayoutEffect(()=>{if(!s.current||e.isLoading||!e.hasContent)return;const a=e.scrollRef.current;a&&(s.current=!1,n.current=!0,Ks(a))},[e.hasContent,e.isLoading,e.scrollRef]),C.useLayoutEffect(()=>{if(!t.current||!e.hasContent)return;const a=e.scrollRef.current;a&&(n.current=!0,Ks(a))},[e.contentVersion,e.hasContent,e.scrollRef]),{onScroll:i}}function _r(){return Zi()}function oo(e){return qu(e)}function lo(e){return Gu(e)}function uo(e){return ea(e,"skill")}const ty={isProviderStateResolved:!1,composerNodes:_r(),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=en(e=>({snapshot:ty,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),ny={sessionRunStatusByKey:new Map,isLocallyRunning:!1,activeBackendRunId:null},er=en(e=>({snapshot:ny,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),ry={sessions:[],selectedSessionKey:null,selectedAgentId:"main",query:"",isLoading:!1},se=en(e=>({snapshot:ry,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function sy(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=[],l=[];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):l.push(c)}const u=[];return i.length>0&&u.push({label:A("chatSidebarToday"),sessions:i}),a.length>0&&u.push({label:A("chatSidebarYesterday"),sessions:a}),o.length>0&&u.push({label:A("chatSidebarPrevious7Days"),sessions:o}),l.length>0&&u.push({label:A("chatSidebarOlder"),sessions:l}),u}function iy(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}function ay(e,t){const n=e.trim().toLowerCase();if(!n||n==="native")return null;const r=t.find(s=>s.value.trim().toLowerCase()===n);return r!=null&&r.label.trim()?r.label.trim():n.split(/[-_]+/g).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}const oy=[{target:"/cron",label:()=>A("chatSidebarScheduledTasks"),icon:hr},{target:"/skills",label:()=>A("chatSidebarSkills"),icon:cr}];function ly(){var x,w;const e=yr(),t=vl(),[n,r]=C.useState(!1),s=K(I=>I.snapshot),i=se(I=>I.snapshot),a=er(I=>I.snapshot),o=Cl(I=>I.connectionStatus),{language:l,setLanguage:u}=gr(),{theme:c,setTheme:d}=Il(),p=A(((x=zr.find(I=>I.value===c))==null?void 0:x.labelKey)??"themeWarm"),f=((w=Br.find(I=>I.value===l))==null?void 0:w.label)??l,m=C.useMemo(()=>sy(i.sessions),[i.sessions]),y=s.defaultSessionType||"native",S=C.useMemo(()=>s.sessionTypeOptions.filter(I=>I.value!==y),[y,s.sessionTypeOptions]),g=I=>{l!==I&&(u(I),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(Tl,{className:"flex items-center gap-2.5 min-w-0",suffix:h.jsx(ku,{status:o})})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsxs(nt,{variant:"primary",className:Te("min-w-0 rounded-xl",S.length>0?"flex-1 rounded-r-md":"w-full"),onClick:()=>{r(!1),e.chatSessionListManager.createSession(y)},children:[h.jsx(ol,{className:"h-4 w-4 mr-2"}),A("chatSidebarNewTask")]}),S.length>0?h.jsxs(lu,{open:n,onOpenChange:r,children:[h.jsx(uu,{asChild:!0,children:h.jsx(nt,{variant:"primary",size:"icon",className:"h-9 w-10 shrink-0 rounded-xl rounded-l-md","aria-label":A("chatSessionTypeLabel"),children:h.jsx(lr,{className:"h-4 w-4"})})}),h.jsxs(cu,{align:"end",className:"w-64 p-2",children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium uppercase tracking-wider text-gray-400",children:A("chatSessionTypeLabel")}),h.jsx("div",{className:"mt-1 space-y-1",children:S.map(I=>h.jsxs("button",{type:"button",onClick:()=>{e.chatSessionListManager.createSession(I.value),r(!1)},className:"w-full rounded-xl px-3 py-2 text-left transition-colors hover:bg-gray-100",children:[h.jsx("div",{className:"text-[13px] font-medium text-gray-900",children:I.label}),h.jsx("div",{className:"mt-0.5 text-[11px] text-gray-500",children:A("chatSidebarNewTask")})]},I.value))})]})]}):null]})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"relative",children:[h.jsx(dr,{className:"h-3.5 w-3.5 absolute left-3 top-2.5 text-gray-400"}),h.jsx(Ri,{value:i.query,onChange:I=>e.chatSessionListManager.setQuery(I.target.value),placeholder:A("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:oy.map(I=>{const R=I.icon;return h.jsx("li",{children:h.jsx(Fr,{to:I.target,className:({isActive:v})=>Te("group w-full flex items-center gap-3 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150",v?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-600 hover:bg-gray-200/60 hover:text-gray-900"),children:({isActive:v})=>h.jsxs(h.Fragment,{children:[h.jsx(R,{className:Te("h-4 w-4 transition-colors",v?"text-gray-900":"text-gray-500 group-hover:text-gray-800")}),h.jsx("span",{children:I.label()})]})})},I.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:i.isLoading?h.jsx("div",{className:"text-xs text-gray-500 p-3",children:A("sessionsLoading")}):m.length===0?h.jsxs("div",{className:"p-4 text-center",children:[h.jsx(ll,{className:"h-6 w-6 mx-auto mb-2 text-gray-300"}),h.jsx("div",{className:"text-xs text-gray-500",children:A("sessionsEmpty")})]}):h.jsx("div",{className:"space-y-3",children:m.map(I=>h.jsxs("div",{children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider",children:I.label}),h.jsx("div",{className:"space-y-0.5",children:I.sessions.map(R=>{const v=i.selectedSessionKey===R.key,N=a.sessionRunStatusByKey.get(R.key),P=ay(R.sessionType,s.sessionTypeOptions);return h.jsxs("button",{onClick:()=>e.chatSessionListManager.selectSession(R.key),className:Te("w-full rounded-xl px-3 py-2 text-left transition-all text-[13px]",v?"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.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[h.jsx("span",{className:"truncate font-medium",children:iy(R)}),P?h.jsx("span",{className:Te("shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none",v?"border-gray-300 bg-white/80 text-gray-700":"border-gray-200 bg-gray-100 text-gray-500"),children:P}):null]}),h.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:N?h.jsx(Wl,{status:N}):null})]}),h.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:[R.messageCount," · ",tn(R.updatedAt)]})]},R.key)})})]},I.label))})}),h.jsxs("div",{className:"px-3 py-3 border-t border-gray-200/60 space-y-0.5",children:[h.jsx(Fr,{to:"/settings",className:({isActive:I})=>Te("group w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-[13px] font-medium transition-all duration-150",I?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-600 hover:bg-gray-200/60 hover:text-gray-900"),children:({isActive:I})=>h.jsxs(h.Fragment,{children:[h.jsx(ul,{className:Te("h-4 w-4 transition-colors",I?"text-gray-900":"text-gray-500 group-hover:text-gray-800")}),h.jsx("span",{children:A("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(cl,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:A("docBrowserHelp")})]}),h.jsxs(Fn,{value:c,onValueChange:I=>d(I),children:[h.jsxs(zn,{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(dl,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:A("theme")})]}),h.jsx("span",{className:"ml-auto text-[11px] text-gray-500",children:p})]}),h.jsx(Bn,{children:zr.map(I=>h.jsx(Ct,{value:I.value,className:"text-xs",children:A(I.labelKey)},I.value))})]}),h.jsxs(Fn,{value:l,onValueChange:I=>g(I),children:[h.jsxs(zn,{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(hl,{className:"h-4 w-4 text-gray-400"}),h.jsx("span",{children:A("language")})]}),h.jsx("span",{className:"ml-auto text-[11px] text-gray-500",children:f})]}),h.jsx(Bn,{children:Br.map(I=>h.jsx(Ct,{value:I.value,className:"text-xs",children:I.label},I.value))})]})]})]})}const Oe={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function $t(e){return(e??"").trim().toLowerCase()}function Hs(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 uy(e,t){const n=$t(t);if(!n)return Oe.fallback;const r=$t(e.key),s=$t(e.label||e.key),i=$t(`${e.descriptionZh??""} ${e.description??""}`),a=s.split(/[\s/_-]+/).filter(Boolean);return r===n?Oe.exactSpec:s===n?Oe.exactLabel:r.startsWith(n)?Oe.prefixSpec:s.startsWith(n)?Oe.prefixLabel:a.some(o=>o.startsWith(n))?Oe.prefixToken:r.includes(n)?Oe.containsSpec:s.includes(n)?Oe.containsLabel:i.includes(n)?Oe.containsDescription:Hs(n,s)||Hs(n,r)?Oe.subsequence:0}function cy(e,t,n){const r=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0});return e.map((s,i)=>({record:s,order:i,score:uy(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(),l=r.compare(a,o);return l!==0?l: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 dy(e){return e.map(t=>({key:t.key,label:t.label,description:t.descriptionZh||t.description||"",badgeLabel:t.badgeLabel}))}function hy(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:dy(e.skillRecords),selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}function fy(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 py(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 gy(e){const t=[];for(const n of["off",...e])t.includes(n)||t.push(n);return t}function my(e){if(e.supportedLevels.length===0)return null;const t=gy(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 yy(){return{off:A("chatThinkingLevelOff"),minimal:A("chatThinkingLevelMinimal"),low:A("chatThinkingLevelLow"),medium:A("chatThinkingLevelMedium"),high:A("chatThinkingLevelHigh"),adaptive:A("chatThinkingLevelAdaptive"),xhigh:A("chatThinkingLevelXhigh")}}function xy(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 by(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 Sy(){var R;const e=yr(),{language:t}=gr(),n=K(v=>v.snapshot),[r,s]=C.useState(null),i=C.useMemo(()=>A("chatSkillsPickerOfficial"),[t]),a=C.useMemo(()=>({slashSkillSubtitle:A("chatSlashTypeSkill"),slashSkillSpecLabel:A("chatSlashSkillSpec"),noSkillDescription:A("chatSkillsPickerNoDescription")}),[t]),o=C.useMemo(()=>xy(n.skillRecords,i),[n.skillRecords,i]),l=C.useMemo(()=>by(n.modelOptions),[n.modelOptions]),u=l.length>0,c=!n.isProviderStateResolved&&!u,d=n.isProviderStateResolved&&!u,p=(c||d)&&!n.isSending||n.sessionTypeUnavailable,f=c?"":u?A("chatInputPlaceholder"):A("chatModelNoOptions"),m=C.useMemo(()=>cy(o,r??"",a),[r,o,a]),y=l.find(v=>v.value===n.selectedModel),S=y==null?void 0:y.thinkingCapability,g=(S==null?void 0:S.supported)??[],x=n.stopDisabledReason==="__preparing__"?A("chatStopPreparing"):((R=n.stopDisabledReason)==null?void 0:R.trim())||A("chatStopUnavailable"),w=[py({modelOptions:l,selectedModel:n.selectedModel,isModelOptionsLoading:c,hasModelOptions:u,onValueChange:e.chatInputManager.selectModel,texts:{modelSelectPlaceholder:A("chatSelectModel"),modelNoOptionsLabel:A("chatModelNoOptions")}}),my({supportedLevels:g,selectedThinkingLevel:n.selectedThinkingLevel,defaultThinkingLevel:(S==null?void 0:S.default)??null,onValueChange:v=>e.chatInputManager.selectThinkingLevel(v),texts:{thinkingLabels:yy()}})].filter(v=>v!==null),I=hy({skillRecords:o,selectedSkills:n.selectedSkills,isLoading:n.isSkillsLoading,onSelectedKeysChange:e.chatInputManager.selectSkills,texts:{title:A("chatSkillsPickerTitle"),searchPlaceholder:A("chatSkillsPickerSearchPlaceholder"),emptyLabel:A("chatSkillsPickerEmpty"),loadingLabel:A("sessionsLoading"),manageLabel:A("chatSkillsPickerManage")}});return h.jsx(sc,{composer:{nodes:n.composerNodes,placeholder:f,disabled:p,onNodesChange:e.chatInputManager.setComposerNodes,onSlashQueryChange:s},slashMenu:{isLoading:n.isSkillsLoading,items:m,texts:{slashLoadingLabel:A("chatSlashLoading"),slashSectionLabel:A("chatSlashSectionSkills"),slashEmptyLabel:A("chatSlashNoResult"),slashHintLabel:A("chatSlashHint"),slashSkillHintLabel:A("chatSlashSkillHint")}},hint:fy({isModelOptionsLoading:c,isModelOptionsEmpty:d,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:A("chatModelNoOptions"),configureProviderLabel:A("chatGoConfigureProvider")}}),toolbar:{selects:w,accessories:[{key:"attach",label:A("chatInputAttachComingSoon"),icon:"paperclip",disabled:!0,tooltip:A("chatInputAttachComingSoon")}],skillPicker:I,actions:{sendError:n.sendError,isSending:n.isSending,canStopGeneration:n.canStopGeneration,sendDisabled:n.draft.trim().length===0||!u||n.sessionTypeUnavailable,stopDisabled:!n.canStopGeneration,stopHint:x,sendButtonLabel:A("chatSend"),stopButtonLabel:A("chatStop"),onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}})}function qe(e){return typeof e=="function"}function co(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 An=co(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
36
+ `+n.map(function(r,s){return s+1+") "+r.toString()}).join(`
37
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function tr(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var un=(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=Dn(a),l=o.next();!l.done;l=o.next()){var u=l.value;u.remove(this)}}catch(y){t={error:y}}finally{try{l&&!l.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}else a.remove(this);var c=this.initialTeardown;if(qe(c))try{c()}catch(y){i=y instanceof An?y.errors:[y]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var p=Dn(d),f=p.next();!f.done;f=p.next()){var m=f.value;try{Vs(m)}catch(y){i=i??[],y instanceof An?i=_n(_n([],On(i)),On(y.errors)):i.push(y)}}}catch(y){r={error:y}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}if(i)throw new An(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Vs(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)&&tr(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&tr(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),ho=un.EMPTY;function fo(e){return e instanceof un||e&&"closed"in e&&qe(e.remove)&&qe(e.add)&&qe(e.unsubscribe)}function Vs(e){qe(e)?e():e.unsubscribe()}var ky={Promise:void 0},wy={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,_n([e,t],On(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function vy(e){wy.setTimeout(function(){throw e})}function qs(){}function Wt(e){e()}var po=(function(e){Lt(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,fo(n)&&n.add(r)):r.destination=Ty,r}return t.create=function(n,r,s){return new nr(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})(un),Cy=(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){Ut(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){Ut(r)}else Ut(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Ut(n)}},e})(),nr=(function(e){Lt(t,e);function t(n,r,s){var i=e.call(this)||this,a;return qe(n)||!n?a={next:n??void 0,error:r??void 0,complete:s??void 0}:a=n,i.destination=new Cy(a),i}return t})(po);function Ut(e){vy(e)}function Iy(e){throw e}var Ty={closed:!0,next:qs,error:Iy,complete:qs},My=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Ry(e){return e}function Ay(e){return e.length===0?Ry:e.length===1?e[0]:function(n){return e.reduce(function(r,s){return s(r)},n)}}var Zt=(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=Ly(t)?t:new nr(t,n,r);return Wt(function(){var a=s,o=a.operator,l=a.source;i.add(o?o.call(i,l):l?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=Ws(n),new n(function(s,i){var a=new nr({next:function(o){try{t(o)}catch(l){i(l),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[My]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Ay(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=Ws(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 Ws(e){var t;return(t=e??ky.Promise)!==null&&t!==void 0?t:Promise}function Ey(e){return e&&qe(e.next)&&qe(e.error)&&qe(e.complete)}function Ly(e){return e&&e instanceof po||Ey(e)&&fo(e)}var Ny=co(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ke=(function(e){Lt(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 Gs(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new Ny},t.prototype.next=function(n){var r=this;Wt(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var a=Dn(r.currentObservers),o=a.next();!o.done;o=a.next()){var l=o.value;l.next(n)}}catch(u){s={error:u}}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;Wt(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;Wt(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?ho:(this.currentObservers=null,o.push(n),new un(function(){r.currentObservers=null,tr(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 Zt;return n.source=this,n},t.create=function(n,r){return new Gs(n,r)},t})(Zt),Gs=(function(e){Lt(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:ho},t})(Ke),ut=(function(e){Lt(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})(Ke);const fe=[];for(let e=0;e<256;++e)fe.push((e+256).toString(16).slice(1));function Py(e,t=0){return(fe[e[t+0]]+fe[e[t+1]]+fe[e[t+2]]+fe[e[t+3]]+"-"+fe[e[t+4]]+fe[e[t+5]]+"-"+fe[e[t+6]]+fe[e[t+7]]+"-"+fe[e[t+8]]+fe[e[t+9]]+"-"+fe[e[t+10]]+fe[e[t+11]]+fe[e[t+12]]+fe[e[t+13]]+fe[e[t+14]]+fe[e[t+15]]).toLowerCase()}let En;const jy=new Uint8Array(16);function Dy(){if(!En){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");En=crypto.getRandomValues.bind(crypto)}return En(jy)}const _y=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Qs={randomUUID:_y};function rr(e,t,n){var s;if(Qs.randomUUID&&!e)return Qs.randomUUID();e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??Dy();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,Py(r)}var le=(e=>(e.CALL="call",e.RESULT="result",e.PARTIAL_CALL="partial-call",e.ERROR="error",e.CANCELLED="cancelled",e))(le||{}),G=(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))(G||{});function Oy(e){return!e||e.remoteStopCapable&&e.remoteRunId?null:e.remoteStopCapable?"__preparing__":e.remoteStopReason??""}const Fy=e=>{try{return JSON.parse(e)}catch{return}},Xs=e=>({toolCallId:e.id,toolName:e.function.name,args:e.function.arguments,parsedArgs:Fy(e.function.arguments),status:le.CALL});function zy(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"||![le.CALL,le.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:le.RESULT,result:{error:"invalid_args",raw:i.toolInvocation.args}}}}return{...i,toolInvocation:{...i.toolInvocation,args:i.toolInvocation.args,parsedArgs:a,status:le.RESULT,result:n}}})}:r})}function sr(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 Ys(e){if(e instanceof Error){const n=e.message.trim();if(n)return n}return String(e??"").trim()||"Failed to send message"}function Js(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 By{constructor(t){O(this,"currentMessageId");O(this,"currentReasoningMessageId");O(this,"currentReasoningContent","");O(this,"currentToolCallId");O(this,"currentToolCallMessageId");O(this,"currentToolCallName");O(this,"currentToolCallArgs","");O(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===le.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 G.RUN_STARTED:break;case G.TEXT_START:this.handleTextStart(t);break;case G.TEXT_DELTA:this.handleTextContent(t);break;case G.TEXT_END:this.handleTextEnd();break;case G.REASONING_START:this.handleReasoningStart(t);break;case G.REASONING_DELTA:this.handleReasoningContent(t);break;case G.REASONING_END:this.handleReasoningEnd();break;case G.TOOL_CALL_START:this.handleToolCallStart(t);break;case G.TOOL_CALL_ARGS_DELTA:this.handleToolCallArgsDelta(t);break;case G.TOOL_CALL_ARGS:this.handleToolCallArgs(t);break;case G.TOOL_CALL_END:this.handleToolCallEnd(),this.emitToolCallEvents();break;case G.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 l;this.currentToolCallId=t.toolCallId,this.currentToolCallName=t.toolName,this.currentToolCallArgs="",this.currentToolCallMessageId=t.messageId;const n={type:"tool-invocation",toolInvocation:{status:le.PARTIAL_CALL,toolCallId:this.currentToolCallId,toolName:this.currentToolCallName,args:""}},r=this.sessionManager.getMessages(),s=(l=t.messageId)==null?void 0:l.trim(),i=this.findAssistantMessageById(s);if(i){this.currentToolCallMessageId=i.id;const u=i.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);if(u&&u.type==="tool-invocation"){this.currentToolCallArgs=u.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 u=a.parts.find(c=>c.type==="tool-invocation"&&c.toolInvocation.toolCallId===this.currentToolCallId);this.currentToolCallArgs=(u==null?void 0:u.type)==="tool-invocation"?u.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 u=rr();this.currentToolCallMessageId=u,this.sessionManager.addMessages([{id:u,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:le.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:G.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:{...Xs(n),status:le.CALL}};break}}this.sessionManager.updateMessage({...r,parts:s})}else{const s=((t=this.currentToolCallMessageId)==null?void 0:t.trim())||rr();this.sessionManager.addMessages([{id:s,role:"assistant",parts:[{type:"tool-invocation",toolInvocation:{...Xs(n),status:le.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:le.RESULT})}}class $y{constructor(){O(this,"disposables",[]);O(this,"addDisposable",t=>{this.disposables.push(t)});O(this,"dispose",()=>{this.disposables.forEach(t=>t()),this.disposables=[]})}}class Uy extends $y{constructor(n=null,r){super();O(this,"_messages$",new ut([]));O(this,"messages$");O(this,"threadId$",new ut(null));O(this,"isAgentResponding$",new ut(!1));O(this,"activeRun$",new ut(null));O(this,"lastError$",new ut(null));O(this,"isAwaitingResponse$",new ut(!1));O(this,"runCompleted$",new Ke);O(this,"runError$",new Ke);O(this,"runMetadata$",new Ke);O(this,"activeSubscription",null);O(this,"addMessagesEvent$",new Ke);O(this,"updateMessageEvent$",new Ke);O(this,"setMessagesEvent$",new Ke);O(this,"toolCall$",new Ke);O(this,"eventHandler",new By(this));O(this,"runIdCounter",0);O(this,"metadataParsers");O(this,"callbacks");O(this,"getMessages",()=>this._messages$.getValue());O(this,"setMessages",n=>{this._messages$.next(n),this.setMessagesEvent$.next({messages:n})});O(this,"handleEvent",n=>{this.eventHandler.handleEvent(n)});O(this,"setCallbacks",n=>{this.callbacks=n});O(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});O(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)});O(this,"removeMessages",n=>{n.length!==0&&this._messages$.next(this.getMessages().filter(r=>!n.includes(r.id)))});O(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)});O(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)});O(this,"send",async n=>{(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun(),this.lastError$.next(null);const r=n.message.trim();r&&(this.addMessages([{id:rr(),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}))});O(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})))});O(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}))});O(this,"handleAgentResponse",n=>{this.activeSubscription&&this.activeSubscription.unsubscribe(),this.activeSubscription=n.subscribe(r=>{var s,i,a,o,l,u,c,d,p;if(r.type===G.RUN_METADATA){const f=r,m=this.activeRun$.getValue(),y=((s=f.runId)==null?void 0:s.trim())||(m?`ui-${m.localRunId}`:"");this.metadataParsers&&m&&this.isMatchingRun(m,y)&&this.processRunMetadata(m,f.metadata),this.runMetadata$.next({runId:y,metadata:f.metadata});return}if(this.handleEvent(r),r.type===G.RUN_FINISHED){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),m=((i=r.runId)==null?void 0:i.trim())||(f?`ui-${f.localRunId}`:"");if(!f||!this.isMatchingRun(f,m))return;const y=f.sessionId;this.activeRun$.next(null),y&&((o=(a=this.callbacks).onRunSettled)==null||o.call(a,{sourceSessionId:y}))}else if(r.type===G.RUN_ERROR){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),m=((l=r.runId)==null?void 0:l.trim())||(f?`ui-${f.localRunId}`:""),y=sr(r.error);if(this.runError$.next({runId:m,error:r.error,isAbort:y}),!f||!this.isMatchingRun(f,m)){this.activeRun$.next(null);return}const S=f.sessionId;if(y){this.activeRun$.next(null),S&&((c=(u=this.callbacks).onRunSettled)==null||c.call(u,{sourceSessionId:S}));return}const g=Ys(r.error);this.lastError$.next(g),this.activeRun$.next(null),S&&this.addMessages([Js(g,{sessionKey:S,status:"error"})]),(p=(d=this.callbacks).onRunError)==null||p.call(d,{error:g,sourceMessage:f.sourceMessage,restoreDraft:f.restoreDraftOnError})}})});O(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)});O(this,"runAgent",async n=>{var a,o,l,u;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=zy(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=sr(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=Ys(c);this.lastError$.next(f),p.sessionId&&this.addMessages([Js(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)&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:p.sessionId}))}});O(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)});O(this,"applyReadyMetadata",(n,r)=>{var i,a,o,l,u;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(),(u=(l=this.callbacks).onSessionChanged)==null||u.call(l,s.sessionId)),this.activeRun$.next(s)});O(this,"applyFinalMetadata",(n,r)=>{var a,o,l,u;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&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:s,resultSessionId:i}))});O(this,"isMatchingRun",(n,r)=>r.trim()?r===`ui-${n.localRunId}`:!1);O(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:le.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:le.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())}}const Ky=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Hy(e){return typeof e=="object"&&e!==null}function Vy(e){return e.type==="text"&&typeof e.text=="string"}function qy(e){return e.type==="reasoning"&&typeof e.reasoning=="string"}function Wy(e){return e.type!=="tool-invocation"||!Hy(e.toolInvocation)?!1:typeof e.toolInvocation.toolName=="string"}function Gy(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 Qy(e,t){return e==="user"?t.user:e==="assistant"?t.assistant:e==="tool"?t.tool:e==="system"?t.system:t.fallback}function Xy(e){return e==="user"||e==="assistant"||e==="tool"||e==="system"?e:"message"}function Yy(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 Zs(e){const t=e.trim();return t&&t.replace(Ky,"").trim()?t:null}function Jy(e){return e.uiMessages.map(t=>{var n;return{id:t.id,role:Xy(t.role),roleLabel:Qy(t.role,e.texts.roleLabels),timestampLabel:e.formatTimestamp(Gy(t)),status:(n=t.meta)==null?void 0:n.status,parts:t.parts.map(r=>{if(Vy(r)){const s=Zs(r.text);return s?{type:"markdown",text:s}:null}if(qy(r)){const s=Zs(r.reasoning);return s?{type:"reasoning",text:s,label:e.texts.reasoningLabel}:null}if(Wy(r)){const s=r.toolInvocation,i=Gl(s.parsedArgs??s.args),a=typeof s.error=="string"&&s.error.trim()?s.error.trim():s.result!=null?Ur(s.result).trim():"",o=s.status==="result"||s.status==="error"||s.status==="cancelled",l={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:Yy(l,e.texts)}}return{type:"unknown",label:e.texts.unknownPartLabel,rawType:typeof r.type=="string"?r.type:"unknown",text:Ur(r)}}).filter(r=>r!==null)}})}function Zy(e){const{language:t}=gr(),n=C.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=C.useMemo(()=>Jy({uiMessages:n,formatTimestamp:s=>tn(s,t),texts:{roleLabels:{user:A("chatRoleUser"),assistant:A("chatRoleAssistant"),tool:A("chatRoleTool"),system:A("chatRoleSystem"),fallback:A("chatRoleMessage")},reasoningLabel:A("chatReasoning"),toolCallLabel:A("chatToolCall"),toolResultLabel:A("chatToolResult"),toolNoOutputLabel:A("chatToolNoOutput"),toolOutputLabel:A("chatToolOutput"),unknownPartLabel:A("chatUnknownPart")}}),[t,n]);return h.jsx(Jm,{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:A("chatCodeCopy"),copiedCodeLabel:A("chatCodeCopied"),typingLabel:A("chatTyping")}})}const ex=[{icon:fl,titleKey:"chatWelcomeCapability1Title",descKey:"chatWelcomeCapability1Desc"},{icon:cr,titleKey:"chatWelcomeCapability2Title",descKey:"chatWelcomeCapability2Desc"},{icon:hr,titleKey:"chatWelcomeCapability3Title",descKey:"chatWelcomeCapability3Desc"}];function tx({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(ki,{className:"h-8 w-8 text-primary"})}),h.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:A("chatWelcomeTitle")}),h.jsx("p",{className:"text-sm text-gray-500 mb-8",children:A("chatWelcomeSubtitle")}),h.jsx("div",{className:"grid grid-cols-3 gap-3",children:ex.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:A(t.titleKey)}),h.jsx("div",{className:"text-[11px] text-gray-500 leading-relaxed",children:A(t.descKey)})]},t.titleKey)})})]})})}const nx={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,sessionTypeLabel:null,selectedSessionKey:null,sessionDisplayName:void 0,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,uiMessages:[],isSending:!1,isAwaitingAssistantOutput:!1},Ve=en(e=>({snapshot:nx,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function rx(){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 sx(){var d;const e=yr(),t=Ve(p=>p.snapshot),n=C.useRef(null),r=t.threadRef??n,s=!!(t.selectedSessionKey||t.sessionTypeLabel),i=t.sessionDisplayName||t.selectedSessionKey||A("chatSidebarNewTask"),a=!t.selectedSessionKey&&t.uiMessages.length===0&&!t.isSending,o=t.modelOptions.length>0,l=t.isProviderStateResolved&&!o,u=t.isHistoryLoading&&t.uiMessages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:c}=ey({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:Te("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",s?"py-3 opacity-100":"h-0 py-0 opacity-0 border-b-0"),children:[h.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[h.jsx("span",{className:"text-sm font-medium text-gray-700 truncate",children:i}),t.sessionTypeLabel?h.jsx("span",{className:"shrink-0 rounded-full border border-gray-200 bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600",children:t.sessionTypeLabel}):null]}),t.selectedSessionKey?h.jsx(nt,{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(vi,{className:"h-4 w-4"})}):null]}),l&&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:A("chatModelNoOptions")}),h.jsx("button",{type:"button",onClick:e.chatThreadManager.goToProviders,className:"text-xs font-semibold text-amber-900 underline-offset-2 hover:underline",children:A("chatGoConfigureProvider")})]}),t.sessionTypeUnavailable&&((d=t.sessionTypeUnavailableMessage)==null?void 0:d.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:c,className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar",children:a?h.jsx(tx,{onCreateSession:e.chatThreadManager.createSession}):u?h.jsx("div",{className:"h-full"}):t.uiMessages.length===0?h.jsx("div",{className:"px-5 py-5 text-sm text-gray-500",children:A("chatNoMessages")}):h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Zy,{uiMessages:t.uiMessages,isSending:t.isSending&&t.isAwaitingAssistantOutput})})}),h.jsx(Sy,{})]}):h.jsx(rx,{})}function ei(e){return tn(e??void 0)}function ix(e){return typeof e!="number"||!Number.isFinite(e)?"-":tn(new Date(e))}function ax(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 ox(e){const t=e.schedule;return t.kind==="cron"?t.expr?`cron ${t.expr}`:"cron":t.kind==="every"?`every ${ax(t.everyMs)}`:t.kind==="at"?`at ${ix(t.atMs)}`:"-"}function lx(e){if(!e.payload.deliver)return"-";const t=e.payload.channel??"-",n=e.payload.to??"-";return`${t}:${n}`}function ux(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 cx(e,t){return t==="all"?!0:t==="enabled"?e.enabled:!e.enabled}function dx(){var m;const[e,t]=C.useState(""),[n,r]=C.useState("all"),s=Ml({all:!0}),i=Rl(),a=Al(),o=El(),{confirm:l,ConfirmDialog:u}=pr(),c=C.useMemo(()=>{var S;return(((S=s.data)==null?void 0:S.jobs)??[]).filter(g=>ux(g,e)).filter(g=>cx(g,n))},[s.data,e,n]),d=async y=>{await l({title:`${A("cronDeleteConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,variant:"destructive",confirmLabel:A("delete")})&&i.mutate({id:y.id})},p=async y=>{const S=!y.enabled;await l({title:S?`${A("cronEnableConfirm")}?`:`${A("cronDisableConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,variant:S?"default":"destructive",confirmLabel:S?A("cronEnable"):A("cronDisable")})&&a.mutate({id:y.id,enabled:S})},f=async y=>{const S=!y.enabled;await l({title:S?`${A("cronRunForceConfirm")}?`:`${A("cronRunConfirm")}?`,description:y.name?`${y.name} (${y.id})`:y.id,confirmLabel:A("cronRunNow")})&&o.mutate({id:y.id,force:S})};return h.jsxs(du,{fullHeight:!0,children:[h.jsx(hu,{title:A("cronPageTitle"),description:A("cronPageDescription"),actions:h.jsx(nt,{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(pl,{className:Te("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(Ri,{value:e,onChange:y=>t(y.target.value),placeholder:A("cronSearchPlaceholder"),className:"pl-9"}),h.jsx(hr,{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(Fn,{value:n,onValueChange:y=>r(y),children:[h.jsx(zn,{className:"w-full",children:h.jsx(Ll,{placeholder:A("cronStatusLabel")})}),h.jsxs(Bn,{children:[h.jsx(Ct,{value:"all",children:A("cronStatusAll")}),h.jsx(Ct,{value:"enabled",children:A("cronStatusEnabled")}),h.jsx(Ct,{value:"disabled",children:A("cronStatusDisabled")})]})]})}),h.jsxs("div",{className:"text-xs text-gray-500 ml-auto",children:[A("cronTotalLabel"),": ",((m=s.data)==null?void 0:m.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:A("cronLoading")}):c.length===0?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:A("cronEmpty")}):h.jsx("div",{className:"space-y-4",children:c.map(y=>h.jsx(Nl,{className:"border border-gray-200",children:h.jsx(Pl,{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:y.name||y.id}),h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500",children:y.id}),h.jsx("span",{className:Te("text-[10px] font-semibold px-2 py-0.5 rounded-full",y.enabled?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"),children:y.enabled?A("enabled"):A("disabled")}),y.deleteAfterRun&&h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:A("cronOneShot")})]}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[A("cronScheduleLabel"),": ",ox(y)]}),h.jsx("div",{className:"mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words",children:y.payload.message}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[A("cronDeliverTo"),": ",lx(y)]})]}),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:[A("cronNextRun"),":"]})," ",ei(y.state.nextRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[A("cronLastRun"),":"]})," ",ei(y.state.lastRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[A("cronLastStatus"),":"]})," ",y.state.lastStatus??"-"]}),y.state.lastError&&h.jsx("div",{className:"text-[11px] text-red-500 break-words",children:y.state.lastError})]}),h.jsxs("div",{className:"flex items-start gap-2 flex-wrap justify-end",children:[h.jsxs(nt,{variant:"subtle",size:"sm",onClick:()=>f(y),className:"gap-1",children:[h.jsx(gl,{className:"h-3.5 w-3.5"}),A("cronRunNow")]}),h.jsxs(nt,{variant:y.enabled?"outline":"primary",size:"sm",onClick:()=>p(y),className:"gap-1",children:[h.jsx(ml,{className:"h-3.5 w-3.5"}),y.enabled?A("cronDisable"):A("cronEnable")]}),h.jsxs(nt,{variant:"destructive",size:"sm",onClick:()=>d(y),className:"gap-1",children:[h.jsx(vi,{className:"h-3.5 w-3.5"}),A("delete")]})]})]})})},y.id))})}),h.jsx(u,{})]})}function go(e){const{view:t,routeSessionKey:n,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:i,setSelectedAgentId:a,selectedSessionKeyRef:o,resetStreamState:l,resolveAgentIdFromSessionKey:u}=e;C.useEffect(()=>{if(t==="chat"){if(n){r!==n&&i(n);return}r!==null&&(i(null),l())}},[l,n,r,i,t]),C.useEffect(()=>{const c=r?u(r):null;c&&s!==c&&a(c)},[u,s,r,a]),C.useEffect(()=>{o.current=r},[r,o])}function mo({view:e,confirmDialog:t}){return h.jsxs("div",{className:"h-full flex",children:[h.jsx(ly,{}),e==="chat"?h.jsx(sx,{}):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(dx,{})})}):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(ru,{forcedType:"skills"})})})}),t]})}const ir="sid_";function yo(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 hx(e){const t=Math.random().toString(36).slice(2,8);return`agent:${e}:ui:direct:web-${Date.now().toString(36)}${t}`}function fx(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`${ir}${r}`}function px(e){if(!e.startsWith(ir))return null;const t=e.slice(ir.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 xo(e){if(!e)return null;const t=px(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function gx(e){return`/chat/${fx(e)}`}function mx(e){const t=e.trim();return t.length>0?t:null}function yx(e){return e??null}class bo{constructor(t){this.updateSession=t,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{const n=K.getState().snapshot,s=se.getState().snapshot.selectedSessionKey;s&&this.enqueue({sessionKey:s,patch:{preferredModel:mx(n.selectedModel),preferredThinking:yx(n.selectedThinkingLevel)}})}}enqueue(t){this.queued=t,!this.inFlight&&this.startFlush()}startFlush(){this.inFlight=this.flush().catch(t=>{console.error(`Failed to sync chat session preferences: ${String(t)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})}async flush(){for(;this.queued;){const t=this.queued;this.queued=null,await this.updateSession(t.sessionKey,t.patch)}}}class xx{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.sessionPreferenceSync=new bo($r),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.syncComposerSnapshot=r=>{K.getState().setSnapshot({composerNodes:r,draft:lo(r),selectedSkills:uo(r)})},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&&this.syncComposerSnapshot(oo(i))},this.setComposerNodes=r=>{const s=K.getState().snapshot.composerNodes,i=this.resolveUpdateValue(s,r);Object.is(i,s)||this.syncComposerSnapshot(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=se.getState().snapshot,i=r.draft.trim();if(!i)return;const a=r.selectedSkills,o=r.composerNodes,l=!!s.selectedSessionKey,u=s.selectedSessionKey??hx(s.selectedAgentId);l||this.uiManager.goToSession(u,{replace:!0}),this.setComposerNodes(_r()),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,composerNodes:o})},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=He(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.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=r=>{this.setSelectedThinkingLevel(r),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectSkills=r=>{this.setSelectedSkills(r)},this.syncRemoteSessionType=async r=>{const s=se.getState().snapshot,i=s.selectedSessionKey;if(!i)return;const a=s.sessions.find(o=>o.key===i);a!=null&&a.sessionTypeMutable&&He(a.sessionType)!==r&&await $r(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 bx={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 Sx(e,t){return{driver:"nextbot-stream",mode:"send",payload:e,requestedSkills:t}}function kx(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 wx(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 So{constructor(){this.syncSnapshot=t=>{const n=er.getState().snapshot,r=t.sessionRunStatusByKey;(!r||wx(n.sessionRunStatusByKey,r))&&(t.isLocallyRunning===void 0||Object.is(n.isLocallyRunning,t.isLocallyRunning))&&(t.activeBackendRunId===void 0||Object.is(n.activeBackendRunId,t.activeBackendRunId))||er.getState().setSnapshot(t)}}}class ko{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=se.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)&&se.getState().setSnapshot(r)},this.setSelectedAgentId=r=>{const s=se.getState().snapshot.selectedAgentId,i=this.resolveUpdateValue(s,r);i!==s&&se.getState().setSnapshot({selectedAgentId:i})},this.setSelectedSessionKey=r=>{const s=se.getState().snapshot.selectedSessionKey,i=this.resolveUpdateValue(s,r);i!==s&&se.getState().setSnapshot({selectedSessionKey:i})},this.createSession=r=>{const{snapshot:s}=K.getState(),{defaultSessionType:i}=s,a=i||"native",o=typeof r=="string"&&r.trim().length>0?r.trim():a;this.streamActionsManager.resetStreamState(),this.setSelectedSessionKey(null),K.getState().setSnapshot({pendingSessionType:o}),this.uiManager.goToChatRoot()},this.selectSession=r=>{this.setSelectedSessionKey(r),this.uiManager.goToSession(r)},this.setQuery=r=>{const s=se.getState().snapshot.query,i=this.resolveUpdateValue(s,r);i!==s&&se.getState().setSnapshot({query:i})}}}const Ln=async()=>{},ti=()=>{};class wo{constructor(){this.actions={sendMessage:Ln,stopCurrentRun:Ln,resumeRun:Ln,resetStreamState:ti,applyHistoryMessages:ti},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 vx=async()=>{};class Cx{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:vx},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=Ve.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)&&Ve.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=se.getState();if(!(!s||!await this.uiManager.confirm({title:A("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:A("delete")}))){Ve.getState().setSnapshot({isDeletePending:!0});try{await jl(s),this.streamActionsManager.resetStreamState(),se.getState().setSnapshot({selectedSessionKey:null}),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{Ve.getState().setSnapshot({isDeletePending:!1})}}}}}const Ix=async e=>!1;class vo{constructor(){this.state={pathname:""},this.actions={navigate:null,confirm:Ix},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(gx(t),n)}}}function Tx(e){return e.delta?e.started?[{type:G.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[{type:G.TEXT_START,messageId:e.messageId},{type:G.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[]}function Mx(e){return!1}function Rx(e){var n,r;return((r=(n=e.message)==null?void 0:n.role)==null?void 0:r.toLowerCase().trim())==="assistant"}function Ax(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:G.REASONING_START,messageId:n}),i.push({type:G.REASONING_DELTA,messageId:n,delta:r.reasoning_content.trim()}),i.push({type:G.REASONING_END,messageId:n})),Array.isArray(r.tool_calls))for(let o=0;o<r.tool_calls.length;o+=1){const l=r.tool_calls[o];if(!l||typeof l!="object")continue;const u=l,c=u.function,d=typeof c=="object"&&c?c:null,p=typeof t.seq=="number"?String(t.seq):"unknown",f=typeof u.id=="string"?u.id:`tool-${p}-${o}`,m=typeof(d==null?void 0:d.name)=="string"?d.name:typeof u.name=="string"?u.name:"tool",y=(d==null?void 0:d.arguments)??u.arguments??"",S=typeof y=="string"?y:JSON.stringify(y??{});i.push({type:G.TOOL_CALL_START,messageId:n,toolCallId:f,toolName:m}),i.push({type:G.TOOL_CALL_ARGS,toolCallId:f,args:S}),i.push({type:G.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:G.TOOL_CALL_RESULT,toolCallId:o,content:r.content})}return i}function Co(){return`stream-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ex(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 Lx(e){return Dl(Ex(e.item,e.requestedSkills),{signal:e.signal,onReady:e.onReady,onDelta:e.onDelta,onSessionEvent:e.onSessionEvent})}async function Nx(e){return _l({runId:e.runId,...typeof e.fromEventIndex=="number"?{fromEventIndex:e.fromEventIndex}:{}},{signal:e.signal,onReady:e.onReady,onDelta:e.onDelta,onSessionEvent:e.onSessionEvent})}async function Px(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 Nn(r)))return;const s=await jx(e);for(const i of s){if(n.has(i))continue;if(n.add(i),await Nn(i))return}if(r&&await Nn(r))return}catch{}}async function Nn(e){const t=e.trim();if(!t)return!1;try{return(await Ol({runId:t})).stopped===!0}catch{return!1}}async function jx(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 Dx(e,t);if(a.length>0)return a;i<n-1&&await _x(r)}return[]}async function Dx(e,t){try{const n=await Fl({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 _x(e){return new Promise(t=>{window.setTimeout(t,e)})}function Io(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 Ox(e){var y;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}}},l=(S,g)=>{for(let x=S.length-1;x>=0;x-=1){const w=S[x];if(w.type==="tool-invocation"&&w.toolInvocation.toolCallId===g)return x}return-1},u=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 x=u(S);x.parts=[...x.parts,{type:"text",text:g}]},p=(S,g)=>{if(!g)return;const x=u(S);x.parts=[...x.parts,{type:"reasoning",reasoning:g,details:[]}]},f=S=>{const g=u(S.timestamp),x=l(g.parts,S.toolCallId),w={type:"tool-invocation",toolInvocation:{status:le.CALL,toolCallId:S.toolCallId,toolName:S.toolName,args:S.args,parsedArgs:S.parsedArgs}};if(x>=0){g.parts=[...g.parts.slice(0,x),w,...g.parts.slice(x+1)];return}g.parts=[...g.parts,w]},m=S=>{if(!S.toolCallId)return;const g=u(S.timestamp),x=l(g.parts,S.toolCallId);if(x<0){g.parts=[...g.parts,{type:"tool-invocation",toolInvocation:{status:le.RESULT,toolCallId:S.toolCallId,toolName:S.toolName,args:"{}",parsedArgs:void 0,result:S.result}}];return}const w=g.parts[x];w.type==="tool-invocation"&&(g.parts=[...g.parts.slice(0,x),{...w,toolInvocation:{...w.toolInvocation,status:le.RESULT,result:S.result}},...g.parts.slice(x+1)])};for(const S of e){const g=(y=S.role)==null?void 0:y.toLowerCase().trim();if(!g)continue;const x=S.timestamp;if(g==="user"||g==="system"||g==="data"){c();const w=Kr(S.content).trim();if(!w)continue;n.push({id:a(g,x),role:g,parts:[{type:"text",text:w}],meta:{source:"history",status:"final",timestamp:x}});continue}if(g==="assistant"){const w=Kr(S.content).trim();if(w&&d(x,w),typeof S.reasoning_content=="string"&&S.reasoning_content.trim()&&p(x,S.reasoning_content.trim()),Array.isArray(S.tool_calls))for(const I of S.tool_calls){if(!I||typeof I!="object")continue;const R=I,v=R.function,N=typeof v=="object"&&v?v:null,P=typeof R.id=="string"?R.id.trim():"";if(!P)continue;const F=typeof(N==null?void 0:N.name)=="string"?N.name:typeof R.name=="string"?R.name:"tool",T=o((N==null?void 0:N.arguments)??R.arguments??"");f({timestamp:x,toolCallId:P,toolName:F,args:T.args,parsedArgs:T.parsedArgs})}continue}if(t.has(g)){const w=typeof S.tool_call_id=="string"?S.tool_call_id.trim():"",I=typeof S.name=="string"&&S.name.trim()?S.name.trim():"tool";m({timestamp:x,toolCallId:w,toolName:I,result:S.content})}}return c(),n}function Fx(){const e=Date.now().toString(36),t=Math.random().toString(36).slice(2,10);return`run-${e}-${t}`}function zx(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():"",l=typeof n.stopSupported=="boolean"?n.stopSupported:void 0,u=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 l=="boolean"?{stopSupported:l}:{},...u?{stopReason:u}:{}}}return null}function Bx(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 $x(e){var n;return e.mode!=="send"||((n=e.payload.runId)==null?void 0:n.trim())?e:{...e,payload:{...e.payload,runId:Fx()}}}function Ux(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 Kx(){return{deltaMessageId:Co(),deltaStarted:!1,deltaClosed:!1,hasAssistantSessionEvent:!1,hasAssistantOutput:!1}}function Hx(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 Vx(e,t){return{driver:"nextbot-stream",kind:"final",sessionKey:e.sessionKey,reply:e.reply,hasAssistantSessionEvent:t}}function ni(e,t,n){e({type:G.RUN_METADATA,runId:t,metadata:n})}function ri(e,t){!e.deltaStarted||e.deltaClosed||(t({type:G.TEXT_END,messageId:e.deltaMessageId}),e.deltaClosed=!0)}function qx(e,t,n){const r=Tx({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 Wx(e,t,n){Mx(n.data),Rx(n.data)&&(e.hasAssistantSessionEvent=!0);for(const r of Ax({event:n.data,messageId:e.deltaMessageId}))t(r)}function Gx(e,t,n){const r=n.trim();if(e.hasAssistantOutput||!r)return;const s=Co();t({type:G.TEXT_START,messageId:s}),t({type:G.TEXT_DELTA,messageId:s,delta:r}),t({type:G.TEXT_END,messageId:s})}class Qx{constructor(){this.activeAbortController=null,this.activeRunState=null,this.buildMissingMetadataObservable=t=>new Zt(n=>{n.next({type:G.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"?Lx({item:n.payload,requestedSkills:n.requestedSkills,signal:r,onReady:s,onDelta:i,onSessionEvent:a}):Nx({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 Zt(i=>{const a=Kx();let o=!1;const l=c=>{o||i.next(c)};return l({type:G.RUN_STARTED,runId:n}),this.openRunStream({metadata:t,signal:r.signal,onReady:c=>{this.activeRunState&&Ux(this.activeRunState,c),ni(l,n,Hx(c))},onDelta:c=>{qx(a,l,c)},onSessionEvent:c=>{Wx(a,l,c)}}).then(c=>{ri(a,l),Gx(a,l,c.reply),ni(l,n,Vx(c,a.hasAssistantSessionEvent)),l({type:G.RUN_FINISHED,runId:n}),i.complete()}).catch(c=>{ri(a,l),sr(c)||l({type:G.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&&Px(t),(n=this.activeAbortController)==null||n.abort(),this.activeAbortController=null,this.activeRunState=null},this.run=t=>{const n=zx(t),r=typeof t.runId=="string"&&t.runId.trim()?t.runId:`run-${Date.now()}`;if(!n)return this.buildMissingMetadataObservable(r);const s=$x(n);this.abortRun();const i=new AbortController;this.activeAbortController=i;const a=Bx(s);return this.activeRunState=a,this.createRunObservable({metadata:s,clientRunId:r,abortController:i,runState:a})}}}class Xx{constructor(){this.chatUiManager=new vo,this.runtimeAgent=new Qx,this.chatController=new Uy({agent:this.runtimeAgent,getToolDefs:()=>[],getContexts:()=>[],getToolExecutor:()=>{}},{metadataParsers:bx}),this.chatStreamActionsManager=new wo,this.chatInputManager=new xx(this.chatUiManager,this.chatStreamActionsManager),this.chatSessionListManager=new ko(this.chatUiManager,this.chatStreamActionsManager),this.chatRunStatusManager=new So,this.chatThreadManager=new Cx(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}}function Kt(e){const[t,n]=C.useState(e.getValue());return C.useEffect(()=>{const r=e.subscribe(n);return()=>r.unsubscribe()},[e]),t}function Yx(e,t){const[n,r]=C.useState(t);return C.useEffect(()=>{const s=e.subscribe(r);return()=>s.unsubscribe()},[e]),n}function Jx(e,t){const n=C.useRef(e);C.useEffect(()=>{n.current=e});const r=C.useRef(null);C.useEffect(()=>{t.setCallbacks({onRunSettled:async({sourceSessionId:g,resultSessionId:x})=>{const w=n.current;await w.refetchSessions();const I=w.selectedSessionKeyRef.current;(!I||I===g||x&&I===x)&&await w.refetchHistory()},onRunError:({sourceMessage:g,restoreDraft:x})=>{x&&n.current.setDraft(w=>w.trim().length===0&&g?g:w)},onSessionChanged:g=>{n.current.setSelectedSessionKey(x=>x===g?x:g)}})},[t]);const s=Yx(t.messages$,t.getMessages()),i=Kt(t.isAgentResponding$),a=Kt(t.isAwaitingResponse$),o=Kt(t.activeRun$),l=Kt(t.lastError$),u=(o==null?void 0:o.remoteRunId)??null,c=Oy(o),d=!!(o&&(c===null||o.remoteStopCapable&&!u)),p=C.useCallback(async g=>{const x=Io(g.requestedSkills),w=Sx(g,x);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=C.useCallback(async g=>{var R,v;const x=(R=g.runId)==null?void 0:R.trim(),w=(v=g.sessionKey)==null?void 0:v.trim();if(!x||!w)return;const I=kx(g);await t.resume({remoteRunId:x,sessionId:w,agentId:g.agentId,metadata:I,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),m=C.useCallback(async()=>{await t.stop()},[t]),y=C.useCallback(()=>{r.current=null,t.reset()},[t]),S=C.useCallback((g,x)=>{if(!!(t.activeRun$.getValue()||t.isAgentResponding$.getValue()))return;const I=n.current.selectedSessionKeyRef.current;if(I!==r.current&&(r.current=I,t.getMessages().length>0&&t.setMessages([])),!I){t.getMessages().length>0&&t.setMessages([]);return}x!=null&&x.isLoading&&g.length===0||t.setMessages(Ox(g))},[t]);return{uiMessages:s,isSending:i,isAwaitingAssistantOutput:a,canStopCurrentRun:d,stopDisabledReason:c,lastSendError:l,activeBackendRunId:u,sendMessage:p,stopCurrentRun:m,resumeRun:f,resetStreamState:y,applyHistoryMessages:S}}function Zx({view:e}){var Je,Ze,Ge;const[t]=C.useState(()=>new Xx),n=se(ce=>ce.snapshot.query),r=se(ce=>ce.snapshot.selectedSessionKey),s=se(ce=>ce.snapshot.selectedAgentId),i=K(ce=>ce.snapshot.pendingSessionType),{confirm:a,ConfirmDialog:o}=pr(),l=fr(),u=Ci(),{sessionId:c}=Ii(),d=C.useRef(null),p=C.useRef(r),f=C.useRef(null),m=C.useRef(null),y=C.useMemo(()=>xo(c),[c]),{sessionsQuery:S,installedSkillsQuery:g,chatCapabilitiesQuery:x,historyQuery:w,isProviderStateResolved:I,modelOptions:R,sessions:v,skillRecords:N,selectedSession:P,hydratedSessionModel:F,historyMessages:T,selectedSessionThinkingLevel:L,sessionTypeOptions:D,defaultSessionType:$,selectedSessionType:z,canEditSessionType:_,sessionTypeUnavailable:W,sessionTypeUnavailableMessage:ee}=bu({query:n,selectedSessionKey:r,selectedAgentId:s,pendingSessionType:i,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel}),{uiMessages:de,isSending:re,isAwaitingAssistantOutput:k,canStopCurrentRun:pe,stopDisabledReason:Se,lastSendError:b,activeBackendRunId:ae,sendMessage:ie,stopCurrentRun:te,resumeRun:Ne,resetStreamState:ke,applyHistoryMessages:Re}=Jx({selectedSessionKeyRef:p,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setDraft:t.chatInputManager.setDraft,setComposerNodes:t.chatInputManager.setComposerNodes,refetchSessions:S.refetch,refetchHistory:w.refetch},t.chatController);C.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:ie,stopCurrentRun:te,resumeRun:Ne,resetStreamState:ke,applyHistoryMessages:Re})},[Re,t,ke,Ne,ie,te]);const{sessionRunStatusByKey:he}=gu({view:e,selectedSessionKey:r,activeBackendRunId:ae,isLocallyRunning:re||!!ae,resumeRun:t.chatStreamActionsManager.resumeRun});go({view:e,routeSessionKey:y,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:p,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:yo}),C.useEffect(()=>{t.chatStreamActionsManager.applyHistoryMessages(T,{isLoading:w.isLoading})},[T,w.isLoading,t]),C.useEffect(()=>{t.chatUiManager.syncState({pathname:l.pathname}),t.chatUiManager.bindActions({navigate:u,confirm:a})},[a,l.pathname,u,t]);const _e=P?Fi(P):void 0,Ye=((Je=D.find(ce=>ce.value===z))==null?void 0:Je.label)??ht(z);return C.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:S.refetch})},[t,S.refetch]),C.useEffect(()=>{var ye,Ae;const ce=!re&&!k&&!S.isLoading&&I&&R.length>0&&r!==f.current,V=!re&&!k&&!w.isLoading&&I&&R.length>0&&r!==m.current;t.chatInputManager.syncSnapshot({isProviderStateResolved:I,defaultSessionType:$,canStopGeneration:pe,stopDisabledReason:Se,stopSupported:((ye=x.data)==null?void 0:ye.stopSupported)??!1,stopReason:(Ae=x.data)==null?void 0:Ae.stopReason,sendError:b,isSending:re,modelOptions:R,...ce?{selectedModel:F}:{},sessionTypeOptions:D,selectedSessionType:z,...V?{selectedThinkingLevel:L}:{},canEditSessionType:_,sessionTypeUnavailable:W,skillRecords:N,isSkillsLoading:g.isLoading}),ce&&(f.current=r),V&&(m.current=r),r||(f.current=null,m.current=null),t.chatSessionListManager.syncSnapshot({sessions:v,query:n,isLoading:S.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:he,isLocallyRunning:re||!!ae,activeBackendRunId:ae}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:I,modelOptions:R,sessionTypeUnavailable:W,sessionTypeUnavailableMessage:ee,sessionTypeLabel:Ye,selectedSessionKey:r,sessionDisplayName:_e,canDeleteSession:!!P,threadRef:d,isHistoryLoading:w.isLoading,uiMessages:de,isSending:re,isAwaitingAssistantOutput:k})},[ae,_,pe,_e,Ye,(Ze=x.data)==null?void 0:Ze.stopReason,(Ge=x.data)==null?void 0:Ge.stopSupported,$,w.isLoading,g.isLoading,k,F,I,re,b,R.length,R,t,n,P,r,L,z,he,D,W,ee,v,S.isLoading,N,Se,d,de]),h.jsx(Bi,{presenter:t,children:h.jsx(mo,{view:e,confirmDialog:h.jsx(o,{})})})}var ne=(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))(ne||{}),si=/\[\[\s*reply_to_current\s*\]\]/gi,ii=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function ar(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function eb(e,t){var i;let n=e,r;si.test(n)&&(r=ar(t),n=n.replace(si,"").trim());const s=(i=n.match(ii))==null?void 0:i[1];return s&&(r=ar(s),n=n.replace(ii,"").trim()),r?{content:n,replyTo:r}:{content:n}}function tb(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=ar(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}=eb(i.text,t),l=o??s,u=e.parts.flatMap((c,d)=>d!==n||c.type!=="text"?[c]:a.length===0?[]:[{...c,text:a}]);return l?{...e,parts:u,metadata:{...r,reply_to:l}}:{...e,parts:u,metadata:r}}function ai(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(`
38
+ `)}}async function*nb(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:l}=oi(r);r=l;for(const u of o)yield u}r+=n.decode();const{frames:s}=oi(r,!0);for(const i of s)yield i}finally{t.releaseLock()}}function oi(e,t=!1){const n=e.split(/\r?\n\r?\n/),r=n.pop()??"",s=[];for(const i of n){const a=ai(i);a&&s.push(a)}if(t&&r.trim()){const i=ai(r);return i&&s.push(i),{frames:s,rest:""}}return{frames:s,rest:r}}var li="/ncp/agent",rb="ncp-http-agent-client",To=class extends Error{constructor(t,n=!1){super(t.message);O(this,"ncpError");O(this,"alreadyPublished");this.name=`NcpHttpAgentClientError(${t.code})`,this.ncpError=t,this.alreadyPublished=n}};function sb(e){const t=e.trim();if(!t)throw new Error("NcpHttpAgentClient requires a non-empty baseUrl.");return new URL(t)}function ib(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 ab(e){const t=(e??li).trim();if(!t)return li;const n=t.startsWith("/")?t:`/${t}`;return n.endsWith("/")?n.slice(0,-1):n}async function ui(e){try{return(await e.text()).trim()}catch{return""}}function ci(e){if(Mo(e))return e.ncpError;if(ob(e))return e;const t=e instanceof Error?e.message:String(e??"Unknown error");return{code:Ro(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function Pn(e,t={}){return new To(e,t.alreadyPublished??!1)}function ob(e){return Or(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Or(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Mo(e){return e instanceof To}var lb={"config-error":"config-error","auth-error":"auth-error","runtime-error":"runtime-error","timeout-error":"timeout-error","abort-error":"abort-error"};function Ro(e){if(!e)return"runtime-error";const t=lb[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 ub(e){const t=Ao(e);return!t||typeof t.type!="string"||!t.type.trim()?null:t}function cb(e){const t=Ao(e);if(!t)return{code:"runtime-error",message:e||"Unknown stream error."};const n=typeof t.code=="string"?t.code:void 0,r=Ro(n),s=Or(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 Ao(e){try{const t=JSON.parse(e);return Or(t)?t:null}catch{return null}}var db=["text","file","source","step-start","reasoning","tool-invocation","card","rich-text","action","extension"],hb=class{constructor(e){O(this,"manifest");O(this,"baseUrl");O(this,"basePath");O(this,"fetchImpl");O(this,"defaultHeaders");O(this,"subscribers",new Set);O(this,"activeControllers",new Set);O(this,"started",!1);var t;this.baseUrl=sb(e.baseUrl),this.basePath=ab(e.basePath),this.fetchImpl=ib(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:"custom",endpointId:((t=e.endpointId)==null?void 0:t.trim())||rb,version:"0.1.0",supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:db,expectedLatency:"seconds",metadata:{transport:"http+sse",scope:"agent"}}}async start(){this.started||(this.started=!0,this.publish({type:ne.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 ui(n)}`)}catch(n){if(t.signal.aborted)return;const r=ci(n);throw this.publish({type:ne.EndpointError,payload:r}),Pn(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 ui(n)}`);if(!n.body)throw new Error("NCP stream response has no body.");for await(const r of nb(n.body)){if(t.signal.aborted)return;this.handleSseFrame(r)}}catch(n){if(t.signal.aborted)return;if(Mo(n))throw n;const r=ci(n);throw this.publish({type:ne.EndpointError,payload:r}),Pn(r)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event==="ncp-event"){const t=ub(e.data);if(!t){this.publish({type:ne.EndpointError,payload:{code:"runtime-error",message:"Received malformed ncp-event frame."}});return}this.publish(t);return}if(e.event==="error"){const t=cb(e.data);throw this.publish({type:ne.EndpointError,payload:t}),Pn(t,{alreadyPublished:!0})}}};function Gt(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function jn(e){return Gt(tb(e))}function fb(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}}}function pb(e,t){return t.trim()?e.id.startsWith("tool-")?!0:e.parts.some(n=>n.type==="tool-invocation"):!1}function gb(e,t,n){for(const[r,s]of e)s===t&&e.set(r,n)}function Ht(e,t,n){for(const[r,s]of e)s===n&&(e.delete(r),t.delete(r))}function or(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}function di(e,t){const n=or(e,t);return(n==null?void 0:n.toolName)??null}function vt(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}var mb="assistant",yb=class{constructor(){O(this,"messages",[]);O(this,"streamingMessage",null);O(this,"error",null);O(this,"activeRun",null);O(this,"listeners",new Set);O(this,"toolCallMessageIdByCallId",new Map);O(this,"toolCallArgsRawByCallId",new Map);O(this,"snapshotCache",null);O(this,"snapshotVersion",-1);O(this,"stateVersion",0)}getSnapshot(){if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;const e={messages:this.messages.map(t=>Gt(t)),streamingMessage:this.streamingMessage?Gt(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=>jn(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 ne.MessageSent:this.handleMessageSent(e.payload);break;case ne.MessageAbort:this.handleMessageAbort(e.payload);break;case ne.MessageTextStart:this.handleMessageTextStart(e.payload);break;case ne.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case ne.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case ne.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case ne.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case ne.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case ne.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case ne.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case ne.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case ne.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case ne.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case ne.RunStarted:this.handleRunStarted(e.payload);break;case ne.RunFinished:this.handleRunFinished(e.payload);break;case ne.RunError:this.handleRunError(e.payload);break;case ne.RunMetadata:this.handleRunMetadata(e.payload);break;case ne.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?Ht(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):Ht(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,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=vt(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=vt(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:di(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 vt(n.parts,s)})){const n=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),r=vt(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),Ht(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)}this.setError(null),this.clearActiveRun()}handleRunError(e){if(this.streamingMessage){const t={...this.streamingMessage,status:"error"};this.upsertMessage(t),this.replaceStreamingMessage(null),Ht(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)}this.setError(fb(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=di(s.parts,t)??"unknown",a=vt(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 a;if(((a=this.streamingMessage)==null?void 0:a.id)===t){if(this.streamingMessage.status===n)return this.streamingMessage;const o={...this.streamingMessage,status:n};return this.replaceStreamingMessage(o),o}const r=this.messages.findIndex(o=>o.id===t);if(r>=0){const o=Gt(this.messages[r]),l=[...this.messages];l.splice(r,1),this.messages=l,this.stateVersion+=1;const u={...o,sessionId:e,status:n};return this.replaceStreamingMessage(u),u}const s=this.streamingMessage;if(s&&s.id!==t&&s.sessionId===e&&pb(s,t)){const o={...s,id:t,sessionId:e,status:n};return gb(this.toolCallMessageIdByCallId,s.id,t),this.replaceStreamingMessage(o),o}const i={id:t,sessionId:e,role:mb,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(i),i}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=or(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=or(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}upsertMessage(e){const t=jn(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?jn(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)}notifyListeners(){const e=this.getSnapshot();for(const t of this.listeners)t(e)}};function xb(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 bb(e){return e.parts.some(t=>t.type==="text"||t.type==="rich-text"||t.type==="reasoning"?t.text.trim().length>0:!0)}function Sb(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 bb(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function kb(e,t){return{sessionId:e,messages:t.messages,activeRun:t.activeRun}}function wb(e){const t=C.useRef();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new yb}),t.current.manager}function vb({sessionId:e,client:t,manager:n}){var p;const r=C.useSyncExternalStore(f=>n.subscribe(()=>f()),()=>n.getSnapshot(),()=>n.getSnapshot()),[s,i]=C.useState(!1);C.useEffect(()=>{i(!1)},[e]),C.useEffect(()=>{const f=t.subscribe(m=>{xb(m,e)&&n.dispatch(m)});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,l=!!r.activeRun;return{snapshot:r,visibleMessages:a,activeRunId:o,isRunning:l,isSending:s,send:async f=>{if(s||l)return;const m=Sb(f,e);if(!m)return;i(!0);const y=n.getSnapshot();await n.dispatch({type:ne.MessageSent,payload:{sessionId:e,message:m.message,metadata:m.metadata}});try{await t.send(m)}catch(S){throw n.hydrate(kb(e,y)),S}finally{i(!1)}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{r.activeRun&&await t.stream({sessionId:e})}}}function hi(e){return e instanceof Error?e:new Error(String(e))}function Cb({sessionId:e,client:t,loadSeed:n,autoResumeRunningSession:r=!0}){const s=wb(e),i=vb({sessionId:e,client:t,manager:s}),[a,o]=C.useState(!0),[l,u]=C.useState(null),c=C.useRef({requestId:0,controller:null}),d=C.useCallback(async()=>{var m;(m=c.current.controller)==null||m.abort();const p=new AbortController,f=c.current.requestId+1;c.current={requestId:f,controller:p},await t.stop(),s.reset(),u(null),o(!0);try{const y=await n(e,p.signal);if(p.signal.aborted||c.current.requestId!==f)return;s.hydrate({sessionId:e,messages:y.messages,activeRun:y.status==="running"?{runId:null,sessionId:e,abortDisabledReason:null}:null}),u(null),o(!1),y.status==="running"&&r&&t.stream({sessionId:e}).catch(S=>{c.current.requestId===f&&u(hi(S))})}catch(y){if(p.signal.aborted||c.current.requestId!==f)return;u(hi(y)),o(!1)}finally{c.current.controller===p&&(c.current.controller=null)}},[r,t,n,s,e]);return C.useEffect(()=>(d(),()=>{var p;(p=c.current.controller)==null||p.abort(),c.current.controller=null}),[d]),{...i,isHydrating:a,hydrateError:l,reloadSeed:d}}const Ib=new Set(["off","minimal","low","medium","high","adaptive","xhigh"]);function Tb(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return String(e??"")}}function je(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function cn(e){const{metadata:t}=e;return!t||typeof t!="object"||Array.isArray(t)?null:t}function Mb(e){const t=cn(e);return t?je(t.preferred_model)??je(t.preferredModel)??je(t.model):null}function Rb(e){const t=cn(e);if(!t)return null;const n=je(t.preferred_thinking)??je(t.thinking)??je(t.thinking_level)??je(t.thinkingLevel);if(!n)return null;const r=n.toLowerCase();return Ib.has(r)?r:null}function Ab(e){const t=cn(e);return t?je(t.label):null}function Eb(e){const t=cn(e);return t?je(t.session_type)??je(t.sessionType)??"native":"native"}function Lb(e){return e.state==="result"?le.RESULT:e.state==="partial-call"?le.PARTIAL_CALL:le.CALL}function Nb(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:Lb(n),toolCallId:n.toolCallId??`${n.toolName}-${Math.random().toString(36).slice(2,8)}`,toolName:n.toolName,args:Tb(n.args),result:n.result}})}return t}function Pb(e){return e==="service"?"system":e==="tool"?"assistant":e}function jb(e){return{id:e.id,role:Pb(e.role),parts:Nb(e.parts),meta:{source:"stream",status:e.status,sessionKey:e.sessionId,timestamp:e.timestamp}}}function Db(e){return console.log("[adaptNcpMessagesToUiMessages]",{messages:e}),e.map(jb)}function _b(e){const t=Ab(e),n=Mb(e);return{key:e.sessionId,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{label:t}:{},...n?{preferredModel:n}:{},sessionType:Eb(e),sessionTypeMutable:!1,messageCount:e.messageCount}}function Ob(e){return e.map(_b)}function Fb(e){const t=new Map;for(const r of e.summaries)r.status==="running"&&t.set(r.sessionId,"running");const n=je(e.activeSessionId);return e.isLocallyRunning&&n&&t.set(n,"running"),t}function fi(){return`ncp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function zb(){return yl({queryKey:["ncp-session-types"],queryFn:zl,staleTime:1e4,retry:!1})}function Bb(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>r.key.toLowerCase().includes(n)):e}function $b(e){var x,w,I,R;const t=Ti(),n=Mi(),r=Bl({limit:200}),s=zb(),i=Ai("skill"),a=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),o=C.useMemo(()=>{const v=Li({meta:n.data,config:t.data,onlyConfigured:!0}),N=new Set,P=[];for(const F of v)for(const T of F.models){const L=Ni(F.prefix,T);!L||N.has(L)||(N.add(L),P.push({value:L,modelLabel:T,providerLabel:F.displayName,thinkingCapability:Pi(F.modelThinking,T,F.aliases)}))}return P.sort((F,T)=>{const L=F.providerLabel.localeCompare(T.providerLabel);return L!==0?L:F.modelLabel.localeCompare(T.modelLabel)})},[n.data,t.data]),l=C.useMemo(()=>{var v;return((v=r.data)==null?void 0:v.sessions)??[]},[(x=r.data)==null?void 0:x.sessions]),u=C.useMemo(()=>Ob(l),[l]),c=C.useMemo(()=>Bb(u,e.query),[u,e.query]),d=C.useMemo(()=>u.find(v=>v.key===e.selectedSessionKey)??null,[u,e.selectedSessionKey]),p=C.useMemo(()=>l.find(v=>v.sessionId===e.selectedSessionKey)??null,[e.selectedSessionKey,l]),f=C.useMemo(()=>{var v;return((v=i.data)==null?void 0:v.records)??[]},[(w=i.data)==null?void 0:w.records]),m=C.useMemo(()=>p?Rb(p):null,[p]),y=Oi({selectedSession:d,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:s.data}),S=C.useMemo(()=>Di({sessions:u,selectedSessionKey:e.selectedSessionKey,sessionType:y.selectedSessionType}),[u,e.selectedSessionKey,y.selectedSessionType]);_i({modelOptions:o,selectedSessionKey:e.selectedSessionKey,selectedSessionPreferredModel:d==null?void 0:d.preferredModel,fallbackPreferredModel:S,defaultModel:(I=t.data)==null?void 0:I.agents.defaults.model,setSelectedModel:e.setSelectedModel});const g=C.useMemo(()=>{var v;return mr({currentSelectedModel:"",modelOptions:o,selectedSessionPreferredModel:d==null?void 0:d.preferredModel,fallbackPreferredModel:S,defaultModel:(v=t.data)==null?void 0:v.agents.defaults.model,preferSessionPreferredModel:!0})},[(R=t.data)==null?void 0:R.agents.defaults.model,o,S,d==null?void 0:d.preferredModel]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,sessionTypesQuery:s,installedSkillsQuery:i,isProviderStateResolved:a,modelOptions:o,sessionSummaries:l,sessions:c,skillRecords:f,selectedSession:d,hydratedSessionModel:g,selectedSessionThinkingLevel:m,...y}}class Ub{constructor(t,n,r){this.uiManager=t,this.streamActionsManager=n,this.getDraftSessionId=r,this.sessionPreferenceSync=new bo($l),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.syncComposerSnapshot=s=>{K.getState().setSnapshot({composerNodes:s,draft:lo(s),selectedSkills:uo(s)})},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&&this.syncComposerSnapshot(oo(a))},this.setComposerNodes=s=>{const i=K.getState().snapshot.composerNodes,a=this.resolveUpdateValue(i,s);Object.is(a,i)||this.syncComposerSnapshot(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=se.getState().snapshot,a=s.draft.trim();if(!a)return;const o=s.selectedSkills,l=s.composerNodes,u=i.selectedSessionKey??this.getDraftSessionId();i.selectedSessionKey||this.uiManager.goToSession(u,{replace:!0}),this.setComposerNodes(_r()),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,composerNodes:l})},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=He(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.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=s=>{this.setSelectedThinkingLevel(s),this.sessionPreferenceSync.syncSelectedSessionPreferences()},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 Kb=async()=>{};class Hb{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:Kb},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=Ve.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)&&Ve.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=se.getState();if(!(!s||!await this.uiManager.confirm({title:A("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:A("delete")}))){Ve.getState().setSnapshot({isDeletePending:!0});try{await Ul(s),this.streamActionsManager.resetStreamState(),se.getState().setSnapshot({selectedSessionKey:null}),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{Ve.getState().setSnapshot({isDeletePending:!1})}}}}}class Vb{constructor(){this.chatUiManager=new vo,this.chatStreamActionsManager=new wo,this.chatSessionListManager=new ko(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new Ub(this.chatUiManager,this.chatStreamActionsManager,()=>this.getDraftSessionId()),this.chatRunStatusManager=new So,this.chatThreadManager=new Hb(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager),this.draftSessionId="",this.setDraftSessionId=t=>{this.draftSessionId=t}}getDraftSessionId(){return this.draftSessionId}}function qb(){return(e,t)=>fetch(e,{credentials:"include",...t})}function Wb(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=Io(e.requestedSkills);return n.length>0&&(t.requested_skills=n),t}function Gb(e){return e instanceof Error?e.message.includes("ncp session not found:"):!1}function Qb({view:e}){var Ze,Ge,ce;const[t]=C.useState(()=>new Vb),[n,r]=C.useState(()=>fi()),s=se(V=>V.snapshot.query),i=se(V=>V.snapshot.selectedSessionKey),a=se(V=>V.snapshot.selectedAgentId),o=K(V=>V.snapshot.pendingSessionType),{confirm:l,ConfirmDialog:u}=pr(),c=fr(),d=Ci(),{sessionId:p}=Ii(),f=C.useRef(null),m=C.useRef(i),y=C.useRef(null),S=C.useRef(null),g=C.useMemo(()=>xo(p),[p]),{sessionsQuery:x,installedSkillsQuery:w,isProviderStateResolved:I,modelOptions:R,sessionSummaries:v,sessions:N,skillRecords:P,selectedSession:F,hydratedSessionModel:T,selectedSessionThinkingLevel:L,sessionTypeOptions:D,defaultSessionType:$,selectedSessionType:z,canEditSessionType:_,sessionTypeUnavailable:W,sessionTypeUnavailableMessage:ee}=$b({query:s,selectedSessionKey:i,pendingSessionType:o,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel}),de=x.refetch,re=i??n,k=C.useRef(v);C.useEffect(()=>{k.current=v},[v]);const[pe]=C.useState(()=>new hb({baseUrl:Kl,basePath:"/api/ncp/agent",fetchImpl:qb()})),Se=C.useCallback(async(V,ye)=>{ye.throwIfAborted();let Ae=null;try{Ae=await Hl(V,300)}catch(Be){if(!Gb(Be))throw Be}ye.throwIfAborted();const xe=k.current.find(Be=>Be.sessionId===V)??null;return{messages:(Ae==null?void 0:Ae.messages)??[],status:(xe==null?void 0:xe.status)==="running"?"running":"idle"}},[]),b=Cb({sessionId:re,client:pe,loadSeed:Se});C.useEffect(()=>{t.setDraftSessionId(n)},[n,t]),C.useEffect(()=>{if(i===null){const V=fi();r(V),t.setDraftSessionId(V)}},[t,i]);const ae=C.useMemo(()=>Db(b.visibleMessages),[b.visibleMessages]),ie=b.isSending||b.isRunning,te=b.isRunning,Ne=b.isRunning,ke=b.isRunning?null:"__preparing__",Re=((Ze=b.hydrateError)==null?void 0:Ze.message)??((Ge=b.snapshot.error)==null?void 0:Ge.message)??null,he=b.activeRunId,_e=C.useMemo(()=>Fb({summaries:v,activeSessionId:re,isLocallyRunning:ie||!!he}),[he,re,ie,v]);C.useEffect(()=>{!ie&&!he||de()},[he,ie,de]),C.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:async V=>{if(V.sessionKey!==re)return;const ye=Wb({model:V.model,thinkingLevel:V.thinkingLevel,sessionType:V.sessionType,requestedSkills:V.requestedSkills});try{x.refetch(),await b.send({sessionId:V.sessionKey,message:{id:`user-${Date.now().toString(36)}`,sessionId:V.sessionKey,role:"user",status:"final",parts:[{type:"text",text:V.message}],timestamp:new Date().toISOString(),...Object.keys(ye).length>0?{metadata:ye}:{}},...Object.keys(ye).length>0?{metadata:ye}:{}}),await x.refetch()}catch(Ae){throw V.restoreDraftOnError&&(V.composerNodes&&V.composerNodes.length>0?t.chatInputManager.setComposerNodes(xe=>{var Be;return xe.length===1&&((Be=xe[0])==null?void 0:Be.type)==="text"&&xe[0].text.length===0?V.composerNodes??xe:xe}):t.chatInputManager.setDraft(xe=>xe.trim().length===0?V.message:xe)),Ae}},stopCurrentRun:async()=>{await b.abort(),await x.refetch()},resumeRun:async V=>{V.sessionKey===re&&await b.streamRun()},resetStreamState:()=>{m.current=null},applyHistoryMessages:()=>{}})},[re,b,t,x]),go({view:e,routeSessionKey:g,selectedSessionKey:i,selectedAgentId:a,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:m,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:yo}),C.useEffect(()=>{t.chatUiManager.syncState({pathname:c.pathname}),t.chatUiManager.bindActions({navigate:d,confirm:l})},[l,c.pathname,d,t]);const Ye=F?Fi(F):void 0,Je=((ce=D.find(V=>V.value===z))==null?void 0:ce.label)??ht(z);return C.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:x.refetch})},[t,x.refetch]),C.useEffect(()=>{const V=!ie&&!te&&!x.isLoading&&I&&R.length>0&&i!==y.current,ye=!ie&&!te&&!b.isHydrating&&I&&R.length>0&&i!==S.current;t.chatInputManager.syncSnapshot({isProviderStateResolved:I,defaultSessionType:$,canStopGeneration:Ne,stopDisabledReason:ke,stopSupported:!0,stopReason:void 0,sendError:Re,isSending:ie,modelOptions:R,...V?{selectedModel:T}:{},sessionTypeOptions:D,selectedSessionType:z,...ye?{selectedThinkingLevel:L}:{},canEditSessionType:_,sessionTypeUnavailable:W,skillRecords:P,isSkillsLoading:w.isLoading}),V&&(y.current=i),ye&&(S.current=i),i||(y.current=null,S.current=null),t.chatSessionListManager.syncSnapshot({sessions:N,query:s,isLoading:x.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:_e,isLocallyRunning:ie||!!he,activeBackendRunId:he}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:I,modelOptions:R,sessionTypeUnavailable:W,sessionTypeUnavailableMessage:ee,sessionTypeLabel:Je,selectedSessionKey:i,sessionDisplayName:Ye,canDeleteSession:!!F,threadRef:f,isHistoryLoading:b.isHydrating,uiMessages:ae,isSending:ie,isAwaitingAssistantOutput:te})},[he,b.isHydrating,_,Ne,Ye,Je,$,w.isLoading,te,T,I,ie,Re,R.length,R,t,s,F,i,L,z,_e,D,W,ee,N,x.isLoading,P,ke,f,ae]),h.jsx(Bi,{presenter:t,children:h.jsx(mo,{view:e,confirmDialog:h.jsx(u,{})})})}function lS({view:e}){const t=fr();return pu(t.search)==="ncp"?h.jsx(Qb,{view:e}):h.jsx(Zx,{view:e})}export{lS as ChatPage};