@nextclaw/ui 0.10.4 → 0.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/assets/{ChannelsList-ohaw9GpD.js → ChannelsList-Nu7Ig6_-.js} +1 -1
- package/dist/assets/{ChatPage-BqFTFaut.js → ChatPage-CBCFSk4e.js} +24 -24
- package/dist/assets/{DocBrowser-Cm8LqQ8S.js → DocBrowser-3CfKmJA6.js} +1 -1
- package/dist/assets/{LogoBadge-GTNIKJO9.js → LogoBadge-DdthDJOp.js} +1 -1
- package/dist/assets/{MarketplacePage-CfSXSQFi.js → MarketplacePage-inGGiv1T.js} +1 -1
- package/dist/assets/{McpMarketplacePage-BRJudD8Z.js → McpMarketplacePage-Dg8GSZh6.js} +1 -1
- package/dist/assets/{ModelConfig-B-P04UNK.js → ModelConfig-DyQ6cC92.js} +1 -1
- package/dist/assets/{ProvidersList-D9IocmDB.js → ProvidersList-B2T8Lc_i.js} +1 -1
- package/dist/assets/{RemoteAccessPage-58fYdCYK.js → RemoteAccessPage-C9LxgK-C.js} +1 -1
- package/dist/assets/{RuntimeConfig-C5NlEc57.js → RuntimeConfig-Ey4VIqTW.js} +1 -1
- package/dist/assets/{SearchConfig-Cw17ED0n.js → SearchConfig-R1BcCLWO.js} +1 -1
- package/dist/assets/{SecretsConfig-DliEIjCS.js → SecretsConfig-D-jZMHeY.js} +2 -2
- package/dist/assets/{SessionsConfig-BRqvuKqq.js → SessionsConfig-Cawoh4_2.js} +1 -1
- package/dist/assets/{chat-message-C6dxqsRj.js → chat-message-BbuIK4dQ.js} +1 -1
- package/dist/assets/index-BulnQWr6.js +8 -0
- package/dist/assets/{label-B3FlNUAA.js → label-C7yzBvzK.js} +1 -1
- package/dist/assets/{page-layout-HrT1hpq7.js → page-layout-DF0xpax2.js} +1 -1
- package/dist/assets/{popover-BEo9XeN-.js → popover-DjaScZDJ.js} +1 -1
- package/dist/assets/{security-config-BRE-9ipr.js → security-config-Bg2eriNx.js} +1 -1
- package/dist/assets/{skeleton-BeC_fgbu.js → skeleton-DycBJAJF.js} +1 -1
- package/dist/assets/{status-dot-D9tZgJWo.js → status-dot-B9opOZ22.js} +1 -1
- package/dist/assets/{switch-Cq7y46-d.js → switch-l1P0ev4D.js} +1 -1
- package/dist/assets/{tabs-custom-xrIDQNF2.js → tabs-custom-BG9y2JhC.js} +1 -1
- package/dist/assets/{useConfirmDialog-DCZbJzHW.js → useConfirmDialog-DTducNfn.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +6 -6
- package/src/api/ncp-attachments.ts +41 -0
- package/src/api/types.ts +13 -0
- package/src/components/chat/adapters/chat-message.adapter.test.ts +27 -0
- package/src/components/chat/adapters/chat-message.adapter.ts +5 -1
- package/src/components/chat/chat-composer-state.test.ts +33 -0
- package/src/components/chat/chat-composer-state.ts +3 -1
- package/src/components/chat/containers/chat-input-bar.container.tsx +9 -8
- package/src/components/chat/ncp/ncp-chat-input.manager.ts +3 -1
- package/src/components/chat/ncp/ncp-session-adapter.test.ts +3 -1
- package/src/components/chat/ncp/ncp-session-adapter.ts +15 -1
- package/src/lib/i18n.chat.ts +7 -7
- package/dist/assets/index-B3caHNCU.js +0 -8
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
var Ha=Object.defineProperty;var qa=(e,t,n)=>t in e?Ha(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var F=(e,t,n)=>qa(e,typeof t!="symbol"?t+"":t,n);import{r as k,j as h,ae as Wa,v as Jt,X as Ga,af as Qa,f as Xa,e as kt,t as Ya,c as Ja,y as Za,z as el,h as yi,I as tl,i as ur,n as nl,o as xi,V as rl,q as bi,s as sl,w as il,k as Si,l as ol,m as ki,a as al,ag as ll,B as cr,G as dr,ah as ul,ai as cl,aj as dl,F as hl,ak as fl,al as pl,_ as vi,am as wi,an as Ci,ao as gl,ap as ml,aq as yl,ar as xl,as as bl,at as Sl,d as Zt,a4 as en,au as kl,A as hr,av as vl,a0 as wl,a3 as Cl,a1 as Tl,a2 as Il,aw as On,ax as Fn,ay as zn,az as At,M as Ml,aA as Ti,aB as Rl,aC as Al,aD as El,aE as Ii,aF as Mi,u as Ll}from"./vendor-CNhxtHCf.js";import{u as fr}from"./useConfirmDialog-DCZbJzHW.js";import{i as Nl,t as I,u as Ri,a as Ai,j as Pl,k as jl,l as Dl,m as _l,c as Le,I as pr,B as Ve,n as tn,o as Ei,p as Bn,q as Ol,r as Fl,s as gr,v as zl,T as Br,L as $r,w as Bl,x as Kr,y as $l,z as Ur,h as vt,A as Kl,E as Ul,F as Vl,G as Hl,S as ql,e as Wl,f as Gl,g as Ql,C as Xl,H as Yl,J as Jl,K as Li,M as Zl,N as eu,O as tu,P as nu,Q as ru,R as su,U as iu}from"./index-B3caHNCU.js";import{b as ou,a as au,S as lu,s as uu,c as Vr,e as Hr}from"./chat-message-C6dxqsRj.js";import{u as Ni,T as cu,a as du,b as hu,c as fu,P as pu,R as gu,d as mu,e as yu,C as Pi,M as xu}from"./MarketplacePage-CfSXSQFi.js";import{b as ji,c as Di,r as _i}from"./provider-models-BOeNnjk9.js";import{R as bu,A as Su,P as ku,C as Oi,T as vu,a as wu,b as Cu,c as Tu}from"./popover-BEo9XeN-.js";import{P as Iu,a as Mu}from"./page-layout-HrT1hpq7.js";import"./tabs-custom-xrIDQNF2.js";import"./skeleton-BeC_fgbu.js";import"./marketplace-localization-Dk31LJJJ.js";const Ru="ncp";function qr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="legacy"||t==="ncp"?t:null}function Fi(e){const t=qr(new URLSearchParams(e).get("chatChain"));return t||(qr(void 0)??Ru)}function Au(e){var v;const{view:t,selectedSessionKey:n,activeBackendRunId:r,isLocallyRunning:s,resumeRun:i}=e,[o,a]=k.useState(null),l=k.useRef(!1),u=k.useRef(new Map),c=k.useRef(new Map),d=k.useRef(new Map),p=k.useRef(r),f=k.useRef(new Set);k.useEffect(()=>{n&&f.current.add(n)},[n]),k.useEffect(()=>{n&&s&&f.current.delete(n)},[s,n]);const y=Nl(t==="chat"?{states:["queued","running"],limit:200,syncActiveStates:!0,isLocallyRunning:s}:void 0),m=k.useMemo(()=>{var w;return ou(((w=y.data)==null?void 0:w.runs)??[])},[(v=y.data)==null?void 0:v.runs]),b=k.useMemo(()=>{const w=au(m);if(o){const N=m.get(o.sessionKey)??null;N&&(!o.runId||N.runId===o.runId)&&w.delete(o.sessionKey)}return w},[m,o]),g=k.useMemo(()=>{if(!n)return null;const w=m.get(n)??null;return(!w||!o||o.sessionKey!==n?!1:!o.runId||w.runId===o.runId)?null:w},[m,n,o]);return k.useEffect(()=>{r&&(p.current=r)},[r]),k.useEffect(()=>{if(t!=="chat"||!n||!g||!f.current.has(n)||s||r===g.runId||u.current.get(n)===g.runId)return;const N=c.current.get(n);if(N&&N===g.runId)return;const j=d.current.get(n);if(typeof j=="number"){const T=Date.parse(g.requestedAt??"");if(Number.isFinite(T)){if(T<=j+2e3)return}else if(Date.now()-j<=8e3)return}u.current.set(n,g.runId),f.current.delete(n),i(g)},[r,g,s,i,n,t]),k.useEffect(()=>{if(!n){u.current.clear(),c.current.clear(),d.current.clear(),f.current.clear();return}m.has(n)||(u.current.delete(n),c.current.delete(n),d.current.delete(n))},[m,n]),k.useEffect(()=>{var N,j,T;const w=l.current;if(l.current=s,!s&&w&&n){const O=((N=p.current)==null?void 0:N.trim())||((T=(j=m.get(n))==null?void 0:j.runId)==null?void 0:T.trim());O&&c.current.set(n,O),d.current.set(n,Date.now()),a({sessionKey:n,...O?{runId:O}:{}}),y.refetch()}},[m,s,n,y]),k.useEffect(()=>{if(!o)return;const w=m.get(o.sessionKey)??null;if(!w){a(null);return}o.runId&&w.runId!==o.runId&&a(null)},[m,o]),k.useEffect(()=>{s&&(o==null?void 0:o.sessionKey)===n&&a(null)},[s,n,o]),{sessionRunStatusByKey:b}}const Me="native";function Oe(e){return typeof e!="string"?Me:e.trim().toLowerCase()||Me}function lt(e,t){return e==="native"?I("chatSessionTypeNative"):e.trim().split(/[-_]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")||e}function Eu(e){var n;const t=new Map;for(const r of e){const s=Oe(r.value);t.set(s,{value:s,label:((n=r.label)==null?void 0:n.trim())||lt(s),ready:r.ready??!0,reason:r.reason??null,reasonMessage:r.reasonMessage??null,supportedModels:r.supportedModels,recommendedModel:r.recommendedModel??null,cta:r.cta??null})}return t.has(Me)||t.set(Me,{value:Me,label:lt(Me),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((r,s)=>r.value===Me?-1:s.value===Me?1:r.value.localeCompare(s.value))}function zi(e){const{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:s,sessionTypesData:i}=e,o=k.useMemo(()=>Eu((i==null?void 0:i.options)??[]),[i==null?void 0:i.options]),a=k.useMemo(()=>{const b=[...o],g=Oe(t==null?void 0:t.sessionType);return b.some(v=>v.value===g)||b.push({value:g,label:lt(g),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),b.sort((v,w)=>v.value===Me?-1:w.value===Me?1:v.value.localeCompare(w.value))},[o,t==null?void 0:t.sessionType]),l=k.useMemo(()=>Oe((i==null?void 0:i.defaultType)??Me),[i==null?void 0:i.defaultType]),u=k.useRef(null),c=k.useMemo(()=>Oe((t==null?void 0:t.sessionType)??r??l),[l,r,t==null?void 0:t.sessionType]),d=k.useMemo(()=>a.find(b=>b.value===c)??null,[c,a]);k.useEffect(()=>{if(n)return;const b=typeof r=="string"?r.trim():"",g=Oe(r);(b.length===0||u.current===g||u.current===null&&g===Me)&&(u.current=l,g!==l&&s(l))},[l,r,n,s]);const p=!n||!!(t!=null&&t.sessionTypeMutable),f=k.useMemo(()=>new Set(o.map(b=>b.value)),[o]),y=k.useMemo(()=>t&&!f.has(Oe(t.sessionType))?!0:(d==null?void 0:d.ready)===!1,[f,t,d==null?void 0:d.ready]),m=k.useMemo(()=>{var b;return t&&!f.has(Oe(t.sessionType))?`${lt(c)} ${I("chatSessionTypeUnavailableSuffix")}`:(d==null?void 0:d.ready)===!1?((b=d.reasonMessage)==null?void 0:b.trim())||`${d.label} setup required`:null},[f,t,c,d]);return{sessionTypeOptions:a,selectedSessionTypeOption:d,defaultSessionType:l,selectedSessionType:c,canEditSessionType:p,sessionTypeUnavailable:y,sessionTypeUnavailableMessage:m}}function Wr(e){return(e==null?void 0:e.trim().toLowerCase())||"native"}function Lu(e,t){if(typeof t!="string")return!1;const n=t.trim();return n?e.some(r=>r.value===n):!1}function Nu(e,t){return typeof t=="string"&&e.includes(t)}function Pu(e){return e.length===0?null:e.includes("off")?"off":e[0]??null}function Bi(e){const{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:s,isValueSupported:i,firstAvailableValue:o,preferSessionPreferredValue:a=!1,preserveCurrentValueOnSessionChange:l=!1}=e;return i(t)&&(!a||l)?t:i(n)?n:i(r)?r:i(s)?s:o}function ju(e){var n;const{modelOptions:t}=e;return t.length===0?"":Bi({currentValue:e.currentSelectedModel,selectedSessionPreferredValue:e.selectedSessionPreferredModel,fallbackPreferredValue:e.fallbackPreferredModel,defaultValue:e.defaultModel,isValueSupported:r=>Lu(t,r),firstAvailableValue:((n=t[0])==null?void 0:n.value)??"",preferSessionPreferredValue:e.preferSessionPreferredModel,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedModelOnSessionChange})}function Du(e){const{supportedThinkingLevels:t}=e;return t.length===0?null:Bi({currentValue:e.currentSelectedThinkingLevel,selectedSessionPreferredValue:e.selectedSessionPreferredThinking,fallbackPreferredValue:e.fallbackPreferredThinking,defaultValue:e.defaultThinkingLevel,isValueSupported:n=>Nu(t,n),firstAvailableValue:Pu(t)??"off",preferSessionPreferredValue:e.preferSessionPreferredThinking,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedThinkingOnSessionChange})}function $i(e){const t=Wr(e.sessionType);let n,r=Number.NEGATIVE_INFINITY;for(const s of e.sessions){if(s.key===e.selectedSessionKey||Wr(s.sessionType)!==t)continue;const i=e.readPreference(s);if(i==null)continue;const o=Date.parse(s.updatedAt),a=Number.isFinite(o)?o:Number.NEGATIVE_INFINITY;(n===void 0||a>r)&&(n=i,r=a)}return n}function Ki(e){return $i({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>{var r;return((r=t.preferredModel)==null?void 0:r.trim())||void 0}})}function Ui(e){return $i({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>t.preferredThinking??void 0})}function Vi(e){const{isPreferenceAvailable:t,emptyValue:n,selectedSessionKey:r,selectedSessionExists:s=!1,setValue:i,resolveValue:o}=e,a=k.useRef(void 0),l=k.useRef(o);k.useEffect(()=>{l.current=o},[o]),k.useEffect(()=>{const u=a.current!==r;if(!t){i(n),a.current=r;return}i(c=>l.current({currentValue:c,sessionChanged:u,preserveCurrentValueOnSessionChange:u&&!!r&&!s})),a.current=r},[n,t,s,r,i])}function Hi(e){const{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,setSelectedModel:a}=e;Vi({isPreferenceAvailable:t.length>0,emptyValue:"",selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>ju({currentSelectedModel:l,modelOptions:t,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,preferSessionPreferredModel:u,preserveCurrentSelectedModelOnSessionChange:c})})}function qi(e){const{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,setSelectedThinkingLevel:a}=e;Vi({isPreferenceAvailable:t.length>0,emptyValue:null,selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>Du({currentSelectedThinkingLevel:l,supportedThinkingLevels:t,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,preferSessionPreferredThinking:u,preserveCurrentSelectedThinkingOnSessionChange:c})})}function _u(e){var N,j,T,O,B,$;const t=Ri(),n=Ai(),r=Pl({q:e.query.trim()||void 0,limit:120,activeMinutes:0}),s=Ni("skill"),i=jl({sessionKey:e.selectedSessionKey,agentId:e.selectedAgentId}),o=Dl(e.selectedSessionKey,300),a=_l(),l=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),u=k.useMemo(()=>{const C=ji({meta:n.data,config:t.data,onlyConfigured:!0}),R=new Set,E=[];for(const z of C)for(const _ of z.models){const A=Di(z.prefix,_);!A||R.has(A)||(R.add(A),E.push({value:A,modelLabel:_,providerLabel:z.displayName,thinkingCapability:_i(z.modelThinking,_,z.aliases)}))}return E.sort((z,_)=>{const A=z.providerLabel.localeCompare(_.providerLabel);return A!==0?A:z.modelLabel.localeCompare(_.modelLabel)})},[n.data,t.data]),c=k.useMemo(()=>{var C;return((C=r.data)==null?void 0:C.sessions)??[]},[(N=r.data)==null?void 0:N.sessions]),d=k.useMemo(()=>{var C;return((C=s.data)==null?void 0:C.records)??[]},[(j=s.data)==null?void 0:j.records]),p=k.useMemo(()=>c.find(C=>C.key===e.selectedSessionKey)??null,[e.selectedSessionKey,c]),f=zi({selectedSession:p,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:a.data}),y=k.useMemo(()=>Ki({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]),m=k.useMemo(()=>u.find(C=>C.value===e.currentSelectedModel),[u,e.currentSelectedModel]),b=k.useMemo(()=>{var C;return((C=m==null?void 0:m.thinkingCapability)==null?void 0:C.supported)??[]},[(T=m==null?void 0:m.thinkingCapability)==null?void 0:T.supported]),g=k.useMemo(()=>{var C;return((C=m==null?void 0:m.thinkingCapability)==null?void 0:C.default)??null},[(O=m==null?void 0:m.thinkingCapability)==null?void 0:O.default]),v=k.useMemo(()=>Ui({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]);Hi({modelOptions:u,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,fallbackPreferredModel:y,defaultModel:(B=t.data)==null?void 0:B.agents.defaults.model,setSelectedModel:e.setSelectedModel}),qi({supportedThinkingLevels:b,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredThinking:(p==null?void 0:p.preferredThinking)??null,fallbackPreferredThinking:v??null,defaultThinkingLevel:g,setSelectedThinkingLevel:e.setSelectedThinkingLevel});const w=k.useMemo(()=>{var C;return((C=o.data)==null?void 0:C.messages)??[]},[($=o.data)==null?void 0:$.messages]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,chatCapabilitiesQuery:i,historyQuery:o,sessionTypesQuery:a,isProviderStateResolved:l,modelOptions:u,sessions:c,skillRecords:d,selectedSession:p,historyMessages:w,...f}}function Wi(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const Ou={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 Fu({status:e,className:t}){const n=Ou[e],r=e==="connected"?I("connected"):e==="disconnected"?I("disconnected"):I("connecting");return h.jsx(cu,{delayDuration:250,children:h.jsxs(du,{children:[h.jsx(hu,{asChild:!0,children:h.jsx("span",{role:"status","aria-label":r,className:Le("inline-flex h-5 w-5 items-center justify-center",t),children:e==="connecting"?h.jsx(Wa,{className:Le("h-3 w-3 animate-spin",n.dotClass)}):h.jsx("span",{className:Le(e==="connected"?"h-2 w-2 rounded-full":"",n.dotClass)})})}),h.jsx(fu,{side:"bottom",className:"text-xs",children:r})]})})}function zu(e){const{session:t,active:n,runStatus:r,sessionTypeLabel:s,title:i,isEditing:o,draftLabel:a,isSaving:l,onSelect:u,onStartEditing:c,onDraftLabelChange:d,onSave:p,onCancel:f}=e;return h.jsx("div",{className:Le("w-full rounded-xl px-3 py-2 text-left transition-all text-[13px]",n?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-700 hover:bg-gray-200/60 hover:text-gray-900"),children:o?h.jsxs("div",{className:"space-y-2",children:[h.jsx(pr,{value:a,onChange:y=>d(y.target.value),onKeyDown:y=>{y.key==="Enter"?(y.preventDefault(),p()):y.key==="Escape"&&(y.preventDefault(),f())},placeholder:I("sessionsLabelPlaceholder"),className:"h-8 rounded-lg border-gray-300 bg-white text-xs",autoFocus:!0,disabled:l}),h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("div",{className:"min-w-0 text-[11px] text-gray-400 truncate",children:t.key}),h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx(Ve,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:()=>void p(),disabled:l,"aria-label":I("save"),children:h.jsx(Jt,{className:"h-3.5 w-3.5"})}),h.jsx(Ve,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:f,disabled:l,"aria-label":I("cancel"),children:h.jsx(Ga,{className:"h-3.5 w-3.5"})})]})]})]}):h.jsxs("div",{className:"group/session relative",children:[h.jsxs("button",{type:"button",onClick:u,className:"w-full text-left",children:[h.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5 pr-8",children:[h.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[h.jsx("span",{className:"truncate font-medium",children:i}),s?h.jsx("span",{className:Le("shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none",n?"border-gray-300 bg-white/80 text-gray-700":"border-gray-200 bg-gray-100 text-gray-500"),children:s}):null]}),h.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:r?h.jsx(lu,{status:r}):null})]}),h.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:[t.messageCount," · ",tn(t.updatedAt)]})]}),h.jsx("button",{type:"button",onClick:y=>{y.stopPropagation(),c()},className:Le("absolute right-0 top-0 inline-flex h-7 w-7 items-center justify-center rounded-lg text-gray-400 transition-all hover:bg-white hover:text-gray-900",n?"opacity-100":"opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100"),"aria-label":I("edit"),children:h.jsx(Qa,{className:"h-3.5 w-3.5"})})]})})}function Bu(){const e=Xa();return async t=>{try{t.chatChain==="ncp"?(await Ei(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["ncp-sessions"]}),e.invalidateQueries({queryKey:["ncp-session-messages",t.sessionKey]})):(await Bn(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["sessions"]}),e.invalidateQueries({queryKey:["session-history",t.sessionKey]})),kt.success(I("configSavedApplied"))}catch(n){throw kt.error(I("configSaveFailed")+": "+(n instanceof Error?n.message:String(n))),n}}}const Gi=k.createContext(null);function Qi({presenter:e,children:t}){return h.jsx(Gi.Provider,{value:e,children:t})}function mr(){const e=k.useContext(Gi);if(!e)throw new Error("usePresenter must be used inside ChatPresenterProvider");return e}const $u=e=>`[data-item-index="${e}"]`;function Xi(e){const t=e.getItemSelector??$u;k.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 Ku(){const e=k.useRef(null),[t,n]=k.useState(null);return k.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 de(...e){return Ya(Ja(e))}const Yi=k.forwardRef(({className:e,type:t,...n},r)=>h.jsx("input",{type:t,className:de("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}));Yi.displayName="ChatInput";const Uu=bu,Vu=vu,Hu=Su,Ji=k.forwardRef(({className:e,sideOffset:t=8,align:n="start",...r},s)=>h.jsx(ku,{children:h.jsx(Oi,{ref:s,sideOffset:t,align:n,className:de("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})}));Ji.displayName=Oi.displayName;const qu=Za,Wu=el,Zi=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(yi,{ref:r,className:de("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(tl,{asChild:!0,children:h.jsx(ur,{className:"h-4 w-4 opacity-50"})})]}));Zi.displayName=yi.displayName;const eo=k.forwardRef(({className:e,...t},n)=>h.jsx(Si,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(ol,{className:"h-4 w-4"})}));eo.displayName=Si.displayName;const to=k.forwardRef(({className:e,...t},n)=>h.jsx(ki,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(ur,{className:"h-4 w-4"})}));to.displayName=ki.displayName;const no=k.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>h.jsx(nl,{children:h.jsxs(xi,{ref:s,className:de("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(eo,{}),h.jsx(rl,{className:de("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),h.jsx(to,{})]})}));no.displayName=xi.displayName;const ro=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(bi,{ref:r,className:de("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(sl,{children:h.jsx(Jt,{className:"h-4 w-4"})})}),h.jsx(il,{children:t})]}));ro.displayName=bi.displayName;const Gu=pu,Qu=gu,Xu=mu,so=k.forwardRef(({className:e,sideOffset:t=4,...n},r)=>h.jsx(yu,{children:h.jsx(Pi,{ref:r,sideOffset:t,className:de("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})}));so.displayName=Pi.displayName;const Et={Popover:Uu,PopoverAnchor:Hu,PopoverContent:Ji,PopoverTrigger:Vu,Input:Yi,Select:qu,SelectContent:no,SelectItem:ro,SelectTrigger:Zi,SelectValue:Wu,Tooltip:Qu,TooltipContent:so,TooltipProvider:Gu,TooltipTrigger:Xu},Yu=680,Ju=.82,Zu=560;function ec(e){const{Popover:t,PopoverAnchor:n,PopoverContent:r}=Et,{elementRef:s,width:i}=Ku(),o=k.useRef(null),{isOpen:a,isLoading:l,items:u,activeIndex:c,activeItem:d,texts:p,onSelectItem:f,onOpenChange:y,onSetActiveIndex:m}=e,b=k.useMemo(()=>{if(i)return Math.min(i>Zu?i*Ju:i,Yu)},[i]);return Xi({containerRef:o,activeIndex:c,itemCount:u.length,isEnabled:a&&!l,getItemSelector:g=>`[data-slash-index="${g}"]`}),h.jsxs(t,{open:a,onOpenChange:y,children:[h.jsx(n,{asChild:!0,children:h.jsx("div",{ref:s,className:"pointer-events-none absolute bottom-full left-3 right-3 h-0"})}),h.jsx(r,{side:"top",align:"start",sideOffset:10,className:"z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md",onOpenAutoFocus:g=>g.preventDefault(),style:b?{width:`${b}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:o,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,v)=>{const w=v===c;return h.jsxs("button",{type:"button",role:"option","aria-selected":w,"data-slash-index":v,onMouseEnter:()=>m(v),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 tc=al("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"}}),Ut=k.forwardRef(({className:e,variant:t,size:n,...r},s)=>h.jsx("button",{className:de(tc({variant:t,size:n,className:e})),ref:s,...r}));Ut.displayName="ChatButton";function Gr(){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 nc(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Et;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(Ut,{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(Gr,{})}):h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:h.jsx("span",{children:h.jsx(Ut,{size:"icon",variant:"outline",className:"h-8 w-8 rounded-full","aria-label":e.stopButtonLabel,disabled:!0,children:h.jsx(Gr,{})})})}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:e.stopHint})})]})}):h.jsx(Ut,{size:"icon",className:"h-8 w-8 rounded-full","aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:h.jsx(ll,{className:"h-5 w-5"})})})]})}function rc(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 sc(e){const{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:s}=Et,{picker:i}=e,o=k.useRef(null),a=k.useId(),[l,u]=k.useState(""),[c,d]=k.useState(0),p=k.useMemo(()=>new Set(i.selectedKeys),[i.selectedKeys]),f=i.selectedKeys.length,y=k.useMemo(()=>rc(i.options,l),[i.options,l]);k.useEffect(()=>{d(0)},[l]),k.useEffect(()=>{d(g=>y.length===0?0:Math.min(g,y.length-1))},[y.length]),Xi({containerRef:o,activeIndex:c,itemCount:y.length,isEnabled:y.length>0,getItemSelector:g=>`[data-skill-index="${g}"]`});const m=g=>{if(p.has(g)){i.onSelectedKeysChange(i.selectedKeys.filter(v=>v!==g));return}i.onSelectedKeysChange([...i.selectedKeys,g])},b=g=>{if(y.length!==0){if(g.key==="ArrowDown"){g.preventDefault(),d(v=>Math.min(v+1,y.length-1));return}if(g.key==="ArrowUp"){g.preventDefault(),d(v=>Math.max(v-1,0));return}if(g.key==="Enter"){g.preventDefault();const v=y[c];v&&m(v.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:b,placeholder:i.searchPlaceholder,role:"combobox","aria-controls":a,"aria-expanded":"true","aria-autocomplete":"list","aria-activedescendant":y[c]?`${a}-option-${c}`:void 0,className:"h-8 rounded-lg pl-8 text-xs"})]})]}),h.jsx("div",{ref:o,id:a,role:"listbox","aria-multiselectable":"true",className:"custom-scrollbar max-h-[320px] overflow-y-auto",children:i.isLoading?h.jsx("div",{className:"p-4 text-xs text-gray-500",children:i.loadingLabel}):y.length===0?h.jsx("div",{className:"p-4 text-center text-xs text-gray-500",children:i.emptyLabel}):h.jsx("div",{className:"py-1",children:y.map((g,v)=>{const w=p.has(g.key),N=v===c;return h.jsxs("button",{type:"button",id:`${a}-option-${v}`,role:"option","aria-selected":w,"data-skill-index":v,onClick:()=>m(g.key),onMouseEnter:()=>d(v),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${N?"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(ul,{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(Jt,{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(cl,{className:"h-3 w-3"})]})}):null]})]})}function io({icon:e}){return e==="sparkles"?h.jsx(hl,{className:"h-3.5 w-3.5 shrink-0 text-primary"}):e==="brain"?h.jsx(fl,{className:"h-3.5 w-3.5 shrink-0 text-gray-500"}):null}function ic({icon:e}){return e==="paperclip"?h.jsx(dl,{className:"h-4 w-4"}):h.jsx(io,{icon:e})}function oc(e){return e==="model"?"min-w-[220px]":e==="session-type"?"min-w-[140px]":e==="thinking"?"min-w-[150px]":""}function ac(e){return e==="model"?"w-[320px]":e==="session-type"?"w-[220px]":e==="thinking"?"w-[180px]":""}function lc({item:e}){const{Select:t,SelectContent:n,SelectItem:r,SelectTrigger:s,SelectValue:i}=Et;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 ${oc(e.key)}`,children:e.selectedLabel?h.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-left",children:[h.jsx(io,{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:ac(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(o=>h.jsx(r,{value:o.value,className:"py-2",children:o.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:o.label}),h.jsx("span",{className:"truncate text-[11px] text-gray-500",children:o.description})]}):h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:o.label})},o.value))]})]})}function uc(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Et;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(sc,{picker:e.skillPicker}):null,e.selects.map(o=>h.jsx(lc,{item:o},o.key)),(i=e.accessories)==null?void 0:i.map(o=>{const a=h.jsxs("button",{type:"button",className:`inline-flex items-center rounded-lg 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 ${o.iconOnly?"h-8 w-8 justify-center px-0":"gap-1.5 px-3"}`,onClick:o.onClick,disabled:o.disabled,"aria-label":o.label,children:[h.jsx(ic,{icon:o.icon}),o.iconOnly?null:h.jsx("span",{children:o.label})]});if(!o.tooltip)return h.jsx("div",{children:a},o.key);const l=o.disabled?h.jsx("span",{className:"inline-flex",children:a}):a;return h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:l}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:o.tooltip})})]})},o.key)})]}),h.jsx(nc,{...e.actions})]})}const cc="";function oo(){return`composer-${Math.random().toString(36).slice(2,10)}`}function It(e=""){return{id:oo(),type:"text",text:e}}function yr(e){return{id:oo(),type:"token",tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function Lt(e){return e.type==="text"?e.text.length:1}function xr(){return[It("")]}function dc(e){return[It(e)]}function ut(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?xr():t}function hc(e){return e.map(t=>t.type==="text"?t.text:cc).join("")}function fc(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function nn(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 pc(e,t,n,r){const s=Math.max(0,n-t),i=Math.max(0,t+e.text.length-r),o=[];return s>0&&o.push({...e,text:e.text.slice(0,s)}),i>0&&o.push({...e,text:e.text.slice(e.text.length-i)}),o}function gc(e,t,n,r){return t<=n||e>=r}function mc(e,t,n,r,s){return!n&&r>=s?(e.push(...t),!0):n}function yc(e,t,n,r,s,i,o){const a=pc(t,n,r,s);a[0]&&e.push(a[0]);let l=o;return l||(e.push(...i),l=!0),a[1]&&e.push(a[1]),l}function xc(e,t,n,r,s,i){return!r&&s<=i?(e.push(...n),!0):(e.push(t),r)}function dn(e,t,n,r){const s=Math.max(0,t),i=Math.max(s,n),o=[];let a=0,l=!1;for(const u of e){const c=Lt(u),d=a,p=a+c;if(gc(d,p,s,i)){l=mc(o,r,l,d,i),o.push(u),a=p;continue}u.type==="text"?l=yc(o,u,d,s,i,r,l):l=xc(o,u,r,l,s,d),a=p}return l||o.push(...r),ut(o)}function br(e,t){return ut(e.filter(n=>n.type!=="token"||!t(n)))}function bc(e,t){if(!t||t.start!==t.end)return null;const n=hc(e),r=t.end,s=n.slice(0,r),i=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(s);if(!i)return null;const o=r-i[0].length+(i[0].startsWith("/")?0:1);return{query:(i[1]??"").trim().toLowerCase(),start:o,end:r}}function Sc(e,t,n){return e?e.start<n&&e.end>t:!1}function ao(e){const t=new Map;let n=0;for(const r of e)t.set(r.id,n),n+=Lt(r);return t}function lo(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 kc(e,t,n){if(e instanceof HTMLElement){const r=e.dataset.composerNodeId;if(r)return n.find(s=>s.id===r)}return n[t]}function uo(e,t,n){let r=0;for(let s=0;s<n;s+=1){const i=kc(e.childNodes[s],s,t);i&&(r+=Lt(i))}return r}function vc(e,t,n,r){var a;const s=lo(e,t),i=uo(e,r,s),o=r[s];return(o==null?void 0:o.type)==="text"?i+Math.min(n,o.text.length):i+Math.min(n,((a=t.textContent)==null?void 0:a.length)??0)}function wc(e,t,n,r,s){return n.type==="text"?e.nodeType===Node.TEXT_NODE?r+Math.min(t,n.text.length):e===s?r+(t>0?n.text.length:0):r+n.text.length:e===s?r+(t>0?1:0):r+1}function $n(e,t,n,r,s){var u;if(t===e)return uo(e,r,n);if(t.nodeType===Node.TEXT_NODE&&t.parentNode===e)return vc(e,t,n,r);const i=t instanceof HTMLElement?t.closest("[data-composer-node-id]"):((u=t.parentElement)==null?void 0:u.closest("[data-composer-node-id]"))??null;if(!(i instanceof HTMLElement)){const c=lo(e,t);return $n(e,e,c,r,s)}const o=i.dataset.composerNodeId;if(!o)return 0;const a=r.find(c=>c.id===o),l=s.get(o)??0;return a?wc(t,n,a,l,i):l}function co(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=ao(t),i=$n(e,r.startContainer,r.startOffset,t,s),o=$n(e,r.endContainer,r.endOffset,t,s);return{start:Math.min(i,o),end:Math.max(i,o)}}function Cc(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=Lt(d),f=u,y=u+p,m=e.childNodes[c];if(!m){u=y;continue}if(d.type==="text"){if(l<=y)return{container:m.firstChild??m,offset:Math.max(0,Math.min(l-f,d.text.length))}}else{if(l<=f)return{container:e,offset:c};if(l<=y)return{container:e,offset:c+1}}u=y}return{container:e,offset:e.childNodes.length}},i=s(n.start),o=s(n.end),a=document.createRange();a.setStart(i.container,i.offset),a.setEnd(o.container,o.offset),r.removeAllRanges(),r.addRange(a)}function Tc(e){const t=[];for(const n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(It(n.textContent??""));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType==="token"){const i=n.dataset.composerTokenKind,o=n.dataset.composerTokenKey,a=n.dataset.composerLabel;i&&o&&a&&t.push({id:n.dataset.composerNodeId??yr({tokenKind:i,tokenKey:o,label:a}).id,type:"token",tokenKind:i,tokenKey:o,label:a});continue}const s=n.textContent??"";t.push({id:n.dataset.composerNodeId??It(s).id,type:"text",text:s})}return ut(t)}function Qr(e){const t=Tc(e);return{nodes:t,selection:co(e,t)}}class Ic{constructor(){this.nodes=xr(),this.selection=null,this.sync=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.setSelection=t=>(this.selection=t,this.getSnapshot()),this.replaceDocument=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.insertText=t=>{const n=this.selection??{start:0,end:0};this.nodes=dn(this.nodes,n.start,n.end,[It(t)]);const r=n.start+t.length;return this.selection={start:r,end:r},this.getSnapshot()},this.insertFileToken=(t,n)=>this.insertToken("file",t,n),this.insertSkillToken=(t,n)=>this.getSelectedSkillKeys().includes(t)?this.getSnapshot():this.insertToken("skill",t,n,this.getSlashTrigger()),this.syncSelectedSkills=(t,n)=>{const r=this.getSelectedSkillKeys(),s=new Map(n.map(a=>[a.key,a])),i=t.find(a=>!r.includes(a));if(i){const a=s.get(i);return this.insertSkillToken(i,(a==null?void 0:a.label)??i)}const o=r.find(a=>!t.includes(a));return o&&(this.nodes=br(this.nodes,a=>a.tokenKind==="skill"&&a.tokenKey===o)),this.getSnapshot()},this.deleteContent=t=>{const n=this.getDocumentLength(),r=this.selection??{start:n,end:n};let s=r.start,i=r.end;if(r.start===r.end)if(t==="backward"&&r.start>0)s=r.start-1;else if(t==="forward")i=r.end+1;else return this.getSnapshot();return this.nodes=dn(this.nodes,s,i,[]),this.selection={start:s,end:s},this.getSnapshot()},this.getSnapshot=()=>({nodes:this.nodes,selection:this.selection,nodeStartMap:ao(this.nodes),documentLength:this.getDocumentLength(),selectedSkillKeys:this.getSelectedSkillKeys(),slashTrigger:this.getSlashTrigger()}),this.getDocumentLength=()=>this.nodes.reduce((t,n)=>t+Lt(n),0),this.getSelectedSkillKeys=()=>nn(this.nodes,"skill"),this.insertToken=(t,n,r,s=null)=>{var l,u;const i=this.getDocumentLength(),o=(s==null?void 0:s.start)??((l=this.selection)==null?void 0:l.start)??i,a=(s==null?void 0:s.end)??((u=this.selection)==null?void 0:u.end)??o;return this.nodes=dn(this.nodes,o,a,[yr({tokenKind:t,tokenKey:n,label:r})]),this.selection={start:o+1,end:o+1},this.getSnapshot()},this.getSlashTrigger=()=>bc(this.nodes,this.selection)}}function Mc(e){const{key:t,shiftKey:n,isComposing:r,isSlashMenuOpen:s,slashItemCount:i,activeSlashIndex:o,isSending:a,canStopGeneration:l}=e;if(s&&i>0){if(t==="ArrowDown")return{type:"move-slash-index",index:(o+1)%i};if(t==="ArrowUp")return{type:"move-slash-index",index:(o-1+i)%i};if(t==="Enter"&&!n||t==="Tab")return{type:"insert-active-slash-item"}}return t==="Escape"?s?{type:"close-slash"}:a&&l?{type:"stop-generation"}:{type:"noop"}:t==="Enter"&&n?{type:"insert-line-break"}:t==="Enter"?{type:"send-message"}:!r&&(t==="Backspace"||t==="Delete")?{type:"delete-content",direction:t==="Backspace"?"backward":"forward"}:{type:"noop"}}const Xr="http://www.w3.org/2000/svg";class Rc{constructor(){this.render=(t,n)=>{if(!t)return;const r=document.createDocumentFragment();for(const s of n.nodes){const i=s.type==="text"?this.createTextNodeElement(s):this.createTokenNodeElement(s,n.selectedRange,n.nodeStartMap);i&&r.appendChild(i)}t.replaceChildren(r)},this.createTextNodeElement=t=>{if(t.text.length===0)return null;const n=document.createElement("span");return n.dataset.composerNodeId=t.id,n.dataset.composerNodeType="text",n.textContent=t.text,n},this.createTokenNodeElement=(t,n,r)=>{const s=r.get(t.id)??0,i=Sc(n,s,s+1),o=document.createElement("span");o.contentEditable="false",o.dataset.composerNodeId=t.id,o.dataset.composerNodeType="token",o.dataset.composerTokenKind=t.tokenKind,o.dataset.composerTokenKey=t.tokenKey,o.dataset.composerLabel=t.label,o.title=t.label,o.className=this.buildTokenClassName(t.tokenKind,i),o.append(this.createTokenIcon(t.tokenKind));const a=document.createElement("span");return a.className=t.tokenKind==="file"?"min-w-0 flex-1 truncate text-[12px] font-medium text-slate-700":"truncate",a.textContent=t.label,o.append(a),o},this.buildTokenClassName=(t,n)=>t==="file"?["mx-[2px]","inline-flex","h-7","max-w-[min(100%,17rem)]","items-center","gap-1.5","rounded-lg","border","px-2","align-baseline","transition-[border-color,background-color,box-shadow,color]","duration-150",n?"border-slate-300 bg-slate-100 text-slate-800 shadow-[0_0_0_2px_rgba(148,163,184,0.14)]":"border-slate-200/80 bg-slate-50 text-slate-700"].join(" "):["mx-[2px]","inline-flex","h-7","max-w-full","items-center","gap-1.5","rounded-lg","border","px-2","align-baseline","text-[11px]","font-medium","transition",n?"border-primary/30 bg-primary/18 text-primary":"border-primary/12 bg-primary/8 text-primary"].join(" "),this.createTokenIcon=t=>{const n=document.createElement("span");return n.className=t==="file"?"inline-flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-md bg-white text-slate-500 ring-1 ring-black/5":"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-primary/70",n.append(t==="file"?this.createFileIcon():this.createSkillIcon()),n},this.createSkillIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M8.5 2.75 2.75 6l5.75 3.25L14.25 6 8.5 2.75Z"}},{tag:"path",attrs:{d:"M2.75 10 8.5 13.25 14.25 10"}},{tag:"path",attrs:{d:"M2.75 6v4l5.75 3.25V9.25L2.75 6Z"}},{tag:"path",attrs:{d:"M14.25 6v4L8.5 13.25V9.25L14.25 6Z"}}]),this.createFileIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M3.25 4.25A1.5 1.5 0 0 1 4.75 2.75h6.5a1.5 1.5 0 0 1 1.5 1.5v7.5a1.5 1.5 0 0 1-1.5 1.5h-6.5a1.5 1.5 0 0 1-1.5-1.5v-7.5Z"}},{tag:"path",attrs:{d:"m4.75 10 2.25-2.5 1.75 1.75 1.25-1.25 2 2"}},{tag:"path",attrs:{d:"M9.75 6.25h.01"}}]),this.createSvgIcon=t=>{const n=document.createElementNS(Xr,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.25"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("class","h-3 w-3");for(const r of t){const s=document.createElementNS(Xr,r.tag);for(const[i,o]of Object.entries(r.attrs))s.setAttribute(i,o);n.append(s)}return n}}}const Yr=188;class Ac{constructor(t){this.controller=t,this.surfaceRenderer=new Rc,this.sync=(n,r)=>this.controller.sync(n,r),this.syncSelectionFromRoot=n=>this.controller.setSelection(co(n,this.controller.getSnapshot().nodes)),this.restoreSelectionIfFocused=(n,r)=>{!n||document.activeElement!==n||Cc(n,this.controller.getSnapshot().nodes,r)},this.syncViewport=n=>{n&&(n.style.maxHeight=`${Yr}px`,n.style.overflowY=n.scrollHeight>Yr?"auto":"hidden")},this.renderSurface=n=>{this.surfaceRenderer.render(n.root,{nodes:n.snapshot.nodes,selectedRange:n.selectedRange,nodeStartMap:n.snapshot.nodeStartMap})},this.insertSlashItem=(n,r)=>{n.value&&r(this.controller.insertSkillToken(n.value,n.title))},this.syncSelectedSkills=(n,r,s)=>{s(this.controller.syncSelectedSkills(n,r))},this.handleBeforeInput=n=>{const{event:r,disabled:s,isComposing:i,commitSnapshot:o}=n,a=r.nativeEvent;s||i||a.isComposing||!(a.inputType==="insertText"||a.inputType==="insertReplacementText")||!a.data||(r.preventDefault(),o(this.controller.insertText(a.data)))},this.handleInput=n=>{const{event:r,isComposing:s,commitSnapshot:i}=n,o=r.nativeEvent;if(s||o.isComposing)return;const a=r.currentTarget,l=Qr(a);i(this.controller.replaceDocument(l.nodes,l.selection))},this.handleCompositionEnd=n=>{const{event:r,commitSnapshot:s}=n,i=r.currentTarget,o=Qr(i);s(this.controller.replaceDocument(o.nodes,o.selection))},this.handleKeyDown=n=>{const{event:r,slashItems:s,activeSlashIndex:i,activeSlashItem:o,actions:a,commitSnapshot:l,insertSkillToken:u,onSlashActiveIndexChange:c,onSlashQueryChange:d,onSlashOpenChange:p}=n,f=this.controller.getSnapshot(),y=Mc({key:r.key,shiftKey:r.shiftKey,isComposing:r.nativeEvent.isComposing,isSlashMenuOpen:f.slashTrigger!==null,slashItemCount:s.length,activeSlashIndex:i,isSending:a.isSending,canStopGeneration:a.canStopGeneration});if(y.type!=="noop"){if(r.preventDefault(),y.type==="move-slash-index"){c(y.index);return}if(y.type==="insert-active-slash-item"){o&&u(o.value??o.key,o.title);return}if(y.type==="close-slash"){d==null||d(null),p(!1);return}if(y.type==="stop-generation"){a.onStop();return}if(y.type==="insert-line-break"){l(this.controller.insertText(`
|
|
2
|
-
`));return}if(y.type==="send-message"){a.onSend();return}y.type==="delete-content"&&l(this.controller.deleteContent(y.direction))}},this.handlePaste=n=>{const{event:r,onFilesAdd:s,commitSnapshot:i}=n,o=Array.from(r.clipboardData.files??[]);if(o.length>0&&s){r.preventDefault(),s(o);return}const a=r.clipboardData.getData("text/plain");a&&(r.preventDefault(),i(this.controller.insertText(a)))},this.handleBlur=n=>{const{clearSelectedRange:r,onSlashQueryChange:s,onSlashOpenChange:i}=n;r(),s==null||s(null),i(!1)}}}class Ec{constructor(){this.controller=new Ic,this.viewController=new Ac(this.controller),this.rootElement=null,this.selection=null,this.selectedRange=null,this.snapshot=this.controller.getSnapshot(),this.config=null,this.isComposing=!1,this.bindRootElement=t=>{this.rootElement=t},this.update=t=>(this.config=t,this.snapshot=this.viewController.sync(t.nodes,this.selectedRange),{snapshot:this.snapshot,selectedRange:this.selectedRange,bindRootElement:this.bindRootElement,handleBeforeInput:this.handleBeforeInput,handleInput:this.handleInput,handleCompositionStart:this.handleCompositionStart,handleCompositionEnd:this.handleCompositionEnd,handleKeyDown:this.handleKeyDown,handlePaste:this.handlePaste,handleBlur:this.handleBlur,syncSelectionState:this.syncSelectionState,imperativeHandle:this.createHandle()}),this.createHandle=()=>({insertSlashItem:t=>{this.viewController.insertSlashItem(t,this.commitSnapshot)},insertFileToken:(t,n)=>{this.commitSnapshot(this.controller.insertFileToken(t,n)),this.focusComposerSoon()},insertFileTokens:t=>{let n=null;for(const r of t)n=this.controller.insertFileToken(r.tokenKey,r.label);n&&(this.commitSnapshot(n),this.focusComposerSoon())},focusComposer:()=>{this.focusComposer()},syncSelectedSkills:(t,n)=>{this.viewController.syncSelectedSkills(t,n,this.commitSnapshot)}}),this.restoreDomAfterCommit=()=>{this.isComposing||this.viewController.restoreSelectionIfFocused(this.rootElement,this.selection)},this.renderSurface=()=>{this.isComposing||this.viewController.renderSurface({root:this.rootElement,snapshot:this.snapshot,selectedRange:this.selectedRange})},this.syncViewport=()=>{this.viewController.syncViewport(this.rootElement)},this.syncSelectionState=()=>{if(!this.rootElement||this.isComposing)return;const t=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=t.selection,this.selectedRange=t.selection,this.syncSlashState(t),this.requestRender()},this.handleBeforeInput=t=>{this.viewController.handleBeforeInput({event:t,disabled:this.requireConfig().disabled,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleInput=t=>{this.viewController.handleInput({event:t,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleCompositionStart=()=>{this.isComposing=!0},this.handleCompositionEnd=t=>{this.isComposing=!1,this.viewController.handleCompositionEnd({event:t,commitSnapshot:this.commitSnapshot})},this.handleKeyDown=t=>{const n=this.requireConfig();if(this.rootElement&&!this.isComposing){const s=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=s.selection,this.selectedRange=s.selection,this.snapshot=s}const r=n.slashItems[n.activeSlashIndex]??null;this.viewController.handleKeyDown({event:t,slashItems:n.slashItems,activeSlashIndex:n.activeSlashIndex,activeSlashItem:r,actions:n.actions,commitSnapshot:this.commitSnapshot,insertSkillToken:this.insertSkillToken,onSlashActiveIndexChange:n.onSlashActiveIndexChange,onSlashQueryChange:n.onSlashQueryChange,onSlashOpenChange:n.onSlashOpenChange})},this.handlePaste=t=>{this.viewController.handlePaste({event:t,onFilesAdd:this.requireConfig().onFilesAdd,commitSnapshot:this.commitSnapshot})},this.handleBlur=()=>{const t=this.requireConfig();this.isComposing=!1,this.viewController.handleBlur({clearSelectedRange:this.clearSelectedRange,onSlashQueryChange:t.onSlashQueryChange,onSlashOpenChange:t.onSlashOpenChange})},this.setSelectedRange=t=>{this.selectedRange=t,this.selection=t,this.requestRender()},this.clearSelectedRange=()=>{this.selectedRange=null,this.requestRender()},this.commitSnapshot=t=>{const n=this.requireConfig();this.selection=t.selection,this.selectedRange=t.selection,this.snapshot=t,n.onNodesChange(t.nodes),this.syncSlashState(t)},this.insertSkillToken=(t,n)=>{this.commitSnapshot(this.controller.insertSkillToken(t,n))},this.syncSlashState=t=>{var r,s,i;const n=this.requireConfig();(r=n.onSlashTriggerChange)==null||r.call(n,t.slashTrigger),(i=n.onSlashQueryChange)==null||i.call(n,((s=t.slashTrigger)==null?void 0:s.query)??null),n.onSlashOpenChange(t.slashTrigger!==null)},this.requestRender=()=>{this.requireConfig().requestRender()},this.focusComposerSoon=()=>{if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>this.focusComposer());return}this.focusComposer()},this.focusComposer=()=>{this.rootElement&&(this.rootElement.focus(),this.viewController.restoreSelectionIfFocused(this.rootElement,this.selection))},this.requireConfig=()=>{if(!this.config)throw new Error("ChatComposerRuntime is not configured.");return this.config}}}const Lc=k.forwardRef(function(t,n){const{nodes:r,placeholder:s,disabled:i,slashItems:o,actions:a,onNodesChange:l,onFilesAdd:u,onSlashQueryChange:c,onSlashTriggerChange:d,onSlashOpenChange:p,onSlashActiveIndexChange:f,activeSlashIndex:y}=t,[m,b]=k.useState(0),[g]=k.useState(()=>new Ec),{snapshot:v,bindRootElement:w,handleBeforeInput:N,handleInput:j,handleCompositionStart:T,handleCompositionEnd:O,handleKeyDown:B,handlePaste:$,handleBlur:C,syncSelectionState:R,imperativeHandle:E}=g.update({nodes:r,disabled:i,slashItems:o,actions:a,onNodesChange:l,onFilesAdd:u,onSlashQueryChange:c,onSlashTriggerChange:d,onSlashOpenChange:p,onSlashActiveIndexChange:f,activeSlashIndex:y,requestRender:()=>b(z=>z+1)});return k.useImperativeHandle(n,()=>E,[E]),k.useLayoutEffect(()=>{g.renderSurface(),g.restoreDomAfterCommit(),g.syncViewport()},[g,v.nodes,v.nodeStartMap,m]),h.jsx("div",{className:"px-4 py-2.5",children:h.jsx("div",{className:"min-h-[60px]",children:h.jsx("div",{ref:w,contentEditable:!i,suppressContentEditableWarning:!0,role:"textbox","aria-multiline":"true","data-placeholder":s,onBeforeInput:N,onInput:j,onCompositionStart:T,onCompositionEnd:O,onKeyDown:B,onKeyUp:R,onMouseUp:R,onFocus:R,onBlur:C,onPaste:$,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)]"})})})});function Nc({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]})})}const ho=k.forwardRef(function(t,n){const r=k.useRef(null),[s,i]=k.useState(null),[o,a]=k.useState(0),[l,u]=k.useState(null),[c,d]=k.useState(null),p=l!==null&&c!==l,f=t.slashMenu.items[o]??null;k.useEffect(()=>{a(m=>t.slashMenu.items.length===0?0:Math.min(m,t.slashMenu.items.length-1))},[t.slashMenu.items.length]),k.useEffect(()=>{s!==null&&a(0)},[s]),k.useEffect(()=>{l===null&&c!==null&&d(null)},[l,c]);const y=k.useMemo(()=>t.toolbar.skillPicker?{...t.toolbar,skillPicker:{...t.toolbar.skillPicker,onSelectedKeysChange:m=>{var b,g;(g=r.current)==null||g.syncSelectedSkills(m,((b=t.toolbar.skillPicker)==null?void 0:b.options)??[])}}}:t.toolbar,[t.toolbar]);return k.useImperativeHandle(n,()=>({insertFileToken:(m,b)=>{var g;return(g=r.current)==null?void 0:g.insertFileToken(m,b)},insertFileTokens:m=>{var b;return(b=r.current)==null?void 0:b.insertFileTokens(m)},focusComposer:()=>{var m;return(m=r.current)==null?void 0:m.focusComposer()}}),[]),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(Lc,{ref:r,nodes:t.composer.nodes,placeholder:t.composer.placeholder,disabled:t.composer.disabled,slashItems:t.slashMenu.items,actions:t.toolbar.actions,activeSlashIndex:o,onNodesChange:t.composer.onNodesChange,onFilesAdd:t.composer.onFilesAdd,onSlashQueryChange:m=>{var b,g;i(m),(g=(b=t.composer).onSlashQueryChange)==null||g.call(b,m)},onSlashTriggerChange:m=>{u((m==null?void 0:m.start)??null)},onSlashOpenChange:m=>{!m&&l!==null&&d(l)},onSlashActiveIndexChange:a}),h.jsx(ec,{isOpen:p,isLoading:t.slashMenu.isLoading,items:t.slashMenu.items,activeIndex:o,activeItem:f,texts:t.slashMenu.texts,onSelectItem:m=>{var b;d(null),(b=r.current)==null||b.insertSlashItem(m)},onOpenChange:m=>{!m&&l!==null&&d(l)},onSetActiveIndex:a})]}),h.jsx(Nc,{hint:t.hint}),h.jsx(uc,{...y})]})})})});ho.displayName="ChatInputBar";function hn({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(pl,{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(vi,{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(wi,{className:"h-4 w-4"})})}function Pc(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const jc=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Dc=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,_c={};function Jr(e,t){return(_c.jsx?Dc:jc).test(e)}const Oc=/[ \t\n\f\r]/g;function Fc(e){return typeof e=="object"?e.type==="text"?Zr(e.value):!1:Zr(e)}function Zr(e){return e.replace(Oc,"")===""}class Nt{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Nt.prototype.normal={};Nt.prototype.property={};Nt.prototype.space=void 0;function fo(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new Nt(n,r,t)}function Kn(e){return e.toLowerCase()}class Se{constructor(t,n){this.attribute=n,this.property=t}}Se.prototype.attribute="";Se.prototype.booleanish=!1;Se.prototype.boolean=!1;Se.prototype.commaOrSpaceSeparated=!1;Se.prototype.commaSeparated=!1;Se.prototype.defined=!1;Se.prototype.mustUseProperty=!1;Se.prototype.number=!1;Se.prototype.overloadedBoolean=!1;Se.prototype.property="";Se.prototype.spaceSeparated=!1;Se.prototype.space=void 0;let zc=0;const q=tt(),le=tt(),Un=tt(),P=tt(),te=tt(),at=tt(),we=tt();function tt(){return 2**++zc}const Vn=Object.freeze(Object.defineProperty({__proto__:null,boolean:q,booleanish:le,commaOrSpaceSeparated:we,commaSeparated:at,number:P,overloadedBoolean:Un,spaceSeparated:te},Symbol.toStringTag,{value:"Module"})),fn=Object.keys(Vn);class Sr extends Se{constructor(t,n,r,s){let i=-1;if(super(t,n),es(this,"space",s),typeof r=="number")for(;++i<fn.length;){const o=fn[i];es(this,fn[i],(r&Vn[o])===Vn[o])}}}Sr.prototype.defined=!0;function es(e,t,n){n&&(e[t]=n)}function dt(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new Sr(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 Nt(t,n,e.space)}const po=dt({properties:{ariaActiveDescendant:null,ariaAtomic:le,ariaAutoComplete:null,ariaBusy:le,ariaChecked:le,ariaColCount:P,ariaColIndex:P,ariaColSpan:P,ariaControls:te,ariaCurrent:null,ariaDescribedBy:te,ariaDetails:null,ariaDisabled:le,ariaDropEffect:te,ariaErrorMessage:null,ariaExpanded:le,ariaFlowTo:te,ariaGrabbed:le,ariaHasPopup:null,ariaHidden:le,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:te,ariaLevel:P,ariaLive:null,ariaModal:le,ariaMultiLine:le,ariaMultiSelectable:le,ariaOrientation:null,ariaOwns:te,ariaPlaceholder:null,ariaPosInSet:P,ariaPressed:le,ariaReadOnly:le,ariaRelevant:null,ariaRequired:le,ariaRoleDescription:te,ariaRowCount:P,ariaRowIndex:P,ariaRowSpan:P,ariaSelected:le,ariaSetSize:P,ariaSort:null,ariaValueMax:P,ariaValueMin:P,ariaValueNow:P,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function go(e,t){return t in e?e[t]:t}function mo(e,t){return go(e,t.toLowerCase())}const Bc=dt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:at,acceptCharset:te,accessKey:te,action:null,allow:null,allowFullScreen:q,allowPaymentRequest:q,allowUserMedia:q,alt:null,as:null,async:q,autoCapitalize:null,autoComplete:te,autoFocus:q,autoPlay:q,blocking:te,capture:null,charSet:null,checked:q,cite:null,className:te,cols:P,colSpan:null,content:null,contentEditable:le,controls:q,controlsList:te,coords:P|at,crossOrigin:null,data:null,dateTime:null,decoding:null,default:q,defer:q,dir:null,dirName:null,disabled:q,download:Un,draggable:le,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:q,formTarget:null,headers:te,height:P,hidden:Un,high:P,href:null,hrefLang:null,htmlFor:te,httpEquiv:te,id:null,imageSizes:null,imageSrcSet:null,inert:q,inputMode:null,integrity:null,is:null,isMap:q,itemId:null,itemProp:te,itemRef:te,itemScope:q,itemType:te,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:q,low:P,manifest:null,max:null,maxLength:P,media:null,method:null,min:null,minLength:P,multiple:q,muted:q,name:null,nonce:null,noModule:q,noValidate:q,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:q,optimum:P,pattern:null,ping:te,placeholder:null,playsInline:q,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:q,referrerPolicy:null,rel:te,required:q,reversed:q,rows:P,rowSpan:P,sandbox:te,scope:null,scoped:q,seamless:q,selected:q,shadowRootClonable:q,shadowRootDelegatesFocus:q,shadowRootMode:null,shape:null,size:P,sizes:null,slot:null,span:P,spellCheck:le,src:null,srcDoc:null,srcLang:null,srcSet:null,start:P,step:null,style:null,tabIndex:P,target:null,title:null,translate:null,type:null,typeMustMatch:q,useMap:null,value:le,width:P,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:te,axis:null,background:null,bgColor:null,border:P,borderColor:null,bottomMargin:P,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:q,declare:q,event:null,face:null,frame:null,frameBorder:null,hSpace:P,leftMargin:P,link:null,longDesc:null,lowSrc:null,marginHeight:P,marginWidth:P,noResize:q,noHref:q,noShade:q,noWrap:q,object:null,profile:null,prompt:null,rev:null,rightMargin:P,rules:null,scheme:null,scrolling:le,standby:null,summary:null,text:null,topMargin:P,valueType:null,version:null,vAlign:null,vLink:null,vSpace:P,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:q,disableRemotePlayback:q,prefix:null,property:null,results:P,security:null,unselectable:null},space:"html",transform:mo}),$c=dt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:we,accentHeight:P,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:P,amplitude:P,arabicForm:null,ascent:P,attributeName:null,attributeType:null,azimuth:P,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:P,by:null,calcMode:null,capHeight:P,className:te,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:P,diffuseConstant:P,direction:null,display:null,dur:null,divisor:P,dominantBaseline:null,download:q,dx:null,dy:null,edgeMode:null,editable:null,elevation:P,enableBackground:null,end:null,event:null,exponent:P,externalResourcesRequired:null,fill:null,fillOpacity:P,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:at,g2:at,glyphName:at,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:P,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:P,horizOriginX:P,horizOriginY:P,id:null,ideographic:P,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:P,k:P,k1:P,k2:P,k3:P,k4:P,kernelMatrix:we,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:P,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:P,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:P,overlineThickness:P,paintOrder:null,panose1:null,path:null,pathLength:P,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:te,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:P,pointsAtY:P,pointsAtZ:P,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:we,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:we,rev:we,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:we,requiredFeatures:we,requiredFonts:we,requiredFormats:we,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:P,specularExponent:P,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:P,strikethroughThickness:P,string:null,stroke:null,strokeDashArray:we,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:P,strokeOpacity:P,strokeWidth:null,style:null,surfaceScale:P,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:we,tabIndex:P,tableValues:null,target:null,targetX:P,targetY:P,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:we,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:P,underlineThickness:P,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:P,values:null,vAlphabetic:P,vMathematical:P,vectorEffect:null,vHanging:P,vIdeographic:P,version:null,vertAdvY:P,vertOriginX:P,vertOriginY:P,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:P,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:go}),yo=dt({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()}}),xo=dt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:mo}),bo=dt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Kc={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"},Uc=/[A-Z]/g,ts=/-[a-z]/g,Vc=/^data[-\w.:]+$/i;function Hc(e,t){const n=Kn(t);let r=t,s=Se;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Vc.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ts,Wc);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ts.test(i)){let o=i.replace(Uc,qc);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}s=Sr}return new s(r,t)}function qc(e){return"-"+e.toLowerCase()}function Wc(e){return e.charAt(1).toUpperCase()}const Gc=fo([po,Bc,yo,xo,bo],"html"),kr=fo([po,$c,yo,xo,bo],"svg");function Qc(e){return e.join(" ").trim()}var rt={},pn,ns;function Xc(){if(ns)return pn;ns=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,a=/^\s+|\s+$/g,l=`
|
|
3
|
-
`,u="/",c="*",d="",p="comment",f="declaration";function y(b,g){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];g=g||{};var v=1,w=1;function N(_){var A=_.match(t);A&&(v+=A.length);var K=_.lastIndexOf(l);w=~K?_.length-K:w+_.length}function j(){var _={line:v,column:w};return function(A){return A.position=new T(_),$(),A}}function T(_){this.start=_,this.end={line:v,column:w},this.source=g.source}T.prototype.content=b;function O(_){var A=new Error(g.source+":"+v+":"+w+": "+_);if(A.reason=_,A.filename=g.source,A.line=v,A.column=w,A.source=b,!g.silent)throw A}function B(_){var A=_.exec(b);if(A){var K=A[0];return N(K),b=b.slice(K.length),A}}function $(){B(n)}function C(_){var A;for(_=_||[];A=R();)A!==!1&&_.push(A);return _}function R(){var _=j();if(!(u!=b.charAt(0)||c!=b.charAt(1))){for(var A=2;d!=b.charAt(A)&&(c!=b.charAt(A)||u!=b.charAt(A+1));)++A;if(A+=2,d===b.charAt(A-1))return O("End of comment missing");var K=b.slice(2,A-2);return w+=2,N(K),b=b.slice(A),w+=2,_({type:p,comment:K})}}function E(){var _=j(),A=B(r);if(A){if(R(),!B(s))return O("property missing ':'");var K=B(i),L=_({type:f,property:m(A[0].replace(e,d)),value:K?m(K[0].replace(e,d)):d});return B(o),L}}function z(){var _=[];C(_);for(var A;A=E();)A!==!1&&(_.push(A),C(_));return _}return $(),z()}function m(b){return b?b.replace(a,d):d}return pn=y,pn}var rs;function Yc(){if(rs)return rt;rs=1;var e=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0}),rt.default=n;const t=e(Xc());function n(r,s){let i=null;if(!r||typeof r!="string")return i;const o=(0,t.default)(r),a=typeof s=="function";return o.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;a?s(u,c,l):c&&(i=i||{},i[u]=c)}),i}return rt}var mt={},ss;function Jc(){if(ss)return mt;ss=1,Object.defineProperty(mt,"__esModule",{value:!0}),mt.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)},o=function(u,c){return c.toUpperCase()},a=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,a):u=u.replace(r,a),u.replace(t,o))};return mt.camelCase=l,mt}var yt,is;function Zc(){if(is)return yt;is=1;var e=yt&&yt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},t=e(Yc()),n=Jc();function r(s,i){var o={};return!s||typeof s!="string"||(0,t.default)(s,function(a,l){a&&l&&(o[(0,n.camelCase)(a,i)]=l)}),o}return r.default=r,yt=r,yt}var ed=Zc();const td=Ci(ed),So=ko("end"),vr=ko("start");function ko(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 nd(e){const t=vr(e),n=So(e);if(t&&n)return{start:t,end:n}}function wt(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?os(e.position):"start"in e||"end"in e?os(e):"line"in e||"column"in e?Hn(e):""}function Hn(e){return as(e&&e.line)+":"+as(e&&e.column)}function os(e){return Hn(e&&e.start)+"-"+Hn(e&&e.end)}function as(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={},o=!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&&(o=!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 a=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=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=wt(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=o&&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 wr={}.hasOwnProperty,rd=new Map,sd=/[A-Z]/g,id=new Set(["table","tbody","thead","tfoot","tr"]),od=new Set(["td","th"]),vo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function ad(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=gd(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=pd(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"?kr:Gc,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=wo(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function wo(e,t,n){if(t.type==="element")return ld(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return ud(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return dd(e,t,n);if(t.type==="mdxjsEsm")return cd(e,t);if(t.type==="root")return hd(e,t,n);if(t.type==="text")return fd(e,t)}function ld(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=kr,e.schema=s),e.ancestors.push(t);const i=To(e,t.tagName,!1),o=md(e,t);let a=Tr(e,t);return id.has(t.tagName)&&(a=a.filter(function(l){return typeof l=="string"?!Fc(l):!0})),Co(e,o,i,t),Cr(o,a),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function ud(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)}Mt(e,t.position)}function cd(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Mt(e,t.position)}function dd(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=kr,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:To(e,t.name,!0),o=yd(e,t),a=Tr(e,t);return Co(e,o,i,t),Cr(o,a),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function hd(e,t,n){const r={};return Cr(r,Tr(e,t)),e.create(t,e.Fragment,r,n)}function fd(e,t){return t.value}function Co(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Cr(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function pd(e,t,n){return r;function r(s,i,o,a){const u=Array.isArray(o.children)?n:t;return a?u(i,o,a):u(i,o)}}function gd(e,t){return n;function n(r,s,i,o){const a=Array.isArray(i.children),l=vr(r);return t(s,i,o,a,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function md(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&wr.call(t.properties,s)){const i=xd(e,s,t.properties[s]);if(i){const[o,a]=i;e.tableCellAlignToStyle&&o==="align"&&typeof a=="string"&&od.has(t.tagName)?r=a:n[o]=a}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function yd(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 o=i.expression;o.type;const a=o.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Mt(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 a=r.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else Mt(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function Tr(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:rd;for(;++r<t.children.length;){const i=t.children[r];let o;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;o=l+"-"+u,s.set(l,u+1)}}const a=wo(e,i,o);a!==void 0&&n.push(a)}return n}function xd(e,t,n){const r=Hc(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?Pc(n):Qc(n)),r.property==="style"){let s=typeof n=="object"?n:bd(e,String(n));return e.stylePropertyNameCase==="css"&&(s=Sd(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&r.space?Kc[r.property]||r.property:r.attribute,n]}}function bd(e,t){try{return td(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=vo+"#cannot-parse-style-attribute",s}}function To(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,o;for(;++i<s.length;){const a=Jr(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};o=o?{type:"MemberExpression",object:o,property:a,computed:!!(i&&a.type==="Literal"),optional:!1}:a}r=o}else r=Jr(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const s=r.value;return wr.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(r);Mt(e)}function Mt(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=vo+"#cannot-handle-mdx-estrees-without-createevaluater",n}function Sd(e){const t={};let n;for(n in e)wr.call(e,n)&&(t[kd(n)]=e[n]);return t}function kd(e){let t=e.replace(sd,vd);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function vd(e){return"-"+e.toLowerCase()}const gn={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"]},wd={};function Ir(e,t){const n=wd,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Io(e,r,s)}function Io(e,t,n){if(Cd(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 ls(e.children,t,n)}return Array.isArray(e)?ls(e,t,n):""}function ls(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=Io(e[s],t,n);return r.join("")}function Cd(e){return!!(e&&typeof e=="object")}const us=document.createElement("i");function Mr(e){const t="&"+e+";";us.innerHTML=t;const n=us.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Ce(e,t,n,r){const s=e.length;let i=0,o;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<r.length;)o=r.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function Re(e,t){return e.length>0?(Ce(e,e.length,0,t),e):t}const cs={}.hasOwnProperty;function Mo(e){const t={};let n=-1;for(;++n<e.length;)Td(t,e[n]);return t}function Td(e,t){let n;for(n in t){const s=(cs.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){cs.call(s,o)||(s[o]=[]);const a=i[o];Id(s[o],Array.isArray(a)?a:a?[a]:[])}}}function Id(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);Ce(e,0,0,r)}function Ro(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ne(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ye=Qe(/[A-Za-z]/),ge=Qe(/[\dA-Za-z]/),Md=Qe(/[#-'*+\--9=?A-Z^-~]/);function Wt(e){return e!==null&&(e<32||e===127)}const qn=Qe(/\d/),Rd=Qe(/[\dA-Fa-f]/),Ad=Qe(/[!-/:-@[-`{-~]/);function U(e){return e!==null&&e<-2}function ee(e){return e!==null&&(e<0||e===32)}function Q(e){return e===-2||e===-1||e===32}const rn=Qe(new RegExp("\\p{P}|\\p{S}","u")),et=Qe(/\s/);function Qe(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ht(e){const t=[];let n=-1,r=0,s=0;for(;++n<e.length;){const i=e.charCodeAt(n);let o="";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))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(o=String.fromCharCode(i,a),s=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+s+1,o=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function J(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(l){return Q(l)?(e.enter(n),a(l)):t(l)}function a(l){return Q(l)&&i++<s?(e.consume(l),a):(e.exit(n),t(l))}}const Ed={tokenize:Ld};function Ld(e){const t=e.attempt(this.parser.constructs.contentInitial,r,s);let n;return t;function r(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),J(e,t,"linePrefix")}function s(a){return e.enter("paragraph"),i(a)}function i(a){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,o(a)}function o(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return U(a)?(e.consume(a),e.exit("chunkText"),i):(e.consume(a),o)}}const Nd={tokenize:Pd},ds={tokenize:jd};function Pd(e){const t=this,n=[];let r=0,s,i,o;return a;function a(w){if(r<n.length){const N=n[r];return t.containerState=N[1],e.attempt(N[0].continuation,l,u)(w)}return u(w)}function l(w){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const N=t.events.length;let j=N,T;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){T=t.events[j][1].end;break}g(r);let O=N;for(;O<t.events.length;)t.events[O][1].end={...T},O++;return Ce(t.events,j+1,0,t.events.slice(N)),t.events.length=O,u(w)}return a(w)}function u(w){if(r===n.length){if(!s)return p(w);if(s.currentConstruct&&s.currentConstruct.concrete)return y(w);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(ds,c,d)(w)}function c(w){return s&&v(),g(r),p(w)}function d(w){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,y(w)}function p(w){return t.containerState={},e.attempt(ds,f,y)(w)}function f(w){return r++,n.push([t.currentConstruct,t.containerState]),p(w)}function y(w){if(w===null){s&&v(),g(0),e.consume(w);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),m(w)}function m(w){if(w===null){b(e.exit("chunkFlow"),!0),g(0),e.consume(w);return}return U(w)?(e.consume(w),b(e.exit("chunkFlow")),r=0,t.interrupt=void 0,a):(e.consume(w),m)}function b(w,N){const j=t.sliceStream(w);if(N&&j.push(null),w.previous=i,i&&(i.next=w),i=w,s.defineSkip(w.start),s.write(j),t.parser.lazy[w.start.line]){let T=s.events.length;for(;T--;)if(s.events[T][1].start.offset<o&&(!s.events[T][1].end||s.events[T][1].end.offset>o))return;const O=t.events.length;let B=O,$,C;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){if($){C=t.events[B][1].end;break}$=!0}for(g(r),T=O;T<t.events.length;)t.events[T][1].end={...C},T++;Ce(t.events,B+1,0,t.events.slice(O)),t.events.length=T}}function g(w){let N=n.length;for(;N-- >w;){const j=n[N];t.containerState=j[1],j[0].exit.call(t,e)}n.length=w}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function jd(e,t,n){return J(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ct(e){if(e===null||ee(e)||et(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 Wn={name:"attention",resolveAll:Dd,tokenize:_d};function Dd(e,t){let n=-1,r,s,i,o,a,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};hs(d,-l),hs(p,l),o={type:l>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},a={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:{...o.start},end:{...a.end}},e[r][1].end={...o.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Re(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Re(u,[["enter",s,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=Re(u,sn(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Re(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Re(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,Ce(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 _d(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,s=ct(r);let i;return o;function o(l){return i=l,e.enter("attentionSequence"),a(l)}function a(l){if(l===i)return e.consume(l),a;const u=e.exit("attentionSequence"),c=ct(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 hs(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Od={name:"autolink",tokenize:Fd};function Fd(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 ye(f)?(e.consume(f),o):f===64?n(f):u(f)}function o(f){return f===43||f===45||f===46||ge(f)?(r=1,a(f)):u(f)}function a(f){return f===58?(e.consume(f),r=0,l):(f===43||f===45||f===46||ge(f))&&r++<32?(e.consume(f),a):(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||Wt(f)?n(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),c):Md(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 y=f===45?p:d;return e.consume(f),y}return n(f)}}const Pt={partial:!0,tokenize:zd};function zd(e,t,n){return r;function r(i){return Q(i)?J(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||U(i)?t(i):n(i)}}const Ao={continuation:{tokenize:$d},exit:Kd,name:"blockQuote",tokenize:Bd};function Bd(e,t,n){const r=this;return s;function s(o){if(o===62){const a=r.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return n(o)}function i(o){return Q(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function $d(e,t,n){const r=this;return s;function s(o){return Q(o)?J(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(Ao,t,n)(o)}}function Kd(e){e.exit("blockQuote")}const Eo={name:"characterEscape",tokenize:Ud};function Ud(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 Ad(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const Lo={name:"characterReference",tokenize:Vd};function Vd(e,t,n){const r=this;let s=0,i,o;return a;function a(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,o=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,o=Rd,c):(e.enter("characterReferenceValue"),i=7,o=qn,c(d))}function c(d){if(d===59&&s){const p=e.exit("characterReferenceValue");return o===ge&&!Mr(r.sliceSerialize(p))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(d)&&s++<i?(e.consume(d),c):n(d)}}const fs={partial:!0,tokenize:qd},ps={concrete:!0,name:"codeFenced",tokenize:Hd};function Hd(e,t,n){const r=this,s={partial:!0,tokenize:j};let i=0,o=0,a;return l;function l(T){return u(T)}function u(T){const O=r.events[r.events.length-1];return i=O&&O[1].type==="linePrefix"?O[2].sliceSerialize(O[1],!0).length:0,a=T,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(T)}function c(T){return T===a?(o++,e.consume(T),c):o<3?n(T):(e.exit("codeFencedFenceSequence"),Q(T)?J(e,d,"whitespace")(T):d(T))}function d(T){return T===null||U(T)?(e.exit("codeFencedFence"),r.interrupt?t(T):e.check(fs,m,N)(T)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(T))}function p(T){return T===null||U(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(T)):Q(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),J(e,f,"whitespace")(T)):T===96&&T===a?n(T):(e.consume(T),p)}function f(T){return T===null||U(T)?d(T):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),y(T))}function y(T){return T===null||U(T)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(T)):T===96&&T===a?n(T):(e.consume(T),y)}function m(T){return e.attempt(s,N,b)(T)}function b(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),g}function g(T){return i>0&&Q(T)?J(e,v,"linePrefix",i+1)(T):v(T)}function v(T){return T===null||U(T)?e.check(fs,m,N)(T):(e.enter("codeFlowValue"),w(T))}function w(T){return T===null||U(T)?(e.exit("codeFlowValue"),v(T)):(e.consume(T),w)}function N(T){return e.exit("codeFenced"),t(T)}function j(T,O,B){let $=0;return C;function C(A){return T.enter("lineEnding"),T.consume(A),T.exit("lineEnding"),R}function R(A){return T.enter("codeFencedFence"),Q(A)?J(T,E,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):E(A)}function E(A){return A===a?(T.enter("codeFencedFenceSequence"),z(A)):B(A)}function z(A){return A===a?($++,T.consume(A),z):$>=o?(T.exit("codeFencedFenceSequence"),Q(A)?J(T,_,"whitespace")(A):_(A)):B(A)}function _(A){return A===null||U(A)?(T.exit("codeFencedFence"),O(A)):B(A)}}}function qd(e,t,n){const r=this;return s;function s(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const mn={name:"codeIndented",tokenize:Gd},Wd={partial:!0,tokenize:Qd};function Gd(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),J(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?o(u):n(u)}function o(u){return u===null?l(u):U(u)?e.attempt(Wd,o,l)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||U(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),a)}function l(u){return e.exit("codeIndented"),t(u)}}function Qd(e,t,n){const r=this;return s;function s(o){return r.parser.lazy[r.now().line]?n(o):U(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):J(e,i,"linePrefix",5)(o)}function i(o){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):U(o)?s(o):n(o)}}const Xd={name:"codeText",previous:Jd,resolve:Yd,tokenize:Zd};function Yd(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 Jd(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Zd(e,t,n){let r=0,s,i;return o;function o(d){return e.enter("codeText"),e.enter("codeTextSequence"),a(d)}function a(d){return d===96?(e.consume(d),r++,a):(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)):U(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||U(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 eh{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&&xt(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),xt(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),xt(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);xt(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);xt(this.left,n.reverse())}}}function xt(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 No(e){const t={};let n=-1,r,s,i,o,a,l,u;const c=new eh(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,th(c,n)),n=t[n],u=!0);else if(r[1]._container){for(i=n,s=void 0;i--;)if(o=c.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(s&&(c.get(s)[1].type="lineEndingBlank"),o[1].type="lineEnding",s=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;s&&(r[1].end={...c.get(s)[1].start},a=c.slice(s,n),a.unshift(r),c.splice(s,n-s+1,a))}}return Ce(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function th(e,t){const n=e.get(t)[1],r=e.get(t)[2];let s=t-1;const i=[];let o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,l=[],u={};let c,d,p=-1,f=n,y=0,m=0;const b=[m];for(;f;){for(;e.get(++s)[1]!==f;);i.push(s),f._tokenizer||(c=r.sliceStream(f),f.next||c.push(null),d&&o.defineSkip(f.start),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(c),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++p<a.length;)a[p][0]==="exit"&&a[p-1][0]==="enter"&&a[p][1].type===a[p-1][1].type&&a[p][1].start.line!==a[p][1].end.line&&(m=p+1,b.push(m),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(o.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),p=b.length;p--;){const g=a.slice(b[p],b[p+1]),v=i.pop();l.push([v,v+g.length-1]),e.splice(v,2,g)}for(l.reverse(),p=-1;++p<l.length;)u[y+l[p][0]]=y+l[p][1],y+=l[p][1]-l[p][0]-1;return u}const nh={resolve:sh,tokenize:ih},rh={partial:!0,tokenize:oh};function sh(e){return No(e),e}function ih(e,t){let n;return r;function r(a){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(a)}function s(a){return a===null?i(a):U(a)?e.check(rh,o,i)(a):(e.consume(a),s)}function i(a){return e.exit("chunkContent"),e.exit("content"),t(a)}function o(a){return e.consume(a),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}function oh(e,t,n){const r=this;return s;function s(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),J(e,i,"linePrefix")}function i(o){if(o===null||U(o))return n(o);const a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function Po(e,t,n,r,s,i,o,a,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||Wt(g)?n(g):(e.enter(r),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),m(g))}function p(g){return g===62?(e.enter(i),e.consume(g),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===62?(e.exit("chunkString"),e.exit(a),p(g)):g===null||g===60||U(g)?n(g):(e.consume(g),g===92?y:f)}function y(g){return g===60||g===62||g===92?(e.consume(g),f):f(g)}function m(g){return!c&&(g===null||g===41||ee(g))?(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(r),t(g)):c<u&&g===40?(e.consume(g),c++,m):g===41?(e.consume(g),c--,m):g===null||g===32||g===40||Wt(g)?n(g):(e.consume(g),g===92?b:m)}function b(g){return g===40||g===41||g===92?(e.consume(g),m):m(g)}}function jo(e,t,n,r,s,i){const o=this;let a=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 a>999||f===null||f===91||f===93&&!l||f===94&&!a&&"_hiddenFootnoteSupport"in o.parser.constructs?n(f):f===93?(e.exit(i),e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):U(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||U(f)||a++>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),a++,d):d(f)}}function Do(e,t,n,r,s,i){let o;return a;function a(p){return p===34||p===39||p===40?(e.enter(r),e.enter(s),e.consume(p),e.exit(s),o=p===40?41:p,l):n(p)}function l(p){return p===o?(e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):(e.enter(i),u(p))}function u(p){return p===o?(e.exit(i),l(o)):p===null?n(p):U(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),J(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===o||p===null||U(p)?(e.exit("chunkString"),u(p)):(e.consume(p),p===92?d:c)}function d(p){return p===o||p===92?(e.consume(p),c):c(p)}}function Ct(e,t){let n;return r;function r(s){return U(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):Q(s)?J(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const ah={name:"definition",tokenize:uh},lh={partial:!0,tokenize:ch};function uh(e,t,n){const r=this;let s;return i;function i(f){return e.enter("definition"),o(f)}function o(f){return jo.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function a(f){return s=Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):n(f)}function l(f){return ee(f)?Ct(e,u)(f):u(f)}function u(f){return Po(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(lh,d,d)(f)}function d(f){return Q(f)?J(e,p,"whitespace")(f):p(f)}function p(f){return f===null||U(f)?(e.exit("definition"),r.parser.defined.push(s),t(f)):n(f)}}function ch(e,t,n){return r;function r(a){return ee(a)?Ct(e,s)(a):n(a)}function s(a){return Do(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return Q(a)?J(e,o,"whitespace")(a):o(a)}function o(a){return a===null||U(a)?t(a):n(a)}}const dh={name:"hardBreakEscape",tokenize:hh};function hh(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return U(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const fh={name:"headingAtx",resolve:ph,tokenize:gh};function ph(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"},Ce(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function gh(e,t,n){let r=0;return s;function s(c){return e.enter("atxHeading"),i(c)}function i(c){return e.enter("atxHeadingSequence"),o(c)}function o(c){return c===35&&r++<6?(e.consume(c),o):c===null||ee(c)?(e.exit("atxHeadingSequence"),a(c)):n(c)}function a(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||U(c)?(e.exit("atxHeading"),t(c)):Q(c)?J(e,a,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),a(c))}function u(c){return c===null||c===35||ee(c)?(e.exit("atxHeadingText"),a(c)):(e.consume(c),u)}}const mh=["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"],gs=["pre","script","style","textarea"],yh={concrete:!0,name:"htmlFlow",resolveTo:Sh,tokenize:kh},xh={partial:!0,tokenize:wh},bh={partial:!0,tokenize:vh};function Sh(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 kh(e,t,n){const r=this;let s,i,o,a,l;return u;function u(S){return c(S)}function c(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),d}function d(S){return S===33?(e.consume(S),p):S===47?(e.consume(S),i=!0,m):S===63?(e.consume(S),s=3,r.interrupt?t:x):ye(S)?(e.consume(S),o=String.fromCharCode(S),b):n(S)}function p(S){return S===45?(e.consume(S),s=2,f):S===91?(e.consume(S),s=5,a=0,y):ye(S)?(e.consume(S),s=4,r.interrupt?t:x):n(S)}function f(S){return S===45?(e.consume(S),r.interrupt?t:x):n(S)}function y(S){const he="CDATA[";return S===he.charCodeAt(a++)?(e.consume(S),a===he.length?r.interrupt?t:E:y):n(S)}function m(S){return ye(S)?(e.consume(S),o=String.fromCharCode(S),b):n(S)}function b(S){if(S===null||S===47||S===62||ee(S)){const he=S===47,ke=o.toLowerCase();return!he&&!i&&gs.includes(ke)?(s=1,r.interrupt?t(S):E(S)):mh.includes(o.toLowerCase())?(s=6,he?(e.consume(S),g):r.interrupt?t(S):E(S)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(S):i?v(S):w(S))}return S===45||ge(S)?(e.consume(S),o+=String.fromCharCode(S),b):n(S)}function g(S){return S===62?(e.consume(S),r.interrupt?t:E):n(S)}function v(S){return Q(S)?(e.consume(S),v):C(S)}function w(S){return S===47?(e.consume(S),C):S===58||S===95||ye(S)?(e.consume(S),N):Q(S)?(e.consume(S),w):C(S)}function N(S){return S===45||S===46||S===58||S===95||ge(S)?(e.consume(S),N):j(S)}function j(S){return S===61?(e.consume(S),T):Q(S)?(e.consume(S),j):w(S)}function T(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),l=S,O):Q(S)?(e.consume(S),T):B(S)}function O(S){return S===l?(e.consume(S),l=null,$):S===null||U(S)?n(S):(e.consume(S),O)}function B(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||ee(S)?j(S):(e.consume(S),B)}function $(S){return S===47||S===62||Q(S)?w(S):n(S)}function C(S){return S===62?(e.consume(S),R):n(S)}function R(S){return S===null||U(S)?E(S):Q(S)?(e.consume(S),R):n(S)}function E(S){return S===45&&s===2?(e.consume(S),K):S===60&&s===1?(e.consume(S),L):S===62&&s===4?(e.consume(S),oe):S===63&&s===3?(e.consume(S),x):S===93&&s===5?(e.consume(S),ae):U(S)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(xh,re,z)(S)):S===null||U(S)?(e.exit("htmlFlowData"),z(S)):(e.consume(S),E)}function z(S){return e.check(bh,_,re)(S)}function _(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),A}function A(S){return S===null||U(S)?z(S):(e.enter("htmlFlowData"),E(S))}function K(S){return S===45?(e.consume(S),x):E(S)}function L(S){return S===47?(e.consume(S),o="",G):E(S)}function G(S){if(S===62){const he=o.toLowerCase();return gs.includes(he)?(e.consume(S),oe):E(S)}return ye(S)&&o.length<8?(e.consume(S),o+=String.fromCharCode(S),G):E(S)}function ae(S){return S===93?(e.consume(S),x):E(S)}function x(S){return S===62?(e.consume(S),oe):S===45&&s===2?(e.consume(S),x):E(S)}function oe(S){return S===null||U(S)?(e.exit("htmlFlowData"),re(S)):(e.consume(S),oe)}function re(S){return e.exit("htmlFlow"),t(S)}}function vh(e,t,n){const r=this;return s;function s(o){return U(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):n(o)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function wh(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Pt,t,n)}}const Ch={name:"htmlText",tokenize:Th};function Th(e,t,n){const r=this;let s,i,o;return a;function a(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),j):x===63?(e.consume(x),w):ye(x)?(e.consume(x),B):n(x)}function u(x){return x===45?(e.consume(x),c):x===91?(e.consume(x),i=0,y):ye(x)?(e.consume(x),v):n(x)}function c(x){return x===45?(e.consume(x),f):n(x)}function d(x){return x===null?n(x):x===45?(e.consume(x),p):U(x)?(o=d,L(x)):(e.consume(x),d)}function p(x){return x===45?(e.consume(x),f):d(x)}function f(x){return x===62?K(x):x===45?p(x):d(x)}function y(x){const oe="CDATA[";return x===oe.charCodeAt(i++)?(e.consume(x),i===oe.length?m:y):n(x)}function m(x){return x===null?n(x):x===93?(e.consume(x),b):U(x)?(o=m,L(x)):(e.consume(x),m)}function b(x){return x===93?(e.consume(x),g):m(x)}function g(x){return x===62?K(x):x===93?(e.consume(x),g):m(x)}function v(x){return x===null||x===62?K(x):U(x)?(o=v,L(x)):(e.consume(x),v)}function w(x){return x===null?n(x):x===63?(e.consume(x),N):U(x)?(o=w,L(x)):(e.consume(x),w)}function N(x){return x===62?K(x):w(x)}function j(x){return ye(x)?(e.consume(x),T):n(x)}function T(x){return x===45||ge(x)?(e.consume(x),T):O(x)}function O(x){return U(x)?(o=O,L(x)):Q(x)?(e.consume(x),O):K(x)}function B(x){return x===45||ge(x)?(e.consume(x),B):x===47||x===62||ee(x)?$(x):n(x)}function $(x){return x===47?(e.consume(x),K):x===58||x===95||ye(x)?(e.consume(x),C):U(x)?(o=$,L(x)):Q(x)?(e.consume(x),$):K(x)}function C(x){return x===45||x===46||x===58||x===95||ge(x)?(e.consume(x),C):R(x)}function R(x){return x===61?(e.consume(x),E):U(x)?(o=R,L(x)):Q(x)?(e.consume(x),R):$(x)}function E(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),s=x,z):U(x)?(o=E,L(x)):Q(x)?(e.consume(x),E):(e.consume(x),_)}function z(x){return x===s?(e.consume(x),s=void 0,A):x===null?n(x):U(x)?(o=z,L(x)):(e.consume(x),z)}function _(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||ee(x)?$(x):(e.consume(x),_)}function A(x){return x===47||x===62||ee(x)?$(x):n(x)}function K(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function L(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),G}function G(x){return Q(x)?J(e,ae,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):ae(x)}function ae(x){return e.enter("htmlTextData"),o(x)}}const Rr={name:"labelEnd",resolveAll:Ah,resolveTo:Eh,tokenize:Lh},Ih={tokenize:Nh},Mh={tokenize:Ph},Rh={tokenize:jh};function Ah(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&&Ce(e,0,e.length,n),e}function Eh(e,t){let n=e.length,r=0,s,i,o,a;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(o){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"&&(o=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[o][1].end}},c={type:"labelText",start:{...e[i+r+2][1].end},end:{...e[o-2][1].start}};return a=[["enter",l,t],["enter",u,t]],a=Re(a,e.slice(i+1,i+r+3)),a=Re(a,[["enter",c,t]]),a=Re(a,sn(t.parser.constructs.insideSpan.null,e.slice(i+r+4,o-3),t)),a=Re(a,[["exit",c,t],e[o-2],e[o-1],["exit",u,t]]),a=Re(a,e.slice(o+1)),a=Re(a,[["exit",l,t]]),Ce(e,i,e.length,a),e}function Lh(e,t,n){const r=this;let s=r.events.length,i,o;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 a;function a(p){return i?i._inactive?d(p):(o=r.parser.defined.includes(Ne(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),l):n(p)}function l(p){return p===40?e.attempt(Ih,c,o?c:d)(p):p===91?e.attempt(Mh,c,o?u:d)(p):o?c(p):d(p)}function u(p){return e.attempt(Rh,c,d)(p)}function c(p){return t(p)}function d(p){return i._balanced=!0,n(p)}}function Nh(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 ee(d)?Ct(e,i)(d):i(d)}function i(d){return d===41?c(d):Po(e,o,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function o(d){return ee(d)?Ct(e,l)(d):c(d)}function a(d){return n(d)}function l(d){return d===34||d===39||d===40?Do(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return ee(d)?Ct(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 Ph(e,t,n){const r=this;return s;function s(a){return jo.call(r,e,i,o,"reference","referenceMarker","referenceString")(a)}function i(a){return r.parser.defined.includes(Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(a):n(a)}function o(a){return n(a)}}function jh(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 Dh={name:"labelStartImage",resolveAll:Rr.resolveAll,tokenize:_h};function _h(e,t,n){const r=this;return s;function s(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),i}function i(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),o):n(a)}function o(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const Oh={name:"labelStartLink",resolveAll:Rr.resolveAll,tokenize:Fh};function Fh(e,t,n){const r=this;return s;function s(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const yn={name:"lineEnding",tokenize:zh};function zh(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),J(e,t,"linePrefix")}}const Vt={name:"thematicBreak",tokenize:Bh};function Bh(e,t,n){let r=0,s;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return s=u,a(u)}function a(u){return u===s?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||U(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===s?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),Q(u)?J(e,a,"whitespace")(u):a(u))}}const be={continuation:{tokenize:Vh},exit:qh,name:"list",tokenize:Uh},$h={partial:!0,tokenize:Wh},Kh={partial:!0,tokenize:Hh};function Uh(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,o=0;return a;function a(f){const y=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:qn(f)){if(r.containerState.type||(r.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Vt,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 qn(f)&&++o<10?(e.consume(f),l):(!r.interrupt||o<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(Pt,r.interrupt?n:c,e.attempt($h,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 Vh(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Pt,s,i);function s(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,J(e,t,"listItemIndent",r.containerState.size+1)(a)}function i(a){return r.containerState.furtherBlankLines||!Q(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Kh,t,o)(a))}function o(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,J(e,e.attempt(be,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function Hh(e,t,n){const r=this;return J(e,s,"listItemIndent",r.containerState.size+1);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(i):n(i)}}function qh(e){e.exit(this.containerState.type)}function Wh(e,t,n){const r=this;return J(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const o=r.events[r.events.length-1];return!Q(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const ms={name:"setextUnderline",resolveTo:Gh,tokenize:Qh};function Gh(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 o={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",o,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function Qh(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,o(u)):n(u)}function o(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===s?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),Q(u)?J(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||U(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Xh={tokenize:Yh};function Yh(e){const t=this,n=e.attempt(Pt,r,e.attempt(this.parser.constructs.flowInitial,s,J(e,e.attempt(this.parser.constructs.flow,s,e.attempt(nh,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 Jh={resolveAll:Oo()},Zh=_o("string"),ef=_o("text");function _o(e){return{resolveAll:Oo(e==="text"?tf:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,o,a);return o;function o(c){return u(c)?i(c):a(c)}function a(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 Oo(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 tf(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,o=-1,a=0,l;for(;i--;){const u=s[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)a++,o--;if(o)break;o=-1}else if(u===-2)l=!0,a++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(a=0),a){const u={type:n===e.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:r.start._bufferIndex+o,_index:r.start._index+i,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},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 nf={42:be,43:be,45:be,48:be,49:be,50:be,51:be,52:be,53:be,54:be,55:be,56:be,57:be,62:Ao},rf={91:ah},sf={[-2]:mn,[-1]:mn,32:mn},of={35:fh,42:Vt,45:[ms,Vt],60:yh,61:ms,95:Vt,96:ps,126:ps},af={38:Lo,92:Eo},lf={[-5]:yn,[-4]:yn,[-3]:yn,33:Dh,38:Lo,42:Wn,60:[Od,Ch],91:Oh,92:[dh,Eo],93:Rr,95:Wn,96:Xd},uf={null:[Wn,Jh]},cf={null:[42,95]},df={null:[]},hf=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:cf,contentInitial:rf,disable:df,document:nf,flow:of,flowInitial:sf,insideSpan:uf,string:af,text:lf},Symbol.toStringTag,{value:"Module"}));function ff(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 o=[],a=[];const l={attempt:O(j),check:O(T),consume:v,enter:w,exit:N,interrupt:O(T,{interrupt:!0})},u={code:null,containerState:{},defineSkip:m,events:[],now:y,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(R){return o=Re(o,R),b(),o[o.length-1]!==null?[]:(B(t,0),u.events=sn(i,u.events,u),u.events)}function p(R,E){return gf(f(R),E)}function f(R){return pf(o,R)}function y(){const{_bufferIndex:R,_index:E,line:z,column:_,offset:A}=r;return{_bufferIndex:R,_index:E,line:z,column:_,offset:A}}function m(R){s[R.line]=R.column,C()}function b(){let R;for(;r._index<o.length;){const E=o[r._index];if(typeof E=="string")for(R=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===R&&r._bufferIndex<E.length;)g(E.charCodeAt(r._bufferIndex));else g(E)}}function g(R){c=c(R)}function v(R){U(R)?(r.line++,r.column=1,r.offset+=R===-3?2:1,C()):R!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=R}function w(R,E){const z=E||{};return z.type=R,z.start=y(),u.events.push(["enter",z,u]),a.push(z),z}function N(R){const E=a.pop();return E.end=y(),u.events.push(["exit",E,u]),E}function j(R,E){B(R,E.from)}function T(R,E){E.restore()}function O(R,E){return z;function z(_,A,K){let L,G,ae,x;return Array.isArray(_)?re(_):"tokenize"in _?re([_]):oe(_);function oe(se){return pe;function pe(xe){const Te=xe!==null&&se[xe],Ie=xe!==null&&se.null,Pe=[...Array.isArray(Te)?Te:Te?[Te]:[],...Array.isArray(Ie)?Ie:Ie?[Ie]:[]];return re(Pe)(xe)}}function re(se){return L=se,G=0,se.length===0?K:S(se[G])}function S(se){return pe;function pe(xe){return x=$(),ae=se,se.partial||(u.currentConstruct=se),se.name&&u.parser.constructs.disable.null.includes(se.name)?ke():se.tokenize.call(E?Object.assign(Object.create(u),E):u,l,he,ke)(xe)}}function he(se){return R(ae,x),A}function ke(se){return x.restore(),++G<L.length?S(L[G]):K}}}function B(R,E){R.resolveAll&&!i.includes(R)&&i.push(R),R.resolve&&Ce(u.events,E,u.events.length-E,R.resolve(u.events.slice(E),u)),R.resolveTo&&(u.events=R.resolveTo(u.events,u))}function $(){const R=y(),E=u.previous,z=u.currentConstruct,_=u.events.length,A=Array.from(a);return{from:_,restore:K};function K(){r=R,u.previous=E,u.currentConstruct=z,u.events.length=_,a=A,C()}}function C(){r.line in s&&r.column<2&&(r.column=s[r.line],r.offset+=s[r.line]-1)}}function pf(e,t){const n=t.start._index,r=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let o;if(n===s)o=[e[n].slice(r,i)];else{if(o=e.slice(n,s),r>-1){const a=o[0];typeof a=="string"?o[0]=a.slice(r):o.shift()}i>0&&o.push(e[s].slice(0,i))}return o}function gf(e,t){let n=-1;const r=[];let s;for(;++n<e.length;){const i=e[n];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
|
|
1
|
+
var Wa=Object.defineProperty;var Qa=(e,t,n)=>t in e?Wa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var F=(e,t,n)=>Qa(e,typeof t!="symbol"?t+"":t,n);import{r as k,j as h,ae as Ga,v as Jt,X as Xa,af as Ya,f as Ja,e as kt,t as Za,c as el,y as tl,z as nl,h as yi,I as rl,i as ur,n as sl,o as xi,V as il,q as bi,s as ol,w as al,k as Si,l as ll,m as ki,a as ul,ag as cl,B as cr,G as dr,ah as dl,ai as hl,aj as fl,F as pl,ak as gl,al as ml,_ as vi,am as wi,an as Ci,ao as yl,ap as xl,aq as bl,ar as Sl,as as kl,at as vl,d as Zt,a4 as en,au as wl,A as hr,av as Cl,a0 as Tl,a3 as Il,a1 as Ml,a2 as Rl,aw as On,ax as Fn,ay as zn,az as At,M as Al,aA as Ti,aB as El,aC as Ll,aD as Nl,aE as Ii,aF as Mi,u as Pl}from"./vendor-CNhxtHCf.js";import{u as fr}from"./useConfirmDialog-DTducNfn.js";import{i as jl,t as I,u as Ri,a as Ai,j as Dl,k as _l,l as Ol,m as Fl,c as Le,I as pr,B as Ve,n as tn,o as Ei,p as Bn,q as zl,r as Bl,s as gr,v as $l,T as Br,L as $r,w as Kl,x as Kr,y as Ul,z as Ur,h as vt,A as Li,E as Vl,F as Hl,G as ql,H as Wl,S as Ql,e as Gl,f as Xl,g as Yl,C as Jl,J as Zl,K as eu,M as Ni,N as tu,O as nu,P as ru,Q as su,R as iu,U as ou}from"./index-BulnQWr6.js";import{b as au,a as lu,S as uu,s as cu,c as Vr,e as Hr}from"./chat-message-BbuIK4dQ.js";import{u as Pi,T as du,a as hu,b as fu,c as pu,P as gu,R as mu,d as yu,e as xu,C as ji,M as bu}from"./MarketplacePage-inGGiv1T.js";import{b as Di,c as _i,r as Oi}from"./provider-models-BOeNnjk9.js";import{R as Su,A as ku,P as vu,C as Fi,T as wu,a as Cu,b as Tu,c as Iu}from"./popover-DjaScZDJ.js";import{P as Mu,a as Ru}from"./page-layout-DF0xpax2.js";import"./tabs-custom-BG9y2JhC.js";import"./skeleton-DycBJAJF.js";import"./marketplace-localization-Dk31LJJJ.js";const Au="ncp";function qr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="legacy"||t==="ncp"?t:null}function zi(e){const t=qr(new URLSearchParams(e).get("chatChain"));return t||(qr(void 0)??Au)}function Eu(e){var v;const{view:t,selectedSessionKey:n,activeBackendRunId:r,isLocallyRunning:s,resumeRun:i}=e,[o,a]=k.useState(null),l=k.useRef(!1),u=k.useRef(new Map),c=k.useRef(new Map),d=k.useRef(new Map),p=k.useRef(r),f=k.useRef(new Set);k.useEffect(()=>{n&&f.current.add(n)},[n]),k.useEffect(()=>{n&&s&&f.current.delete(n)},[s,n]);const y=jl(t==="chat"?{states:["queued","running"],limit:200,syncActiveStates:!0,isLocallyRunning:s}:void 0),m=k.useMemo(()=>{var w;return au(((w=y.data)==null?void 0:w.runs)??[])},[(v=y.data)==null?void 0:v.runs]),b=k.useMemo(()=>{const w=lu(m);if(o){const N=m.get(o.sessionKey)??null;N&&(!o.runId||N.runId===o.runId)&&w.delete(o.sessionKey)}return w},[m,o]),g=k.useMemo(()=>{if(!n)return null;const w=m.get(n)??null;return(!w||!o||o.sessionKey!==n?!1:!o.runId||w.runId===o.runId)?null:w},[m,n,o]);return k.useEffect(()=>{r&&(p.current=r)},[r]),k.useEffect(()=>{if(t!=="chat"||!n||!g||!f.current.has(n)||s||r===g.runId||u.current.get(n)===g.runId)return;const N=c.current.get(n);if(N&&N===g.runId)return;const j=d.current.get(n);if(typeof j=="number"){const T=Date.parse(g.requestedAt??"");if(Number.isFinite(T)){if(T<=j+2e3)return}else if(Date.now()-j<=8e3)return}u.current.set(n,g.runId),f.current.delete(n),i(g)},[r,g,s,i,n,t]),k.useEffect(()=>{if(!n){u.current.clear(),c.current.clear(),d.current.clear(),f.current.clear();return}m.has(n)||(u.current.delete(n),c.current.delete(n),d.current.delete(n))},[m,n]),k.useEffect(()=>{var N,j,T;const w=l.current;if(l.current=s,!s&&w&&n){const O=((N=p.current)==null?void 0:N.trim())||((T=(j=m.get(n))==null?void 0:j.runId)==null?void 0:T.trim());O&&c.current.set(n,O),d.current.set(n,Date.now()),a({sessionKey:n,...O?{runId:O}:{}}),y.refetch()}},[m,s,n,y]),k.useEffect(()=>{if(!o)return;const w=m.get(o.sessionKey)??null;if(!w){a(null);return}o.runId&&w.runId!==o.runId&&a(null)},[m,o]),k.useEffect(()=>{s&&(o==null?void 0:o.sessionKey)===n&&a(null)},[s,n,o]),{sessionRunStatusByKey:b}}const Me="native";function Oe(e){return typeof e!="string"?Me:e.trim().toLowerCase()||Me}function lt(e,t){return e==="native"?I("chatSessionTypeNative"):e.trim().split(/[-_]+/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")||e}function Lu(e){var n;const t=new Map;for(const r of e){const s=Oe(r.value);t.set(s,{value:s,label:((n=r.label)==null?void 0:n.trim())||lt(s),ready:r.ready??!0,reason:r.reason??null,reasonMessage:r.reasonMessage??null,supportedModels:r.supportedModels,recommendedModel:r.recommendedModel??null,cta:r.cta??null})}return t.has(Me)||t.set(Me,{value:Me,label:lt(Me),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((r,s)=>r.value===Me?-1:s.value===Me?1:r.value.localeCompare(s.value))}function Bi(e){const{selectedSession:t,selectedSessionKey:n,pendingSessionType:r,setPendingSessionType:s,sessionTypesData:i}=e,o=k.useMemo(()=>Lu((i==null?void 0:i.options)??[]),[i==null?void 0:i.options]),a=k.useMemo(()=>{const b=[...o],g=Oe(t==null?void 0:t.sessionType);return b.some(v=>v.value===g)||b.push({value:g,label:lt(g),ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),b.sort((v,w)=>v.value===Me?-1:w.value===Me?1:v.value.localeCompare(w.value))},[o,t==null?void 0:t.sessionType]),l=k.useMemo(()=>Oe((i==null?void 0:i.defaultType)??Me),[i==null?void 0:i.defaultType]),u=k.useRef(null),c=k.useMemo(()=>Oe((t==null?void 0:t.sessionType)??r??l),[l,r,t==null?void 0:t.sessionType]),d=k.useMemo(()=>a.find(b=>b.value===c)??null,[c,a]);k.useEffect(()=>{if(n)return;const b=typeof r=="string"?r.trim():"",g=Oe(r);(b.length===0||u.current===g||u.current===null&&g===Me)&&(u.current=l,g!==l&&s(l))},[l,r,n,s]);const p=!n||!!(t!=null&&t.sessionTypeMutable),f=k.useMemo(()=>new Set(o.map(b=>b.value)),[o]),y=k.useMemo(()=>t&&!f.has(Oe(t.sessionType))?!0:(d==null?void 0:d.ready)===!1,[f,t,d==null?void 0:d.ready]),m=k.useMemo(()=>{var b;return t&&!f.has(Oe(t.sessionType))?`${lt(c)} ${I("chatSessionTypeUnavailableSuffix")}`:(d==null?void 0:d.ready)===!1?((b=d.reasonMessage)==null?void 0:b.trim())||`${d.label} setup required`:null},[f,t,c,d]);return{sessionTypeOptions:a,selectedSessionTypeOption:d,defaultSessionType:l,selectedSessionType:c,canEditSessionType:p,sessionTypeUnavailable:y,sessionTypeUnavailableMessage:m}}function Wr(e){return(e==null?void 0:e.trim().toLowerCase())||"native"}function Nu(e,t){if(typeof t!="string")return!1;const n=t.trim();return n?e.some(r=>r.value===n):!1}function Pu(e,t){return typeof t=="string"&&e.includes(t)}function ju(e){return e.length===0?null:e.includes("off")?"off":e[0]??null}function $i(e){const{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:s,isValueSupported:i,firstAvailableValue:o,preferSessionPreferredValue:a=!1,preserveCurrentValueOnSessionChange:l=!1}=e;return i(t)&&(!a||l)?t:i(n)?n:i(r)?r:i(s)?s:o}function Du(e){var n;const{modelOptions:t}=e;return t.length===0?"":$i({currentValue:e.currentSelectedModel,selectedSessionPreferredValue:e.selectedSessionPreferredModel,fallbackPreferredValue:e.fallbackPreferredModel,defaultValue:e.defaultModel,isValueSupported:r=>Nu(t,r),firstAvailableValue:((n=t[0])==null?void 0:n.value)??"",preferSessionPreferredValue:e.preferSessionPreferredModel,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedModelOnSessionChange})}function _u(e){const{supportedThinkingLevels:t}=e;return t.length===0?null:$i({currentValue:e.currentSelectedThinkingLevel,selectedSessionPreferredValue:e.selectedSessionPreferredThinking,fallbackPreferredValue:e.fallbackPreferredThinking,defaultValue:e.defaultThinkingLevel,isValueSupported:n=>Pu(t,n),firstAvailableValue:ju(t)??"off",preferSessionPreferredValue:e.preferSessionPreferredThinking,preserveCurrentValueOnSessionChange:e.preserveCurrentSelectedThinkingOnSessionChange})}function Ki(e){const t=Wr(e.sessionType);let n,r=Number.NEGATIVE_INFINITY;for(const s of e.sessions){if(s.key===e.selectedSessionKey||Wr(s.sessionType)!==t)continue;const i=e.readPreference(s);if(i==null)continue;const o=Date.parse(s.updatedAt),a=Number.isFinite(o)?o:Number.NEGATIVE_INFINITY;(n===void 0||a>r)&&(n=i,r=a)}return n}function Ui(e){return Ki({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>{var r;return((r=t.preferredModel)==null?void 0:r.trim())||void 0}})}function Vi(e){return Ki({sessions:e.sessions,selectedSessionKey:e.selectedSessionKey,sessionType:e.sessionType,readPreference:t=>t.preferredThinking??void 0})}function Hi(e){const{isPreferenceAvailable:t,emptyValue:n,selectedSessionKey:r,selectedSessionExists:s=!1,setValue:i,resolveValue:o}=e,a=k.useRef(void 0),l=k.useRef(o);k.useEffect(()=>{l.current=o},[o]),k.useEffect(()=>{const u=a.current!==r;if(!t){i(n),a.current=r;return}i(c=>l.current({currentValue:c,sessionChanged:u,preserveCurrentValueOnSessionChange:u&&!!r&&!s})),a.current=r},[n,t,s,r,i])}function qi(e){const{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,setSelectedModel:a}=e;Hi({isPreferenceAvailable:t.length>0,emptyValue:"",selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>Du({currentSelectedModel:l,modelOptions:t,selectedSessionPreferredModel:s,fallbackPreferredModel:i,defaultModel:o,preferSessionPreferredModel:u,preserveCurrentSelectedModelOnSessionChange:c})})}function Wi(e){const{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,setSelectedThinkingLevel:a}=e;Hi({isPreferenceAvailable:t.length>0,emptyValue:null,selectedSessionKey:n,selectedSessionExists:r,setValue:a,resolveValue:({currentValue:l,sessionChanged:u,preserveCurrentValueOnSessionChange:c})=>_u({currentSelectedThinkingLevel:l,supportedThinkingLevels:t,selectedSessionPreferredThinking:s,fallbackPreferredThinking:i,defaultThinkingLevel:o,preferSessionPreferredThinking:u,preserveCurrentSelectedThinkingOnSessionChange:c})})}function Ou(e){var N,j,T,O,B,$;const t=Ri(),n=Ai(),r=Dl({q:e.query.trim()||void 0,limit:120,activeMinutes:0}),s=Pi("skill"),i=_l({sessionKey:e.selectedSessionKey,agentId:e.selectedAgentId}),o=Ol(e.selectedSessionKey,300),a=Fl(),l=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),u=k.useMemo(()=>{const C=Di({meta:n.data,config:t.data,onlyConfigured:!0}),R=new Set,E=[];for(const z of C)for(const _ of z.models){const A=_i(z.prefix,_);!A||R.has(A)||(R.add(A),E.push({value:A,modelLabel:_,providerLabel:z.displayName,thinkingCapability:Oi(z.modelThinking,_,z.aliases)}))}return E.sort((z,_)=>{const A=z.providerLabel.localeCompare(_.providerLabel);return A!==0?A:z.modelLabel.localeCompare(_.modelLabel)})},[n.data,t.data]),c=k.useMemo(()=>{var C;return((C=r.data)==null?void 0:C.sessions)??[]},[(N=r.data)==null?void 0:N.sessions]),d=k.useMemo(()=>{var C;return((C=s.data)==null?void 0:C.records)??[]},[(j=s.data)==null?void 0:j.records]),p=k.useMemo(()=>c.find(C=>C.key===e.selectedSessionKey)??null,[e.selectedSessionKey,c]),f=Bi({selectedSession:p,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:a.data}),y=k.useMemo(()=>Ui({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]),m=k.useMemo(()=>u.find(C=>C.value===e.currentSelectedModel),[u,e.currentSelectedModel]),b=k.useMemo(()=>{var C;return((C=m==null?void 0:m.thinkingCapability)==null?void 0:C.supported)??[]},[(T=m==null?void 0:m.thinkingCapability)==null?void 0:T.supported]),g=k.useMemo(()=>{var C;return((C=m==null?void 0:m.thinkingCapability)==null?void 0:C.default)??null},[(O=m==null?void 0:m.thinkingCapability)==null?void 0:O.default]),v=k.useMemo(()=>Vi({sessions:c,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[e.selectedSessionKey,f.selectedSessionType,c]);qi({modelOptions:u,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredModel:p==null?void 0:p.preferredModel,fallbackPreferredModel:y,defaultModel:(B=t.data)==null?void 0:B.agents.defaults.model,setSelectedModel:e.setSelectedModel}),Wi({supportedThinkingLevels:b,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!p,selectedSessionPreferredThinking:(p==null?void 0:p.preferredThinking)??null,fallbackPreferredThinking:v??null,defaultThinkingLevel:g,setSelectedThinkingLevel:e.setSelectedThinkingLevel});const w=k.useMemo(()=>{var C;return((C=o.data)==null?void 0:C.messages)??[]},[($=o.data)==null?void 0:$.messages]);return{configQuery:t,configMetaQuery:n,sessionsQuery:r,installedSkillsQuery:s,chatCapabilitiesQuery:i,historyQuery:o,sessionTypesQuery:a,isProviderStateResolved:l,modelOptions:u,sessions:c,skillRecords:d,selectedSession:p,historyMessages:w,...f}}function Qi(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}const Fu={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 zu({status:e,className:t}){const n=Fu[e],r=e==="connected"?I("connected"):e==="disconnected"?I("disconnected"):I("connecting");return h.jsx(du,{delayDuration:250,children:h.jsxs(hu,{children:[h.jsx(fu,{asChild:!0,children:h.jsx("span",{role:"status","aria-label":r,className:Le("inline-flex h-5 w-5 items-center justify-center",t),children:e==="connecting"?h.jsx(Ga,{className:Le("h-3 w-3 animate-spin",n.dotClass)}):h.jsx("span",{className:Le(e==="connected"?"h-2 w-2 rounded-full":"",n.dotClass)})})}),h.jsx(pu,{side:"bottom",className:"text-xs",children:r})]})})}function Bu(e){const{session:t,active:n,runStatus:r,sessionTypeLabel:s,title:i,isEditing:o,draftLabel:a,isSaving:l,onSelect:u,onStartEditing:c,onDraftLabelChange:d,onSave:p,onCancel:f}=e;return h.jsx("div",{className:Le("w-full rounded-xl px-3 py-2 text-left transition-all text-[13px]",n?"bg-gray-200 text-gray-900 font-semibold shadow-sm":"text-gray-700 hover:bg-gray-200/60 hover:text-gray-900"),children:o?h.jsxs("div",{className:"space-y-2",children:[h.jsx(pr,{value:a,onChange:y=>d(y.target.value),onKeyDown:y=>{y.key==="Enter"?(y.preventDefault(),p()):y.key==="Escape"&&(y.preventDefault(),f())},placeholder:I("sessionsLabelPlaceholder"),className:"h-8 rounded-lg border-gray-300 bg-white text-xs",autoFocus:!0,disabled:l}),h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("div",{className:"min-w-0 text-[11px] text-gray-400 truncate",children:t.key}),h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx(Ve,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:()=>void p(),disabled:l,"aria-label":I("save"),children:h.jsx(Jt,{className:"h-3.5 w-3.5"})}),h.jsx(Ve,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",onClick:f,disabled:l,"aria-label":I("cancel"),children:h.jsx(Xa,{className:"h-3.5 w-3.5"})})]})]})]}):h.jsxs("div",{className:"group/session relative",children:[h.jsxs("button",{type:"button",onClick:u,className:"w-full text-left",children:[h.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_0.875rem] items-center gap-1.5 pr-8",children:[h.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[h.jsx("span",{className:"truncate font-medium",children:i}),s?h.jsx("span",{className:Le("shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none",n?"border-gray-300 bg-white/80 text-gray-700":"border-gray-200 bg-gray-100 text-gray-500"),children:s}):null]}),h.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:r?h.jsx(uu,{status:r}):null})]}),h.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-400 truncate",children:[t.messageCount," · ",tn(t.updatedAt)]})]}),h.jsx("button",{type:"button",onClick:y=>{y.stopPropagation(),c()},className:Le("absolute right-0 top-0 inline-flex h-7 w-7 items-center justify-center rounded-lg text-gray-400 transition-all hover:bg-white hover:text-gray-900",n?"opacity-100":"opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100"),"aria-label":I("edit"),children:h.jsx(Ya,{className:"h-3.5 w-3.5"})})]})})}function $u(){const e=Ja();return async t=>{try{t.chatChain==="ncp"?(await Ei(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["ncp-sessions"]}),e.invalidateQueries({queryKey:["ncp-session-messages",t.sessionKey]})):(await Bn(t.sessionKey,{label:t.label}),e.invalidateQueries({queryKey:["sessions"]}),e.invalidateQueries({queryKey:["session-history",t.sessionKey]})),kt.success(I("configSavedApplied"))}catch(n){throw kt.error(I("configSaveFailed")+": "+(n instanceof Error?n.message:String(n))),n}}}const Gi=k.createContext(null);function Xi({presenter:e,children:t}){return h.jsx(Gi.Provider,{value:e,children:t})}function mr(){const e=k.useContext(Gi);if(!e)throw new Error("usePresenter must be used inside ChatPresenterProvider");return e}const Ku=e=>`[data-item-index="${e}"]`;function Yi(e){const t=e.getItemSelector??Ku;k.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 Uu(){const e=k.useRef(null),[t,n]=k.useState(null);return k.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 de(...e){return Za(el(e))}const Ji=k.forwardRef(({className:e,type:t,...n},r)=>h.jsx("input",{type:t,className:de("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}));Ji.displayName="ChatInput";const Vu=Su,Hu=wu,qu=ku,Zi=k.forwardRef(({className:e,sideOffset:t=8,align:n="start",...r},s)=>h.jsx(vu,{children:h.jsx(Fi,{ref:s,sideOffset:t,align:n,className:de("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})}));Zi.displayName=Fi.displayName;const Wu=tl,Qu=nl,eo=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(yi,{ref:r,className:de("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(rl,{asChild:!0,children:h.jsx(ur,{className:"h-4 w-4 opacity-50"})})]}));eo.displayName=yi.displayName;const to=k.forwardRef(({className:e,...t},n)=>h.jsx(Si,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(ll,{className:"h-4 w-4"})}));to.displayName=Si.displayName;const no=k.forwardRef(({className:e,...t},n)=>h.jsx(ki,{ref:n,className:de("flex cursor-default items-center justify-center py-1",e),...t,children:h.jsx(ur,{className:"h-4 w-4"})}));no.displayName=ki.displayName;const ro=k.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>h.jsx(sl,{children:h.jsxs(xi,{ref:s,className:de("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(to,{}),h.jsx(il,{className:de("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),h.jsx(no,{})]})}));ro.displayName=xi.displayName;const so=k.forwardRef(({className:e,children:t,...n},r)=>h.jsxs(bi,{ref:r,className:de("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(ol,{children:h.jsx(Jt,{className:"h-4 w-4"})})}),h.jsx(al,{children:t})]}));so.displayName=bi.displayName;const Gu=gu,Xu=mu,Yu=yu,io=k.forwardRef(({className:e,sideOffset:t=4,...n},r)=>h.jsx(xu,{children:h.jsx(ji,{ref:r,sideOffset:t,className:de("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})}));io.displayName=ji.displayName;const Et={Popover:Vu,PopoverAnchor:qu,PopoverContent:Zi,PopoverTrigger:Hu,Input:Ji,Select:Wu,SelectContent:ro,SelectItem:so,SelectTrigger:eo,SelectValue:Qu,Tooltip:Xu,TooltipContent:io,TooltipProvider:Gu,TooltipTrigger:Yu},Ju=680,Zu=.82,ec=560;function tc(e){const{Popover:t,PopoverAnchor:n,PopoverContent:r}=Et,{elementRef:s,width:i}=Uu(),o=k.useRef(null),{isOpen:a,isLoading:l,items:u,activeIndex:c,activeItem:d,texts:p,onSelectItem:f,onOpenChange:y,onSetActiveIndex:m}=e,b=k.useMemo(()=>{if(i)return Math.min(i>ec?i*Zu:i,Ju)},[i]);return Yi({containerRef:o,activeIndex:c,itemCount:u.length,isEnabled:a&&!l,getItemSelector:g=>`[data-slash-index="${g}"]`}),h.jsxs(t,{open:a,onOpenChange:y,children:[h.jsx(n,{asChild:!0,children:h.jsx("div",{ref:s,className:"pointer-events-none absolute bottom-full left-3 right-3 h-0"})}),h.jsx(r,{side:"top",align:"start",sideOffset:10,className:"z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md",onOpenAutoFocus:g=>g.preventDefault(),style:b?{width:`${b}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:o,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,v)=>{const w=v===c;return h.jsxs("button",{type:"button",role:"option","aria-selected":w,"data-slash-index":v,onMouseEnter:()=>m(v),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 nc=ul("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"}}),Ut=k.forwardRef(({className:e,variant:t,size:n,...r},s)=>h.jsx("button",{className:de(nc({variant:t,size:n,className:e})),ref:s,...r}));Ut.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 rc(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Et;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(Ut,{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(Ut,{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(Ut,{size:"icon",className:"h-8 w-8 rounded-full","aria-label":e.sendButtonLabel,onClick:()=>void e.onSend(),disabled:e.sendDisabled,children:h.jsx(cl,{className:"h-5 w-5"})})})]})}function sc(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 ic(e){const{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:s}=Et,{picker:i}=e,o=k.useRef(null),a=k.useId(),[l,u]=k.useState(""),[c,d]=k.useState(0),p=k.useMemo(()=>new Set(i.selectedKeys),[i.selectedKeys]),f=i.selectedKeys.length,y=k.useMemo(()=>sc(i.options,l),[i.options,l]);k.useEffect(()=>{d(0)},[l]),k.useEffect(()=>{d(g=>y.length===0?0:Math.min(g,y.length-1))},[y.length]),Yi({containerRef:o,activeIndex:c,itemCount:y.length,isEnabled:y.length>0,getItemSelector:g=>`[data-skill-index="${g}"]`});const m=g=>{if(p.has(g)){i.onSelectedKeysChange(i.selectedKeys.filter(v=>v!==g));return}i.onSelectedKeysChange([...i.selectedKeys,g])},b=g=>{if(y.length!==0){if(g.key==="ArrowDown"){g.preventDefault(),d(v=>Math.min(v+1,y.length-1));return}if(g.key==="ArrowUp"){g.preventDefault(),d(v=>Math.max(v-1,0));return}if(g.key==="Enter"){g.preventDefault();const v=y[c];v&&m(v.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:b,placeholder:i.searchPlaceholder,role:"combobox","aria-controls":a,"aria-expanded":"true","aria-autocomplete":"list","aria-activedescendant":y[c]?`${a}-option-${c}`:void 0,className:"h-8 rounded-lg pl-8 text-xs"})]})]}),h.jsx("div",{ref:o,id:a,role:"listbox","aria-multiselectable":"true",className:"custom-scrollbar max-h-[320px] overflow-y-auto",children:i.isLoading?h.jsx("div",{className:"p-4 text-xs text-gray-500",children:i.loadingLabel}):y.length===0?h.jsx("div",{className:"p-4 text-center text-xs text-gray-500",children:i.emptyLabel}):h.jsx("div",{className:"py-1",children:y.map((g,v)=>{const w=p.has(g.key),N=v===c;return h.jsxs("button",{type:"button",id:`${a}-option-${v}`,role:"option","aria-selected":w,"data-skill-index":v,onClick:()=>m(g.key),onMouseEnter:()=>d(v),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${N?"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(dl,{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(Jt,{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(hl,{className:"h-3 w-3"})]})}):null]})]})}function oo({icon:e}){return e==="sparkles"?h.jsx(pl,{className:"h-3.5 w-3.5 shrink-0 text-primary"}):e==="brain"?h.jsx(gl,{className:"h-3.5 w-3.5 shrink-0 text-gray-500"}):null}function oc({icon:e}){return e==="paperclip"?h.jsx(fl,{className:"h-4 w-4"}):h.jsx(oo,{icon:e})}function ac(e){return e==="model"?"min-w-[220px]":e==="session-type"?"min-w-[140px]":e==="thinking"?"min-w-[150px]":""}function lc(e){return e==="model"?"w-[320px]":e==="session-type"?"w-[220px]":e==="thinking"?"w-[180px]":""}function uc({item:e}){const{Select:t,SelectContent:n,SelectItem:r,SelectTrigger:s,SelectValue:i}=Et;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 ${ac(e.key)}`,children:e.selectedLabel?h.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-left",children:[h.jsx(oo,{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:lc(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(o=>h.jsx(r,{value:o.value,className:"py-2",children:o.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:o.label}),h.jsx("span",{className:"truncate text-[11px] text-gray-500",children:o.description})]}):h.jsx("span",{className:"truncate text-xs font-semibold text-gray-800",children:o.label})},o.value))]})]})}function cc(e){var i;const{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:s}=Et;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(ic,{picker:e.skillPicker}):null,e.selects.map(o=>h.jsx(uc,{item:o},o.key)),(i=e.accessories)==null?void 0:i.map(o=>{const a=h.jsxs("button",{type:"button",className:`inline-flex items-center rounded-lg 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 ${o.iconOnly?"h-8 w-8 justify-center px-0":"gap-1.5 px-3"}`,onClick:o.onClick,disabled:o.disabled,"aria-label":o.label,children:[h.jsx(oc,{icon:o.icon}),o.iconOnly?null:h.jsx("span",{children:o.label})]});if(!o.tooltip)return h.jsx("div",{children:a},o.key);const l=o.disabled?h.jsx("span",{className:"inline-flex",children:a}):a;return h.jsx(r,{children:h.jsxs(t,{children:[h.jsx(s,{asChild:!0,children:l}),h.jsx(n,{side:"top",children:h.jsx("p",{className:"text-xs",children:o.tooltip})})]})},o.key)})]}),h.jsx(rc,{...e.actions})]})}const dc="";function ao(){return`composer-${Math.random().toString(36).slice(2,10)}`}function It(e=""){return{id:ao(),type:"text",text:e}}function yr(e){return{id:ao(),type:"token",tokenKind:e.tokenKind,tokenKey:e.tokenKey,label:e.label}}function Lt(e){return e.type==="text"?e.text.length:1}function xr(){return[It("")]}function hc(e){return[It(e)]}function ut(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?xr():t}function fc(e){return e.map(t=>t.type==="text"?t.text:dc).join("")}function pc(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function nn(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 gc(e,t,n,r){const s=Math.max(0,n-t),i=Math.max(0,t+e.text.length-r),o=[];return s>0&&o.push({...e,text:e.text.slice(0,s)}),i>0&&o.push({...e,text:e.text.slice(e.text.length-i)}),o}function mc(e,t,n,r){return t<=n||e>=r}function yc(e,t,n,r,s){return!n&&r>=s?(e.push(...t),!0):n}function xc(e,t,n,r,s,i,o){const a=gc(t,n,r,s);a[0]&&e.push(a[0]);let l=o;return l||(e.push(...i),l=!0),a[1]&&e.push(a[1]),l}function bc(e,t,n,r,s,i){return!r&&s<=i?(e.push(...n),!0):(e.push(t),r)}function dn(e,t,n,r){const s=Math.max(0,t),i=Math.max(s,n),o=[];let a=0,l=!1;for(const u of e){const c=Lt(u),d=a,p=a+c;if(mc(d,p,s,i)){l=yc(o,r,l,d,i),o.push(u),a=p;continue}u.type==="text"?l=xc(o,u,d,s,i,r,l):l=bc(o,u,r,l,s,d),a=p}return l||o.push(...r),ut(o)}function br(e,t){return ut(e.filter(n=>n.type!=="token"||!t(n)))}function Sc(e,t){if(!t||t.start!==t.end)return null;const n=fc(e),r=t.end,s=n.slice(0,r),i=/(?:^|\s)\/([^\s\uFFFC]*)$/.exec(s);if(!i)return null;const o=r-i[0].length+(i[0].startsWith("/")?0:1);return{query:(i[1]??"").trim().toLowerCase(),start:o,end:r}}function kc(e,t,n){return e?e.start<n&&e.end>t:!1}function lo(e){const t=new Map;let n=0;for(const r of e)t.set(r.id,n),n+=Lt(r);return t}function uo(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 vc(e,t,n){if(e instanceof HTMLElement){const r=e.dataset.composerNodeId;if(r)return n.find(s=>s.id===r)}return n[t]}function co(e,t,n){let r=0;for(let s=0;s<n;s+=1){const i=vc(e.childNodes[s],s,t);i&&(r+=Lt(i))}return r}function wc(e,t,n,r){var a;const s=uo(e,t),i=co(e,r,s),o=r[s];return(o==null?void 0:o.type)==="text"?i+Math.min(n,o.text.length):i+Math.min(n,((a=t.textContent)==null?void 0:a.length)??0)}function Cc(e,t,n,r,s){return n.type==="text"?e.nodeType===Node.TEXT_NODE?r+Math.min(t,n.text.length):e===s?r+(t>0?n.text.length:0):r+n.text.length:e===s?r+(t>0?1:0):r+1}function $n(e,t,n,r,s){var u;if(t===e)return co(e,r,n);if(t.nodeType===Node.TEXT_NODE&&t.parentNode===e)return wc(e,t,n,r);const i=t instanceof HTMLElement?t.closest("[data-composer-node-id]"):((u=t.parentElement)==null?void 0:u.closest("[data-composer-node-id]"))??null;if(!(i instanceof HTMLElement)){const c=uo(e,t);return $n(e,e,c,r,s)}const o=i.dataset.composerNodeId;if(!o)return 0;const a=r.find(c=>c.id===o),l=s.get(o)??0;return a?Cc(t,n,a,l,i):l}function ho(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=lo(t),i=$n(e,r.startContainer,r.startOffset,t,s),o=$n(e,r.endContainer,r.endOffset,t,s);return{start:Math.min(i,o),end:Math.max(i,o)}}function Tc(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=Lt(d),f=u,y=u+p,m=e.childNodes[c];if(!m){u=y;continue}if(d.type==="text"){if(l<=y)return{container:m.firstChild??m,offset:Math.max(0,Math.min(l-f,d.text.length))}}else{if(l<=f)return{container:e,offset:c};if(l<=y)return{container:e,offset:c+1}}u=y}return{container:e,offset:e.childNodes.length}},i=s(n.start),o=s(n.end),a=document.createRange();a.setStart(i.container,i.offset),a.setEnd(o.container,o.offset),r.removeAllRanges(),r.addRange(a)}function Ic(e){const t=[];for(const n of Array.from(e.childNodes)){if(n.nodeType===Node.TEXT_NODE){t.push(It(n.textContent??""));continue}if(!(n instanceof HTMLElement))continue;if(n.dataset.composerNodeType==="token"){const i=n.dataset.composerTokenKind,o=n.dataset.composerTokenKey,a=n.dataset.composerLabel;i&&o&&a&&t.push({id:n.dataset.composerNodeId??yr({tokenKind:i,tokenKey:o,label:a}).id,type:"token",tokenKind:i,tokenKey:o,label:a});continue}const s=n.textContent??"";t.push({id:n.dataset.composerNodeId??It(s).id,type:"text",text:s})}return ut(t)}function Gr(e){const t=Ic(e);return{nodes:t,selection:ho(e,t)}}class Mc{constructor(){this.nodes=xr(),this.selection=null,this.sync=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.setSelection=t=>(this.selection=t,this.getSnapshot()),this.replaceDocument=(t,n)=>(this.nodes=ut(t),this.selection=n,this.getSnapshot()),this.insertText=t=>{const n=this.selection??{start:0,end:0};this.nodes=dn(this.nodes,n.start,n.end,[It(t)]);const r=n.start+t.length;return this.selection={start:r,end:r},this.getSnapshot()},this.insertFileToken=(t,n)=>this.insertToken("file",t,n),this.insertSkillToken=(t,n)=>this.getSelectedSkillKeys().includes(t)?this.getSnapshot():this.insertToken("skill",t,n,this.getSlashTrigger()),this.syncSelectedSkills=(t,n)=>{const r=this.getSelectedSkillKeys(),s=new Map(n.map(a=>[a.key,a])),i=t.find(a=>!r.includes(a));if(i){const a=s.get(i);return this.insertSkillToken(i,(a==null?void 0:a.label)??i)}const o=r.find(a=>!t.includes(a));return o&&(this.nodes=br(this.nodes,a=>a.tokenKind==="skill"&&a.tokenKey===o)),this.getSnapshot()},this.deleteContent=t=>{const n=this.getDocumentLength(),r=this.selection??{start:n,end:n};let s=r.start,i=r.end;if(r.start===r.end)if(t==="backward"&&r.start>0)s=r.start-1;else if(t==="forward")i=r.end+1;else return this.getSnapshot();return this.nodes=dn(this.nodes,s,i,[]),this.selection={start:s,end:s},this.getSnapshot()},this.getSnapshot=()=>({nodes:this.nodes,selection:this.selection,nodeStartMap:lo(this.nodes),documentLength:this.getDocumentLength(),selectedSkillKeys:this.getSelectedSkillKeys(),slashTrigger:this.getSlashTrigger()}),this.getDocumentLength=()=>this.nodes.reduce((t,n)=>t+Lt(n),0),this.getSelectedSkillKeys=()=>nn(this.nodes,"skill"),this.insertToken=(t,n,r,s=null)=>{var l,u;const i=this.getDocumentLength(),o=(s==null?void 0:s.start)??((l=this.selection)==null?void 0:l.start)??i,a=(s==null?void 0:s.end)??((u=this.selection)==null?void 0:u.end)??o;return this.nodes=dn(this.nodes,o,a,[yr({tokenKind:t,tokenKey:n,label:r})]),this.selection={start:o+1,end:o+1},this.getSnapshot()},this.getSlashTrigger=()=>Sc(this.nodes,this.selection)}}function Rc(e){const{key:t,shiftKey:n,isComposing:r,isSlashMenuOpen:s,slashItemCount:i,activeSlashIndex:o,isSending:a,canStopGeneration:l}=e;if(s&&i>0){if(t==="ArrowDown")return{type:"move-slash-index",index:(o+1)%i};if(t==="ArrowUp")return{type:"move-slash-index",index:(o-1+i)%i};if(t==="Enter"&&!n||t==="Tab")return{type:"insert-active-slash-item"}}return t==="Escape"?s?{type:"close-slash"}:a&&l?{type:"stop-generation"}:{type:"noop"}:t==="Enter"&&n?{type:"insert-line-break"}:t==="Enter"?{type:"send-message"}:!r&&(t==="Backspace"||t==="Delete")?{type:"delete-content",direction:t==="Backspace"?"backward":"forward"}:{type:"noop"}}const Xr="http://www.w3.org/2000/svg";class Ac{constructor(){this.render=(t,n)=>{if(!t)return;const r=document.createDocumentFragment();for(const s of n.nodes){const i=s.type==="text"?this.createTextNodeElement(s):this.createTokenNodeElement(s,n.selectedRange,n.nodeStartMap);i&&r.appendChild(i)}t.replaceChildren(r)},this.createTextNodeElement=t=>{if(t.text.length===0)return null;const n=document.createElement("span");return n.dataset.composerNodeId=t.id,n.dataset.composerNodeType="text",n.textContent=t.text,n},this.createTokenNodeElement=(t,n,r)=>{const s=r.get(t.id)??0,i=kc(n,s,s+1),o=document.createElement("span");o.contentEditable="false",o.dataset.composerNodeId=t.id,o.dataset.composerNodeType="token",o.dataset.composerTokenKind=t.tokenKind,o.dataset.composerTokenKey=t.tokenKey,o.dataset.composerLabel=t.label,o.title=t.label,o.className=this.buildTokenClassName(t.tokenKind,i),o.append(this.createTokenIcon(t.tokenKind));const a=document.createElement("span");return a.className=t.tokenKind==="file"?"min-w-0 flex-1 truncate text-[12px] font-medium text-slate-700":"truncate",a.textContent=t.label,o.append(a),o},this.buildTokenClassName=(t,n)=>t==="file"?["mx-[2px]","inline-flex","h-7","max-w-[min(100%,17rem)]","items-center","gap-1.5","rounded-lg","border","px-2","align-baseline","transition-[border-color,background-color,box-shadow,color]","duration-150",n?"border-slate-300 bg-slate-100 text-slate-800 shadow-[0_0_0_2px_rgba(148,163,184,0.14)]":"border-slate-200/80 bg-slate-50 text-slate-700"].join(" "):["mx-[2px]","inline-flex","h-7","max-w-full","items-center","gap-1.5","rounded-lg","border","px-2","align-baseline","text-[11px]","font-medium","transition",n?"border-primary/30 bg-primary/18 text-primary":"border-primary/12 bg-primary/8 text-primary"].join(" "),this.createTokenIcon=t=>{const n=document.createElement("span");return n.className=t==="file"?"inline-flex h-4.5 w-4.5 shrink-0 items-center justify-center rounded-md bg-white text-slate-500 ring-1 ring-black/5":"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-primary/70",n.append(t==="file"?this.createFileIcon():this.createSkillIcon()),n},this.createSkillIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M8.5 2.75 2.75 6l5.75 3.25L14.25 6 8.5 2.75Z"}},{tag:"path",attrs:{d:"M2.75 10 8.5 13.25 14.25 10"}},{tag:"path",attrs:{d:"M2.75 6v4l5.75 3.25V9.25L2.75 6Z"}},{tag:"path",attrs:{d:"M14.25 6v4L8.5 13.25V9.25L14.25 6Z"}}]),this.createFileIcon=()=>this.createSvgIcon([{tag:"path",attrs:{d:"M3.25 4.25A1.5 1.5 0 0 1 4.75 2.75h6.5a1.5 1.5 0 0 1 1.5 1.5v7.5a1.5 1.5 0 0 1-1.5 1.5h-6.5a1.5 1.5 0 0 1-1.5-1.5v-7.5Z"}},{tag:"path",attrs:{d:"m4.75 10 2.25-2.5 1.75 1.75 1.25-1.25 2 2"}},{tag:"path",attrs:{d:"M9.75 6.25h.01"}}]),this.createSvgIcon=t=>{const n=document.createElementNS(Xr,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.25"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("class","h-3 w-3");for(const r of t){const s=document.createElementNS(Xr,r.tag);for(const[i,o]of Object.entries(r.attrs))s.setAttribute(i,o);n.append(s)}return n}}}const Yr=188;class Ec{constructor(t){this.controller=t,this.surfaceRenderer=new Ac,this.sync=(n,r)=>this.controller.sync(n,r),this.syncSelectionFromRoot=n=>this.controller.setSelection(ho(n,this.controller.getSnapshot().nodes)),this.restoreSelectionIfFocused=(n,r)=>{!n||document.activeElement!==n||Tc(n,this.controller.getSnapshot().nodes,r)},this.syncViewport=n=>{n&&(n.style.maxHeight=`${Yr}px`,n.style.overflowY=n.scrollHeight>Yr?"auto":"hidden")},this.renderSurface=n=>{this.surfaceRenderer.render(n.root,{nodes:n.snapshot.nodes,selectedRange:n.selectedRange,nodeStartMap:n.snapshot.nodeStartMap})},this.insertSlashItem=(n,r)=>{n.value&&r(this.controller.insertSkillToken(n.value,n.title))},this.syncSelectedSkills=(n,r,s)=>{s(this.controller.syncSelectedSkills(n,r))},this.handleBeforeInput=n=>{const{event:r,disabled:s,isComposing:i,commitSnapshot:o}=n,a=r.nativeEvent;s||i||a.isComposing||!(a.inputType==="insertText"||a.inputType==="insertReplacementText")||!a.data||(r.preventDefault(),o(this.controller.insertText(a.data)))},this.handleInput=n=>{const{event:r,isComposing:s,commitSnapshot:i}=n,o=r.nativeEvent;if(s||o.isComposing)return;const a=r.currentTarget,l=Gr(a);i(this.controller.replaceDocument(l.nodes,l.selection))},this.handleCompositionEnd=n=>{const{event:r,commitSnapshot:s}=n,i=r.currentTarget,o=Gr(i);s(this.controller.replaceDocument(o.nodes,o.selection))},this.handleKeyDown=n=>{const{event:r,slashItems:s,activeSlashIndex:i,activeSlashItem:o,actions:a,commitSnapshot:l,insertSkillToken:u,onSlashActiveIndexChange:c,onSlashQueryChange:d,onSlashOpenChange:p}=n,f=this.controller.getSnapshot(),y=Rc({key:r.key,shiftKey:r.shiftKey,isComposing:r.nativeEvent.isComposing,isSlashMenuOpen:f.slashTrigger!==null,slashItemCount:s.length,activeSlashIndex:i,isSending:a.isSending,canStopGeneration:a.canStopGeneration});if(y.type!=="noop"){if(r.preventDefault(),y.type==="move-slash-index"){c(y.index);return}if(y.type==="insert-active-slash-item"){o&&u(o.value??o.key,o.title);return}if(y.type==="close-slash"){d==null||d(null),p(!1);return}if(y.type==="stop-generation"){a.onStop();return}if(y.type==="insert-line-break"){l(this.controller.insertText(`
|
|
2
|
+
`));return}if(y.type==="send-message"){a.onSend();return}y.type==="delete-content"&&l(this.controller.deleteContent(y.direction))}},this.handlePaste=n=>{const{event:r,onFilesAdd:s,commitSnapshot:i}=n,o=Array.from(r.clipboardData.files??[]);if(o.length>0&&s){r.preventDefault(),s(o);return}const a=r.clipboardData.getData("text/plain");a&&(r.preventDefault(),i(this.controller.insertText(a)))},this.handleBlur=n=>{const{clearSelectedRange:r,onSlashQueryChange:s,onSlashOpenChange:i}=n;r(),s==null||s(null),i(!1)}}}class Lc{constructor(){this.controller=new Mc,this.viewController=new Ec(this.controller),this.rootElement=null,this.selection=null,this.selectedRange=null,this.snapshot=this.controller.getSnapshot(),this.config=null,this.isComposing=!1,this.bindRootElement=t=>{this.rootElement=t},this.update=t=>(this.config=t,this.snapshot=this.viewController.sync(t.nodes,this.selectedRange),{snapshot:this.snapshot,selectedRange:this.selectedRange,bindRootElement:this.bindRootElement,handleBeforeInput:this.handleBeforeInput,handleInput:this.handleInput,handleCompositionStart:this.handleCompositionStart,handleCompositionEnd:this.handleCompositionEnd,handleKeyDown:this.handleKeyDown,handlePaste:this.handlePaste,handleBlur:this.handleBlur,syncSelectionState:this.syncSelectionState,imperativeHandle:this.createHandle()}),this.createHandle=()=>({insertSlashItem:t=>{this.viewController.insertSlashItem(t,this.commitSnapshot)},insertFileToken:(t,n)=>{this.commitSnapshot(this.controller.insertFileToken(t,n)),this.focusComposerSoon()},insertFileTokens:t=>{let n=null;for(const r of t)n=this.controller.insertFileToken(r.tokenKey,r.label);n&&(this.commitSnapshot(n),this.focusComposerSoon())},focusComposer:()=>{this.focusComposer()},syncSelectedSkills:(t,n)=>{this.viewController.syncSelectedSkills(t,n,this.commitSnapshot)}}),this.restoreDomAfterCommit=()=>{this.isComposing||this.viewController.restoreSelectionIfFocused(this.rootElement,this.selection)},this.renderSurface=()=>{this.isComposing||this.viewController.renderSurface({root:this.rootElement,snapshot:this.snapshot,selectedRange:this.selectedRange})},this.syncViewport=()=>{this.viewController.syncViewport(this.rootElement)},this.syncSelectionState=()=>{if(!this.rootElement||this.isComposing)return;const t=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=t.selection,this.selectedRange=t.selection,this.syncSlashState(t),this.requestRender()},this.handleBeforeInput=t=>{this.viewController.handleBeforeInput({event:t,disabled:this.requireConfig().disabled,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleInput=t=>{this.viewController.handleInput({event:t,isComposing:this.isComposing,commitSnapshot:this.commitSnapshot})},this.handleCompositionStart=()=>{this.isComposing=!0},this.handleCompositionEnd=t=>{this.isComposing=!1,this.viewController.handleCompositionEnd({event:t,commitSnapshot:this.commitSnapshot})},this.handleKeyDown=t=>{const n=this.requireConfig();if(this.rootElement&&!this.isComposing){const s=this.viewController.syncSelectionFromRoot(this.rootElement);this.selection=s.selection,this.selectedRange=s.selection,this.snapshot=s}const r=n.slashItems[n.activeSlashIndex]??null;this.viewController.handleKeyDown({event:t,slashItems:n.slashItems,activeSlashIndex:n.activeSlashIndex,activeSlashItem:r,actions:n.actions,commitSnapshot:this.commitSnapshot,insertSkillToken:this.insertSkillToken,onSlashActiveIndexChange:n.onSlashActiveIndexChange,onSlashQueryChange:n.onSlashQueryChange,onSlashOpenChange:n.onSlashOpenChange})},this.handlePaste=t=>{this.viewController.handlePaste({event:t,onFilesAdd:this.requireConfig().onFilesAdd,commitSnapshot:this.commitSnapshot})},this.handleBlur=()=>{const t=this.requireConfig();this.isComposing=!1,this.viewController.handleBlur({clearSelectedRange:this.clearSelectedRange,onSlashQueryChange:t.onSlashQueryChange,onSlashOpenChange:t.onSlashOpenChange})},this.setSelectedRange=t=>{this.selectedRange=t,this.selection=t,this.requestRender()},this.clearSelectedRange=()=>{this.selectedRange=null,this.requestRender()},this.commitSnapshot=t=>{const n=this.requireConfig();this.selection=t.selection,this.selectedRange=t.selection,this.snapshot=t,n.onNodesChange(t.nodes),this.syncSlashState(t)},this.insertSkillToken=(t,n)=>{this.commitSnapshot(this.controller.insertSkillToken(t,n))},this.syncSlashState=t=>{var r,s,i;const n=this.requireConfig();(r=n.onSlashTriggerChange)==null||r.call(n,t.slashTrigger),(i=n.onSlashQueryChange)==null||i.call(n,((s=t.slashTrigger)==null?void 0:s.query)??null),n.onSlashOpenChange(t.slashTrigger!==null)},this.requestRender=()=>{this.requireConfig().requestRender()},this.focusComposerSoon=()=>{if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>this.focusComposer());return}this.focusComposer()},this.focusComposer=()=>{if(!this.rootElement)return;const t=this.selection;this.rootElement.focus();const n=()=>{this.rootElement&&(this.selection=t,this.selectedRange=t,this.viewController.restoreSelectionIfFocused(this.rootElement,t))};if(typeof requestAnimationFrame=="function"){requestAnimationFrame(n);return}n()},this.requireConfig=()=>{if(!this.config)throw new Error("ChatComposerRuntime is not configured.");return this.config}}}const Nc=k.forwardRef(function(t,n){const{nodes:r,placeholder:s,disabled:i,slashItems:o,actions:a,onNodesChange:l,onFilesAdd:u,onSlashQueryChange:c,onSlashTriggerChange:d,onSlashOpenChange:p,onSlashActiveIndexChange:f,activeSlashIndex:y}=t,[m,b]=k.useState(0),[g]=k.useState(()=>new Lc),{snapshot:v,bindRootElement:w,handleBeforeInput:N,handleInput:j,handleCompositionStart:T,handleCompositionEnd:O,handleKeyDown:B,handlePaste:$,handleBlur:C,syncSelectionState:R,imperativeHandle:E}=g.update({nodes:r,disabled:i,slashItems:o,actions:a,onNodesChange:l,onFilesAdd:u,onSlashQueryChange:c,onSlashTriggerChange:d,onSlashOpenChange:p,onSlashActiveIndexChange:f,activeSlashIndex:y,requestRender:()=>b(z=>z+1)});return k.useImperativeHandle(n,()=>E,[E]),k.useLayoutEffect(()=>{g.renderSurface(),g.restoreDomAfterCommit(),g.syncViewport()},[g,v.nodes,v.nodeStartMap,m]),h.jsx("div",{className:"px-4 py-2.5",children:h.jsx("div",{className:"min-h-[60px]",children:h.jsx("div",{ref:w,contentEditable:!i,suppressContentEditableWarning:!0,role:"textbox","aria-multiline":"true","data-placeholder":s,onBeforeInput:N,onInput:j,onCompositionStart:T,onCompositionEnd:O,onKeyDown:B,onKeyUp:R,onMouseUp:R,onFocus:R,onBlur:C,onPaste:$,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)]"})})})});function Pc({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]})})}const fo=k.forwardRef(function(t,n){const r=k.useRef(null),[s,i]=k.useState(null),[o,a]=k.useState(0),[l,u]=k.useState(null),[c,d]=k.useState(null),p=l!==null&&c!==l,f=t.slashMenu.items[o]??null;k.useEffect(()=>{a(m=>t.slashMenu.items.length===0?0:Math.min(m,t.slashMenu.items.length-1))},[t.slashMenu.items.length]),k.useEffect(()=>{s!==null&&a(0)},[s]),k.useEffect(()=>{l===null&&c!==null&&d(null)},[l,c]);const y=k.useMemo(()=>t.toolbar.skillPicker?{...t.toolbar,skillPicker:{...t.toolbar.skillPicker,onSelectedKeysChange:m=>{var b,g;(g=r.current)==null||g.syncSelectedSkills(m,((b=t.toolbar.skillPicker)==null?void 0:b.options)??[])}}}:t.toolbar,[t.toolbar]);return k.useImperativeHandle(n,()=>({insertFileToken:(m,b)=>{var g;return(g=r.current)==null?void 0:g.insertFileToken(m,b)},insertFileTokens:m=>{var b;return(b=r.current)==null?void 0:b.insertFileTokens(m)},focusComposer:()=>{var m;return(m=r.current)==null?void 0:m.focusComposer()}}),[]),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:r,nodes:t.composer.nodes,placeholder:t.composer.placeholder,disabled:t.composer.disabled,slashItems:t.slashMenu.items,actions:t.toolbar.actions,activeSlashIndex:o,onNodesChange:t.composer.onNodesChange,onFilesAdd:t.composer.onFilesAdd,onSlashQueryChange:m=>{var b,g;i(m),(g=(b=t.composer).onSlashQueryChange)==null||g.call(b,m)},onSlashTriggerChange:m=>{u((m==null?void 0:m.start)??null)},onSlashOpenChange:m=>{!m&&l!==null&&d(l)},onSlashActiveIndexChange:a}),h.jsx(tc,{isOpen:p,isLoading:t.slashMenu.isLoading,items:t.slashMenu.items,activeIndex:o,activeItem:f,texts:t.slashMenu.texts,onSelectItem:m=>{var b;d(null),(b=r.current)==null||b.insertSlashItem(m)},onOpenChange:m=>{!m&&l!==null&&d(l)},onSetActiveIndex:a})]}),h.jsx(Pc,{hint:t.hint}),h.jsx(cc,{...y})]})})})});fo.displayName="ChatInputBar";function hn({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(ml,{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(vi,{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(wi,{className:"h-4 w-4"})})}function jc(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Dc=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,_c=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Oc={};function Jr(e,t){return(Oc.jsx?_c:Dc).test(e)}const Fc=/[ \t\n\f\r]/g;function zc(e){return typeof e=="object"?e.type==="text"?Zr(e.value):!1:Zr(e)}function Zr(e){return e.replace(Fc,"")===""}class Nt{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Nt.prototype.normal={};Nt.prototype.property={};Nt.prototype.space=void 0;function po(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new Nt(n,r,t)}function Kn(e){return e.toLowerCase()}class Se{constructor(t,n){this.attribute=n,this.property=t}}Se.prototype.attribute="";Se.prototype.booleanish=!1;Se.prototype.boolean=!1;Se.prototype.commaOrSpaceSeparated=!1;Se.prototype.commaSeparated=!1;Se.prototype.defined=!1;Se.prototype.mustUseProperty=!1;Se.prototype.number=!1;Se.prototype.overloadedBoolean=!1;Se.prototype.property="";Se.prototype.spaceSeparated=!1;Se.prototype.space=void 0;let Bc=0;const q=tt(),le=tt(),Un=tt(),P=tt(),te=tt(),at=tt(),we=tt();function tt(){return 2**++Bc}const Vn=Object.freeze(Object.defineProperty({__proto__:null,boolean:q,booleanish:le,commaOrSpaceSeparated:we,commaSeparated:at,number:P,overloadedBoolean:Un,spaceSeparated:te},Symbol.toStringTag,{value:"Module"})),fn=Object.keys(Vn);class Sr extends Se{constructor(t,n,r,s){let i=-1;if(super(t,n),es(this,"space",s),typeof r=="number")for(;++i<fn.length;){const o=fn[i];es(this,fn[i],(r&Vn[o])===Vn[o])}}}Sr.prototype.defined=!0;function es(e,t,n){n&&(e[t]=n)}function dt(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new Sr(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 Nt(t,n,e.space)}const go=dt({properties:{ariaActiveDescendant:null,ariaAtomic:le,ariaAutoComplete:null,ariaBusy:le,ariaChecked:le,ariaColCount:P,ariaColIndex:P,ariaColSpan:P,ariaControls:te,ariaCurrent:null,ariaDescribedBy:te,ariaDetails:null,ariaDisabled:le,ariaDropEffect:te,ariaErrorMessage:null,ariaExpanded:le,ariaFlowTo:te,ariaGrabbed:le,ariaHasPopup:null,ariaHidden:le,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:te,ariaLevel:P,ariaLive:null,ariaModal:le,ariaMultiLine:le,ariaMultiSelectable:le,ariaOrientation:null,ariaOwns:te,ariaPlaceholder:null,ariaPosInSet:P,ariaPressed:le,ariaReadOnly:le,ariaRelevant:null,ariaRequired:le,ariaRoleDescription:te,ariaRowCount:P,ariaRowIndex:P,ariaRowSpan:P,ariaSelected:le,ariaSetSize:P,ariaSort:null,ariaValueMax:P,ariaValueMin:P,ariaValueNow:P,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function mo(e,t){return t in e?e[t]:t}function yo(e,t){return mo(e,t.toLowerCase())}const $c=dt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:at,acceptCharset:te,accessKey:te,action:null,allow:null,allowFullScreen:q,allowPaymentRequest:q,allowUserMedia:q,alt:null,as:null,async:q,autoCapitalize:null,autoComplete:te,autoFocus:q,autoPlay:q,blocking:te,capture:null,charSet:null,checked:q,cite:null,className:te,cols:P,colSpan:null,content:null,contentEditable:le,controls:q,controlsList:te,coords:P|at,crossOrigin:null,data:null,dateTime:null,decoding:null,default:q,defer:q,dir:null,dirName:null,disabled:q,download:Un,draggable:le,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:q,formTarget:null,headers:te,height:P,hidden:Un,high:P,href:null,hrefLang:null,htmlFor:te,httpEquiv:te,id:null,imageSizes:null,imageSrcSet:null,inert:q,inputMode:null,integrity:null,is:null,isMap:q,itemId:null,itemProp:te,itemRef:te,itemScope:q,itemType:te,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:q,low:P,manifest:null,max:null,maxLength:P,media:null,method:null,min:null,minLength:P,multiple:q,muted:q,name:null,nonce:null,noModule:q,noValidate:q,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:q,optimum:P,pattern:null,ping:te,placeholder:null,playsInline:q,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:q,referrerPolicy:null,rel:te,required:q,reversed:q,rows:P,rowSpan:P,sandbox:te,scope:null,scoped:q,seamless:q,selected:q,shadowRootClonable:q,shadowRootDelegatesFocus:q,shadowRootMode:null,shape:null,size:P,sizes:null,slot:null,span:P,spellCheck:le,src:null,srcDoc:null,srcLang:null,srcSet:null,start:P,step:null,style:null,tabIndex:P,target:null,title:null,translate:null,type:null,typeMustMatch:q,useMap:null,value:le,width:P,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:te,axis:null,background:null,bgColor:null,border:P,borderColor:null,bottomMargin:P,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:q,declare:q,event:null,face:null,frame:null,frameBorder:null,hSpace:P,leftMargin:P,link:null,longDesc:null,lowSrc:null,marginHeight:P,marginWidth:P,noResize:q,noHref:q,noShade:q,noWrap:q,object:null,profile:null,prompt:null,rev:null,rightMargin:P,rules:null,scheme:null,scrolling:le,standby:null,summary:null,text:null,topMargin:P,valueType:null,version:null,vAlign:null,vLink:null,vSpace:P,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:q,disableRemotePlayback:q,prefix:null,property:null,results:P,security:null,unselectable:null},space:"html",transform:yo}),Kc=dt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:we,accentHeight:P,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:P,amplitude:P,arabicForm:null,ascent:P,attributeName:null,attributeType:null,azimuth:P,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:P,by:null,calcMode:null,capHeight:P,className:te,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:P,diffuseConstant:P,direction:null,display:null,dur:null,divisor:P,dominantBaseline:null,download:q,dx:null,dy:null,edgeMode:null,editable:null,elevation:P,enableBackground:null,end:null,event:null,exponent:P,externalResourcesRequired:null,fill:null,fillOpacity:P,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:at,g2:at,glyphName:at,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:P,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:P,horizOriginX:P,horizOriginY:P,id:null,ideographic:P,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:P,k:P,k1:P,k2:P,k3:P,k4:P,kernelMatrix:we,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:P,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:P,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:P,overlineThickness:P,paintOrder:null,panose1:null,path:null,pathLength:P,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:te,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:P,pointsAtY:P,pointsAtZ:P,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:we,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:we,rev:we,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:we,requiredFeatures:we,requiredFonts:we,requiredFormats:we,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:P,specularExponent:P,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:P,strikethroughThickness:P,string:null,stroke:null,strokeDashArray:we,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:P,strokeOpacity:P,strokeWidth:null,style:null,surfaceScale:P,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:we,tabIndex:P,tableValues:null,target:null,targetX:P,targetY:P,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:we,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:P,underlineThickness:P,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:P,values:null,vAlphabetic:P,vMathematical:P,vectorEffect:null,vHanging:P,vIdeographic:P,version:null,vertAdvY:P,vertOriginX:P,vertOriginY:P,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:P,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:mo}),xo=dt({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()}}),bo=dt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:yo}),So=dt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Uc={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"},Vc=/[A-Z]/g,ts=/-[a-z]/g,Hc=/^data[-\w.:]+$/i;function qc(e,t){const n=Kn(t);let r=t,s=Se;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Hc.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ts,Qc);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ts.test(i)){let o=i.replace(Vc,Wc);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}s=Sr}return new s(r,t)}function Wc(e){return"-"+e.toLowerCase()}function Qc(e){return e.charAt(1).toUpperCase()}const Gc=po([go,$c,xo,bo,So],"html"),kr=po([go,Kc,xo,bo,So],"svg");function Xc(e){return e.join(" ").trim()}var rt={},pn,ns;function Yc(){if(ns)return pn;ns=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,s=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,a=/^\s+|\s+$/g,l=`
|
|
3
|
+
`,u="/",c="*",d="",p="comment",f="declaration";function y(b,g){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];g=g||{};var v=1,w=1;function N(_){var A=_.match(t);A&&(v+=A.length);var K=_.lastIndexOf(l);w=~K?_.length-K:w+_.length}function j(){var _={line:v,column:w};return function(A){return A.position=new T(_),$(),A}}function T(_){this.start=_,this.end={line:v,column:w},this.source=g.source}T.prototype.content=b;function O(_){var A=new Error(g.source+":"+v+":"+w+": "+_);if(A.reason=_,A.filename=g.source,A.line=v,A.column=w,A.source=b,!g.silent)throw A}function B(_){var A=_.exec(b);if(A){var K=A[0];return N(K),b=b.slice(K.length),A}}function $(){B(n)}function C(_){var A;for(_=_||[];A=R();)A!==!1&&_.push(A);return _}function R(){var _=j();if(!(u!=b.charAt(0)||c!=b.charAt(1))){for(var A=2;d!=b.charAt(A)&&(c!=b.charAt(A)||u!=b.charAt(A+1));)++A;if(A+=2,d===b.charAt(A-1))return O("End of comment missing");var K=b.slice(2,A-2);return w+=2,N(K),b=b.slice(A),w+=2,_({type:p,comment:K})}}function E(){var _=j(),A=B(r);if(A){if(R(),!B(s))return O("property missing ':'");var K=B(i),L=_({type:f,property:m(A[0].replace(e,d)),value:K?m(K[0].replace(e,d)):d});return B(o),L}}function z(){var _=[];C(_);for(var A;A=E();)A!==!1&&(_.push(A),C(_));return _}return $(),z()}function m(b){return b?b.replace(a,d):d}return pn=y,pn}var rs;function Jc(){if(rs)return rt;rs=1;var e=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0}),rt.default=n;const t=e(Yc());function n(r,s){let i=null;if(!r||typeof r!="string")return i;const o=(0,t.default)(r),a=typeof s=="function";return o.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;a?s(u,c,l):c&&(i=i||{},i[u]=c)}),i}return rt}var mt={},ss;function Zc(){if(ss)return mt;ss=1,Object.defineProperty(mt,"__esModule",{value:!0}),mt.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)},o=function(u,c){return c.toUpperCase()},a=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,a):u=u.replace(r,a),u.replace(t,o))};return mt.camelCase=l,mt}var yt,is;function ed(){if(is)return yt;is=1;var e=yt&&yt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},t=e(Jc()),n=Zc();function r(s,i){var o={};return!s||typeof s!="string"||(0,t.default)(s,function(a,l){a&&l&&(o[(0,n.camelCase)(a,i)]=l)}),o}return r.default=r,yt=r,yt}var td=ed();const nd=Ci(td),ko=vo("end"),vr=vo("start");function vo(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 rd(e){const t=vr(e),n=ko(e);if(t&&n)return{start:t,end:n}}function wt(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?os(e.position):"start"in e||"end"in e?os(e):"line"in e||"column"in e?Hn(e):""}function Hn(e){return as(e&&e.line)+":"+as(e&&e.column)}function os(e){return Hn(e&&e.start)+"-"+Hn(e&&e.end)}function as(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={},o=!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&&(o=!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 a=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=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=wt(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=o&&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 wr={}.hasOwnProperty,sd=new Map,id=/[A-Z]/g,od=new Set(["table","tbody","thead","tfoot","tr"]),ad=new Set(["td","th"]),wo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function ld(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=md(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=gd(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"?kr:Gc,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Co(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function Co(e,t,n){if(t.type==="element")return ud(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return cd(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return hd(e,t,n);if(t.type==="mdxjsEsm")return dd(e,t);if(t.type==="root")return fd(e,t,n);if(t.type==="text")return pd(e,t)}function ud(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=kr,e.schema=s),e.ancestors.push(t);const i=Io(e,t.tagName,!1),o=yd(e,t);let a=Tr(e,t);return od.has(t.tagName)&&(a=a.filter(function(l){return typeof l=="string"?!zc(l):!0})),To(e,o,i,t),Cr(o,a),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function cd(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)}Mt(e,t.position)}function dd(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Mt(e,t.position)}function hd(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=kr,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:Io(e,t.name,!0),o=xd(e,t),a=Tr(e,t);return To(e,o,i,t),Cr(o,a),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function fd(e,t,n){const r={};return Cr(r,Tr(e,t)),e.create(t,e.Fragment,r,n)}function pd(e,t){return t.value}function To(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Cr(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function gd(e,t,n){return r;function r(s,i,o,a){const u=Array.isArray(o.children)?n:t;return a?u(i,o,a):u(i,o)}}function md(e,t){return n;function n(r,s,i,o){const a=Array.isArray(i.children),l=vr(r);return t(s,i,o,a,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function yd(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&wr.call(t.properties,s)){const i=bd(e,s,t.properties[s]);if(i){const[o,a]=i;e.tableCellAlignToStyle&&o==="align"&&typeof a=="string"&&ad.has(t.tagName)?r=a:n[o]=a}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function xd(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 o=i.expression;o.type;const a=o.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Mt(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 a=r.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else Mt(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function Tr(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:sd;for(;++r<t.children.length;){const i=t.children[r];let o;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;o=l+"-"+u,s.set(l,u+1)}}const a=Co(e,i,o);a!==void 0&&n.push(a)}return n}function bd(e,t,n){const r=qc(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?jc(n):Xc(n)),r.property==="style"){let s=typeof n=="object"?n:Sd(e,String(n));return e.stylePropertyNameCase==="css"&&(s=kd(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&r.space?Uc[r.property]||r.property:r.attribute,n]}}function Sd(e,t){try{return nd(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=wo+"#cannot-parse-style-attribute",s}}function Io(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,o;for(;++i<s.length;){const a=Jr(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};o=o?{type:"MemberExpression",object:o,property:a,computed:!!(i&&a.type==="Literal"),optional:!1}:a}r=o}else r=Jr(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const s=r.value;return wr.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(r);Mt(e)}function Mt(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=wo+"#cannot-handle-mdx-estrees-without-createevaluater",n}function kd(e){const t={};let n;for(n in e)wr.call(e,n)&&(t[vd(n)]=e[n]);return t}function vd(e){let t=e.replace(id,wd);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function wd(e){return"-"+e.toLowerCase()}const gn={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"]},Cd={};function Ir(e,t){const n=Cd,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Mo(e,r,s)}function Mo(e,t,n){if(Td(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 ls(e.children,t,n)}return Array.isArray(e)?ls(e,t,n):""}function ls(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=Mo(e[s],t,n);return r.join("")}function Td(e){return!!(e&&typeof e=="object")}const us=document.createElement("i");function Mr(e){const t="&"+e+";";us.innerHTML=t;const n=us.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Ce(e,t,n,r){const s=e.length;let i=0,o;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<r.length;)o=r.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function Re(e,t){return e.length>0?(Ce(e,e.length,0,t),e):t}const cs={}.hasOwnProperty;function Ro(e){const t={};let n=-1;for(;++n<e.length;)Id(t,e[n]);return t}function Id(e,t){let n;for(n in t){const s=(cs.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){cs.call(s,o)||(s[o]=[]);const a=i[o];Md(s[o],Array.isArray(a)?a:a?[a]:[])}}}function Md(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);Ce(e,0,0,r)}function Ao(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ne(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ye=Ge(/[A-Za-z]/),ge=Ge(/[\dA-Za-z]/),Rd=Ge(/[#-'*+\--9=?A-Z^-~]/);function Wt(e){return e!==null&&(e<32||e===127)}const qn=Ge(/\d/),Ad=Ge(/[\dA-Fa-f]/),Ed=Ge(/[!-/:-@[-`{-~]/);function U(e){return e!==null&&e<-2}function ee(e){return e!==null&&(e<0||e===32)}function G(e){return e===-2||e===-1||e===32}const rn=Ge(new RegExp("\\p{P}|\\p{S}","u")),et=Ge(/\s/);function Ge(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ht(e){const t=[];let n=-1,r=0,s=0;for(;++n<e.length;){const i=e.charCodeAt(n);let o="";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))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(o=String.fromCharCode(i,a),s=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+s+1,o=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function J(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(l){return G(l)?(e.enter(n),a(l)):t(l)}function a(l){return G(l)&&i++<s?(e.consume(l),a):(e.exit(n),t(l))}}const Ld={tokenize:Nd};function Nd(e){const t=e.attempt(this.parser.constructs.contentInitial,r,s);let n;return t;function r(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),J(e,t,"linePrefix")}function s(a){return e.enter("paragraph"),i(a)}function i(a){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,o(a)}function o(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return U(a)?(e.consume(a),e.exit("chunkText"),i):(e.consume(a),o)}}const Pd={tokenize:jd},ds={tokenize:Dd};function jd(e){const t=this,n=[];let r=0,s,i,o;return a;function a(w){if(r<n.length){const N=n[r];return t.containerState=N[1],e.attempt(N[0].continuation,l,u)(w)}return u(w)}function l(w){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const N=t.events.length;let j=N,T;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){T=t.events[j][1].end;break}g(r);let O=N;for(;O<t.events.length;)t.events[O][1].end={...T},O++;return Ce(t.events,j+1,0,t.events.slice(N)),t.events.length=O,u(w)}return a(w)}function u(w){if(r===n.length){if(!s)return p(w);if(s.currentConstruct&&s.currentConstruct.concrete)return y(w);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(ds,c,d)(w)}function c(w){return s&&v(),g(r),p(w)}function d(w){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,y(w)}function p(w){return t.containerState={},e.attempt(ds,f,y)(w)}function f(w){return r++,n.push([t.currentConstruct,t.containerState]),p(w)}function y(w){if(w===null){s&&v(),g(0),e.consume(w);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),m(w)}function m(w){if(w===null){b(e.exit("chunkFlow"),!0),g(0),e.consume(w);return}return U(w)?(e.consume(w),b(e.exit("chunkFlow")),r=0,t.interrupt=void 0,a):(e.consume(w),m)}function b(w,N){const j=t.sliceStream(w);if(N&&j.push(null),w.previous=i,i&&(i.next=w),i=w,s.defineSkip(w.start),s.write(j),t.parser.lazy[w.start.line]){let T=s.events.length;for(;T--;)if(s.events[T][1].start.offset<o&&(!s.events[T][1].end||s.events[T][1].end.offset>o))return;const O=t.events.length;let B=O,$,C;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){if($){C=t.events[B][1].end;break}$=!0}for(g(r),T=O;T<t.events.length;)t.events[T][1].end={...C},T++;Ce(t.events,B+1,0,t.events.slice(O)),t.events.length=T}}function g(w){let N=n.length;for(;N-- >w;){const j=n[N];t.containerState=j[1],j[0].exit.call(t,e)}n.length=w}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function Dd(e,t,n){return J(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ct(e){if(e===null||ee(e)||et(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 Wn={name:"attention",resolveAll:_d,tokenize:Od};function _d(e,t){let n=-1,r,s,i,o,a,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};hs(d,-l),hs(p,l),o={type:l>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},a={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:{...o.start},end:{...a.end}},e[r][1].end={...o.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Re(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Re(u,[["enter",s,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=Re(u,sn(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Re(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Re(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,Ce(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 Od(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,s=ct(r);let i;return o;function o(l){return i=l,e.enter("attentionSequence"),a(l)}function a(l){if(l===i)return e.consume(l),a;const u=e.exit("attentionSequence"),c=ct(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 hs(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Fd={name:"autolink",tokenize:zd};function zd(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 ye(f)?(e.consume(f),o):f===64?n(f):u(f)}function o(f){return f===43||f===45||f===46||ge(f)?(r=1,a(f)):u(f)}function a(f){return f===58?(e.consume(f),r=0,l):(f===43||f===45||f===46||ge(f))&&r++<32?(e.consume(f),a):(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||Wt(f)?n(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),c):Rd(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 y=f===45?p:d;return e.consume(f),y}return n(f)}}const Pt={partial:!0,tokenize:Bd};function Bd(e,t,n){return r;function r(i){return G(i)?J(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||U(i)?t(i):n(i)}}const Eo={continuation:{tokenize:Kd},exit:Ud,name:"blockQuote",tokenize:$d};function $d(e,t,n){const r=this;return s;function s(o){if(o===62){const a=r.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return n(o)}function i(o){return G(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function Kd(e,t,n){const r=this;return s;function s(o){return G(o)?J(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(Eo,t,n)(o)}}function Ud(e){e.exit("blockQuote")}const Lo={name:"characterEscape",tokenize:Vd};function Vd(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 Ed(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const No={name:"characterReference",tokenize:Hd};function Hd(e,t,n){const r=this;let s=0,i,o;return a;function a(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,o=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,o=Ad,c):(e.enter("characterReferenceValue"),i=7,o=qn,c(d))}function c(d){if(d===59&&s){const p=e.exit("characterReferenceValue");return o===ge&&!Mr(r.sliceSerialize(p))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(d)&&s++<i?(e.consume(d),c):n(d)}}const fs={partial:!0,tokenize:Wd},ps={concrete:!0,name:"codeFenced",tokenize:qd};function qd(e,t,n){const r=this,s={partial:!0,tokenize:j};let i=0,o=0,a;return l;function l(T){return u(T)}function u(T){const O=r.events[r.events.length-1];return i=O&&O[1].type==="linePrefix"?O[2].sliceSerialize(O[1],!0).length:0,a=T,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(T)}function c(T){return T===a?(o++,e.consume(T),c):o<3?n(T):(e.exit("codeFencedFenceSequence"),G(T)?J(e,d,"whitespace")(T):d(T))}function d(T){return T===null||U(T)?(e.exit("codeFencedFence"),r.interrupt?t(T):e.check(fs,m,N)(T)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(T))}function p(T){return T===null||U(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(T)):G(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),J(e,f,"whitespace")(T)):T===96&&T===a?n(T):(e.consume(T),p)}function f(T){return T===null||U(T)?d(T):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),y(T))}function y(T){return T===null||U(T)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(T)):T===96&&T===a?n(T):(e.consume(T),y)}function m(T){return e.attempt(s,N,b)(T)}function b(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),g}function g(T){return i>0&&G(T)?J(e,v,"linePrefix",i+1)(T):v(T)}function v(T){return T===null||U(T)?e.check(fs,m,N)(T):(e.enter("codeFlowValue"),w(T))}function w(T){return T===null||U(T)?(e.exit("codeFlowValue"),v(T)):(e.consume(T),w)}function N(T){return e.exit("codeFenced"),t(T)}function j(T,O,B){let $=0;return C;function C(A){return T.enter("lineEnding"),T.consume(A),T.exit("lineEnding"),R}function R(A){return T.enter("codeFencedFence"),G(A)?J(T,E,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):E(A)}function E(A){return A===a?(T.enter("codeFencedFenceSequence"),z(A)):B(A)}function z(A){return A===a?($++,T.consume(A),z):$>=o?(T.exit("codeFencedFenceSequence"),G(A)?J(T,_,"whitespace")(A):_(A)):B(A)}function _(A){return A===null||U(A)?(T.exit("codeFencedFence"),O(A)):B(A)}}}function Wd(e,t,n){const r=this;return s;function s(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const mn={name:"codeIndented",tokenize:Gd},Qd={partial:!0,tokenize:Xd};function Gd(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),J(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?o(u):n(u)}function o(u){return u===null?l(u):U(u)?e.attempt(Qd,o,l)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||U(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),a)}function l(u){return e.exit("codeIndented"),t(u)}}function Xd(e,t,n){const r=this;return s;function s(o){return r.parser.lazy[r.now().line]?n(o):U(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):J(e,i,"linePrefix",5)(o)}function i(o){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):U(o)?s(o):n(o)}}const Yd={name:"codeText",previous:Zd,resolve:Jd,tokenize:eh};function Jd(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 Zd(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function eh(e,t,n){let r=0,s,i;return o;function o(d){return e.enter("codeText"),e.enter("codeTextSequence"),a(d)}function a(d){return d===96?(e.consume(d),r++,a):(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)):U(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||U(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 th{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&&xt(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),xt(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),xt(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);xt(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);xt(this.left,n.reverse())}}}function xt(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 Po(e){const t={};let n=-1,r,s,i,o,a,l,u;const c=new th(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,nh(c,n)),n=t[n],u=!0);else if(r[1]._container){for(i=n,s=void 0;i--;)if(o=c.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(s&&(c.get(s)[1].type="lineEndingBlank"),o[1].type="lineEnding",s=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;s&&(r[1].end={...c.get(s)[1].start},a=c.slice(s,n),a.unshift(r),c.splice(s,n-s+1,a))}}return Ce(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function nh(e,t){const n=e.get(t)[1],r=e.get(t)[2];let s=t-1;const i=[];let o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,l=[],u={};let c,d,p=-1,f=n,y=0,m=0;const b=[m];for(;f;){for(;e.get(++s)[1]!==f;);i.push(s),f._tokenizer||(c=r.sliceStream(f),f.next||c.push(null),d&&o.defineSkip(f.start),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(c),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++p<a.length;)a[p][0]==="exit"&&a[p-1][0]==="enter"&&a[p][1].type===a[p-1][1].type&&a[p][1].start.line!==a[p][1].end.line&&(m=p+1,b.push(m),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(o.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),p=b.length;p--;){const g=a.slice(b[p],b[p+1]),v=i.pop();l.push([v,v+g.length-1]),e.splice(v,2,g)}for(l.reverse(),p=-1;++p<l.length;)u[y+l[p][0]]=y+l[p][1],y+=l[p][1]-l[p][0]-1;return u}const rh={resolve:ih,tokenize:oh},sh={partial:!0,tokenize:ah};function ih(e){return Po(e),e}function oh(e,t){let n;return r;function r(a){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(a)}function s(a){return a===null?i(a):U(a)?e.check(sh,o,i)(a):(e.consume(a),s)}function i(a){return e.exit("chunkContent"),e.exit("content"),t(a)}function o(a){return e.consume(a),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}function ah(e,t,n){const r=this;return s;function s(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),J(e,i,"linePrefix")}function i(o){if(o===null||U(o))return n(o);const a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function jo(e,t,n,r,s,i,o,a,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||Wt(g)?n(g):(e.enter(r),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),m(g))}function p(g){return g===62?(e.enter(i),e.consume(g),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===62?(e.exit("chunkString"),e.exit(a),p(g)):g===null||g===60||U(g)?n(g):(e.consume(g),g===92?y:f)}function y(g){return g===60||g===62||g===92?(e.consume(g),f):f(g)}function m(g){return!c&&(g===null||g===41||ee(g))?(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(r),t(g)):c<u&&g===40?(e.consume(g),c++,m):g===41?(e.consume(g),c--,m):g===null||g===32||g===40||Wt(g)?n(g):(e.consume(g),g===92?b:m)}function b(g){return g===40||g===41||g===92?(e.consume(g),m):m(g)}}function Do(e,t,n,r,s,i){const o=this;let a=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 a>999||f===null||f===91||f===93&&!l||f===94&&!a&&"_hiddenFootnoteSupport"in o.parser.constructs?n(f):f===93?(e.exit(i),e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):U(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||U(f)||a++>999?(e.exit("chunkString"),c(f)):(e.consume(f),l||(l=!G(f)),f===92?p:d)}function p(f){return f===91||f===92||f===93?(e.consume(f),a++,d):d(f)}}function _o(e,t,n,r,s,i){let o;return a;function a(p){return p===34||p===39||p===40?(e.enter(r),e.enter(s),e.consume(p),e.exit(s),o=p===40?41:p,l):n(p)}function l(p){return p===o?(e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):(e.enter(i),u(p))}function u(p){return p===o?(e.exit(i),l(o)):p===null?n(p):U(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),J(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===o||p===null||U(p)?(e.exit("chunkString"),u(p)):(e.consume(p),p===92?d:c)}function d(p){return p===o||p===92?(e.consume(p),c):c(p)}}function Ct(e,t){let n;return r;function r(s){return U(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):G(s)?J(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const lh={name:"definition",tokenize:ch},uh={partial:!0,tokenize:dh};function ch(e,t,n){const r=this;let s;return i;function i(f){return e.enter("definition"),o(f)}function o(f){return Do.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function a(f){return s=Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):n(f)}function l(f){return ee(f)?Ct(e,u)(f):u(f)}function u(f){return jo(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(uh,d,d)(f)}function d(f){return G(f)?J(e,p,"whitespace")(f):p(f)}function p(f){return f===null||U(f)?(e.exit("definition"),r.parser.defined.push(s),t(f)):n(f)}}function dh(e,t,n){return r;function r(a){return ee(a)?Ct(e,s)(a):n(a)}function s(a){return _o(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return G(a)?J(e,o,"whitespace")(a):o(a)}function o(a){return a===null||U(a)?t(a):n(a)}}const hh={name:"hardBreakEscape",tokenize:fh};function fh(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return U(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const ph={name:"headingAtx",resolve:gh,tokenize:mh};function gh(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"},Ce(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function mh(e,t,n){let r=0;return s;function s(c){return e.enter("atxHeading"),i(c)}function i(c){return e.enter("atxHeadingSequence"),o(c)}function o(c){return c===35&&r++<6?(e.consume(c),o):c===null||ee(c)?(e.exit("atxHeadingSequence"),a(c)):n(c)}function a(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||U(c)?(e.exit("atxHeading"),t(c)):G(c)?J(e,a,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),a(c))}function u(c){return c===null||c===35||ee(c)?(e.exit("atxHeadingText"),a(c)):(e.consume(c),u)}}const yh=["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"],gs=["pre","script","style","textarea"],xh={concrete:!0,name:"htmlFlow",resolveTo:kh,tokenize:vh},bh={partial:!0,tokenize:Ch},Sh={partial:!0,tokenize:wh};function kh(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 vh(e,t,n){const r=this;let s,i,o,a,l;return u;function u(S){return c(S)}function c(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),d}function d(S){return S===33?(e.consume(S),p):S===47?(e.consume(S),i=!0,m):S===63?(e.consume(S),s=3,r.interrupt?t:x):ye(S)?(e.consume(S),o=String.fromCharCode(S),b):n(S)}function p(S){return S===45?(e.consume(S),s=2,f):S===91?(e.consume(S),s=5,a=0,y):ye(S)?(e.consume(S),s=4,r.interrupt?t:x):n(S)}function f(S){return S===45?(e.consume(S),r.interrupt?t:x):n(S)}function y(S){const he="CDATA[";return S===he.charCodeAt(a++)?(e.consume(S),a===he.length?r.interrupt?t:E:y):n(S)}function m(S){return ye(S)?(e.consume(S),o=String.fromCharCode(S),b):n(S)}function b(S){if(S===null||S===47||S===62||ee(S)){const he=S===47,ke=o.toLowerCase();return!he&&!i&&gs.includes(ke)?(s=1,r.interrupt?t(S):E(S)):yh.includes(o.toLowerCase())?(s=6,he?(e.consume(S),g):r.interrupt?t(S):E(S)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(S):i?v(S):w(S))}return S===45||ge(S)?(e.consume(S),o+=String.fromCharCode(S),b):n(S)}function g(S){return S===62?(e.consume(S),r.interrupt?t:E):n(S)}function v(S){return G(S)?(e.consume(S),v):C(S)}function w(S){return S===47?(e.consume(S),C):S===58||S===95||ye(S)?(e.consume(S),N):G(S)?(e.consume(S),w):C(S)}function N(S){return S===45||S===46||S===58||S===95||ge(S)?(e.consume(S),N):j(S)}function j(S){return S===61?(e.consume(S),T):G(S)?(e.consume(S),j):w(S)}function T(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),l=S,O):G(S)?(e.consume(S),T):B(S)}function O(S){return S===l?(e.consume(S),l=null,$):S===null||U(S)?n(S):(e.consume(S),O)}function B(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||ee(S)?j(S):(e.consume(S),B)}function $(S){return S===47||S===62||G(S)?w(S):n(S)}function C(S){return S===62?(e.consume(S),R):n(S)}function R(S){return S===null||U(S)?E(S):G(S)?(e.consume(S),R):n(S)}function E(S){return S===45&&s===2?(e.consume(S),K):S===60&&s===1?(e.consume(S),L):S===62&&s===4?(e.consume(S),oe):S===63&&s===3?(e.consume(S),x):S===93&&s===5?(e.consume(S),ae):U(S)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(bh,re,z)(S)):S===null||U(S)?(e.exit("htmlFlowData"),z(S)):(e.consume(S),E)}function z(S){return e.check(Sh,_,re)(S)}function _(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),A}function A(S){return S===null||U(S)?z(S):(e.enter("htmlFlowData"),E(S))}function K(S){return S===45?(e.consume(S),x):E(S)}function L(S){return S===47?(e.consume(S),o="",Q):E(S)}function Q(S){if(S===62){const he=o.toLowerCase();return gs.includes(he)?(e.consume(S),oe):E(S)}return ye(S)&&o.length<8?(e.consume(S),o+=String.fromCharCode(S),Q):E(S)}function ae(S){return S===93?(e.consume(S),x):E(S)}function x(S){return S===62?(e.consume(S),oe):S===45&&s===2?(e.consume(S),x):E(S)}function oe(S){return S===null||U(S)?(e.exit("htmlFlowData"),re(S)):(e.consume(S),oe)}function re(S){return e.exit("htmlFlow"),t(S)}}function wh(e,t,n){const r=this;return s;function s(o){return U(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):n(o)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function Ch(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Pt,t,n)}}const Th={name:"htmlText",tokenize:Ih};function Ih(e,t,n){const r=this;let s,i,o;return a;function a(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),j):x===63?(e.consume(x),w):ye(x)?(e.consume(x),B):n(x)}function u(x){return x===45?(e.consume(x),c):x===91?(e.consume(x),i=0,y):ye(x)?(e.consume(x),v):n(x)}function c(x){return x===45?(e.consume(x),f):n(x)}function d(x){return x===null?n(x):x===45?(e.consume(x),p):U(x)?(o=d,L(x)):(e.consume(x),d)}function p(x){return x===45?(e.consume(x),f):d(x)}function f(x){return x===62?K(x):x===45?p(x):d(x)}function y(x){const oe="CDATA[";return x===oe.charCodeAt(i++)?(e.consume(x),i===oe.length?m:y):n(x)}function m(x){return x===null?n(x):x===93?(e.consume(x),b):U(x)?(o=m,L(x)):(e.consume(x),m)}function b(x){return x===93?(e.consume(x),g):m(x)}function g(x){return x===62?K(x):x===93?(e.consume(x),g):m(x)}function v(x){return x===null||x===62?K(x):U(x)?(o=v,L(x)):(e.consume(x),v)}function w(x){return x===null?n(x):x===63?(e.consume(x),N):U(x)?(o=w,L(x)):(e.consume(x),w)}function N(x){return x===62?K(x):w(x)}function j(x){return ye(x)?(e.consume(x),T):n(x)}function T(x){return x===45||ge(x)?(e.consume(x),T):O(x)}function O(x){return U(x)?(o=O,L(x)):G(x)?(e.consume(x),O):K(x)}function B(x){return x===45||ge(x)?(e.consume(x),B):x===47||x===62||ee(x)?$(x):n(x)}function $(x){return x===47?(e.consume(x),K):x===58||x===95||ye(x)?(e.consume(x),C):U(x)?(o=$,L(x)):G(x)?(e.consume(x),$):K(x)}function C(x){return x===45||x===46||x===58||x===95||ge(x)?(e.consume(x),C):R(x)}function R(x){return x===61?(e.consume(x),E):U(x)?(o=R,L(x)):G(x)?(e.consume(x),R):$(x)}function E(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),s=x,z):U(x)?(o=E,L(x)):G(x)?(e.consume(x),E):(e.consume(x),_)}function z(x){return x===s?(e.consume(x),s=void 0,A):x===null?n(x):U(x)?(o=z,L(x)):(e.consume(x),z)}function _(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||ee(x)?$(x):(e.consume(x),_)}function A(x){return x===47||x===62||ee(x)?$(x):n(x)}function K(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function L(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),Q}function Q(x){return G(x)?J(e,ae,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):ae(x)}function ae(x){return e.enter("htmlTextData"),o(x)}}const Rr={name:"labelEnd",resolveAll:Eh,resolveTo:Lh,tokenize:Nh},Mh={tokenize:Ph},Rh={tokenize:jh},Ah={tokenize:Dh};function Eh(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&&Ce(e,0,e.length,n),e}function Lh(e,t){let n=e.length,r=0,s,i,o,a;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(o){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"&&(o=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[o][1].end}},c={type:"labelText",start:{...e[i+r+2][1].end},end:{...e[o-2][1].start}};return a=[["enter",l,t],["enter",u,t]],a=Re(a,e.slice(i+1,i+r+3)),a=Re(a,[["enter",c,t]]),a=Re(a,sn(t.parser.constructs.insideSpan.null,e.slice(i+r+4,o-3),t)),a=Re(a,[["exit",c,t],e[o-2],e[o-1],["exit",u,t]]),a=Re(a,e.slice(o+1)),a=Re(a,[["exit",l,t]]),Ce(e,i,e.length,a),e}function Nh(e,t,n){const r=this;let s=r.events.length,i,o;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 a;function a(p){return i?i._inactive?d(p):(o=r.parser.defined.includes(Ne(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),l):n(p)}function l(p){return p===40?e.attempt(Mh,c,o?c:d)(p):p===91?e.attempt(Rh,c,o?u:d)(p):o?c(p):d(p)}function u(p){return e.attempt(Ah,c,d)(p)}function c(p){return t(p)}function d(p){return i._balanced=!0,n(p)}}function Ph(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 ee(d)?Ct(e,i)(d):i(d)}function i(d){return d===41?c(d):jo(e,o,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function o(d){return ee(d)?Ct(e,l)(d):c(d)}function a(d){return n(d)}function l(d){return d===34||d===39||d===40?_o(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return ee(d)?Ct(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 jh(e,t,n){const r=this;return s;function s(a){return Do.call(r,e,i,o,"reference","referenceMarker","referenceString")(a)}function i(a){return r.parser.defined.includes(Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(a):n(a)}function o(a){return n(a)}}function Dh(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 _h={name:"labelStartImage",resolveAll:Rr.resolveAll,tokenize:Oh};function Oh(e,t,n){const r=this;return s;function s(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),i}function i(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),o):n(a)}function o(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const Fh={name:"labelStartLink",resolveAll:Rr.resolveAll,tokenize:zh};function zh(e,t,n){const r=this;return s;function s(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const yn={name:"lineEnding",tokenize:Bh};function Bh(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),J(e,t,"linePrefix")}}const Vt={name:"thematicBreak",tokenize:$h};function $h(e,t,n){let r=0,s;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return s=u,a(u)}function a(u){return u===s?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||U(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===s?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),G(u)?J(e,a,"whitespace")(u):a(u))}}const be={continuation:{tokenize:Hh},exit:Wh,name:"list",tokenize:Vh},Kh={partial:!0,tokenize:Qh},Uh={partial:!0,tokenize:qh};function Vh(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,o=0;return a;function a(f){const y=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:qn(f)){if(r.containerState.type||(r.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Vt,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 qn(f)&&++o<10?(e.consume(f),l):(!r.interrupt||o<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(Pt,r.interrupt?n:c,e.attempt(Kh,p,d))}function c(f){return r.containerState.initialBlankLine=!0,i++,p(f)}function d(f){return G(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 Hh(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Pt,s,i);function s(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,J(e,t,"listItemIndent",r.containerState.size+1)(a)}function i(a){return r.containerState.furtherBlankLines||!G(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Uh,t,o)(a))}function o(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,J(e,e.attempt(be,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function qh(e,t,n){const r=this;return J(e,s,"listItemIndent",r.containerState.size+1);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(i):n(i)}}function Wh(e){e.exit(this.containerState.type)}function Qh(e,t,n){const r=this;return J(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const o=r.events[r.events.length-1];return!G(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const ms={name:"setextUnderline",resolveTo:Gh,tokenize:Xh};function Gh(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 o={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",o,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function Xh(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,o(u)):n(u)}function o(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===s?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),G(u)?J(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||U(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Yh={tokenize:Jh};function Jh(e){const t=this,n=e.attempt(Pt,r,e.attempt(this.parser.constructs.flowInitial,s,J(e,e.attempt(this.parser.constructs.flow,s,e.attempt(rh,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 Zh={resolveAll:Fo()},ef=Oo("string"),tf=Oo("text");function Oo(e){return{resolveAll:Fo(e==="text"?nf:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,o,a);return o;function o(c){return u(c)?i(c):a(c)}function a(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 Fo(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 nf(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,o=-1,a=0,l;for(;i--;){const u=s[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)a++,o--;if(o)break;o=-1}else if(u===-2)l=!0,a++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(a=0),a){const u={type:n===e.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:r.start._bufferIndex+o,_index:r.start._index+i,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},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 rf={42:be,43:be,45:be,48:be,49:be,50:be,51:be,52:be,53:be,54:be,55:be,56:be,57:be,62:Eo},sf={91:lh},of={[-2]:mn,[-1]:mn,32:mn},af={35:ph,42:Vt,45:[ms,Vt],60:xh,61:ms,95:Vt,96:ps,126:ps},lf={38:No,92:Lo},uf={[-5]:yn,[-4]:yn,[-3]:yn,33:_h,38:No,42:Wn,60:[Fd,Th],91:Fh,92:[hh,Lo],93:Rr,95:Wn,96:Yd},cf={null:[Wn,Zh]},df={null:[42,95]},hf={null:[]},ff=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:df,contentInitial:sf,disable:hf,document:rf,flow:af,flowInitial:of,insideSpan:cf,string:lf,text:uf},Symbol.toStringTag,{value:"Module"}));function pf(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 o=[],a=[];const l={attempt:O(j),check:O(T),consume:v,enter:w,exit:N,interrupt:O(T,{interrupt:!0})},u={code:null,containerState:{},defineSkip:m,events:[],now:y,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(R){return o=Re(o,R),b(),o[o.length-1]!==null?[]:(B(t,0),u.events=sn(i,u.events,u),u.events)}function p(R,E){return mf(f(R),E)}function f(R){return gf(o,R)}function y(){const{_bufferIndex:R,_index:E,line:z,column:_,offset:A}=r;return{_bufferIndex:R,_index:E,line:z,column:_,offset:A}}function m(R){s[R.line]=R.column,C()}function b(){let R;for(;r._index<o.length;){const E=o[r._index];if(typeof E=="string")for(R=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===R&&r._bufferIndex<E.length;)g(E.charCodeAt(r._bufferIndex));else g(E)}}function g(R){c=c(R)}function v(R){U(R)?(r.line++,r.column=1,r.offset+=R===-3?2:1,C()):R!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=R}function w(R,E){const z=E||{};return z.type=R,z.start=y(),u.events.push(["enter",z,u]),a.push(z),z}function N(R){const E=a.pop();return E.end=y(),u.events.push(["exit",E,u]),E}function j(R,E){B(R,E.from)}function T(R,E){E.restore()}function O(R,E){return z;function z(_,A,K){let L,Q,ae,x;return Array.isArray(_)?re(_):"tokenize"in _?re([_]):oe(_);function oe(se){return pe;function pe(xe){const Te=xe!==null&&se[xe],Ie=xe!==null&&se.null,Pe=[...Array.isArray(Te)?Te:Te?[Te]:[],...Array.isArray(Ie)?Ie:Ie?[Ie]:[]];return re(Pe)(xe)}}function re(se){return L=se,Q=0,se.length===0?K:S(se[Q])}function S(se){return pe;function pe(xe){return x=$(),ae=se,se.partial||(u.currentConstruct=se),se.name&&u.parser.constructs.disable.null.includes(se.name)?ke():se.tokenize.call(E?Object.assign(Object.create(u),E):u,l,he,ke)(xe)}}function he(se){return R(ae,x),A}function ke(se){return x.restore(),++Q<L.length?S(L[Q]):K}}}function B(R,E){R.resolveAll&&!i.includes(R)&&i.push(R),R.resolve&&Ce(u.events,E,u.events.length-E,R.resolve(u.events.slice(E),u)),R.resolveTo&&(u.events=R.resolveTo(u.events,u))}function $(){const R=y(),E=u.previous,z=u.currentConstruct,_=u.events.length,A=Array.from(a);return{from:_,restore:K};function K(){r=R,u.previous=E,u.currentConstruct=z,u.events.length=_,a=A,C()}}function C(){r.line in s&&r.column<2&&(r.column=s[r.line],r.offset+=s[r.line]-1)}}function gf(e,t){const n=t.start._index,r=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let o;if(n===s)o=[e[n].slice(r,i)];else{if(o=e.slice(n,s),r>-1){const a=o[0];typeof a=="string"?o[0]=a.slice(r):o.shift()}i>0&&o.push(e[s].slice(0,i))}return o}function mf(e,t){let n=-1;const r=[];let s;for(;++n<e.length;){const i=e[n];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
|
|
4
4
|
`;break}case-3:{o=`\r
|
|
5
|
-
`;break}case-2:{o=t?" ":" ";break}case-1:{if(!t&&s)continue;o=" ";break}default:o=String.fromCharCode(i)}s=i===-2,r.push(o)}return r.join("")}function mf(e){const r={constructs:Mo([hf,...(e||{}).extensions||[]]),content:s(Ed),defined:[],document:s(Nd),flow:s(Xh),lazy:{},string:s(Zh),text:s(ef)};return r;function s(i){return o;function o(a){return ff(r,i,a)}}}function yf(e){for(;!No(e););return e}const ys=/[\0\t\n\r]/g;function xf(){let e=1,t="",n=!0,r;return s;function s(i,o,a){const l=[];let u,c,d,p,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(o||void 0).decode(i)),d=0,t="",n&&(i.charCodeAt(0)===65279&&d++,n=void 0);d<i.length;){if(ys.lastIndex=d,u=ys.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 a&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const bf=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Sf(e){return e.replace(bf,kf)}function kf(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const s=n.charCodeAt(1),i=s===120||s===88;return Ro(n.slice(i?2:1),i?16:10)}return Mr(n)||e}const Fo={}.hasOwnProperty;function vf(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),wf(n)(yf(mf(n).document().write(xf()(e,t,!0))))}function wf(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Dt),autolinkProtocol:$,autolinkEmail:$,atxHeading:i(Ye),blockQuote:i(Ie),characterEscape:$,characterReference:$,codeFenced:i(Pe),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:i(Pe,o),codeText:i(Xe,o),codeTextData:$,data:$,codeFlowValue:$,definition:i(ce),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:i(W),hardBreakEscape:i(je),hardBreakTrailing:i(je),htmlFlow:i(ze,o),htmlFlowData:$,htmlText:i(ze,o),htmlTextData:$,image:i(Be),label:o,link:i(Dt),listItem:i(Ba),listItemValue:p,listOrdered:i(ft,d),listUnordered:i(ft),paragraph:i($a),reference:S,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:i(Ye),strong:i(Ka),thematicBreak:i(Va)},exit:{atxHeading:l(),atxHeadingSequence:j,autolink:l(),autolinkEmail:Te,autolinkProtocol:xe,blockQuote:l(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:ke,characterReferenceMarkerNumeric:ke,characterReferenceValue:se,characterReference:pe,codeFenced:l(b),codeFencedFence:m,codeFencedFenceInfo:f,codeFencedFenceMeta:y,codeFlowValue:C,codeIndented:l(g),codeText:l(A),codeTextData:C,data:C,definition:l(),definitionDestinationString:N,definitionLabelString:v,definitionTitleString:w,emphasis:l(),hardBreakEscape:l(E),hardBreakTrailing:l(E),htmlFlow:l(z),htmlFlowData:C,htmlText:l(_),htmlTextData:C,image:l(L),label:ae,labelText:G,lineEnding:R,link:l(K),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:he,resourceDestinationString:x,resourceTitleString:oe,resource:re,setextHeading:l(B),setextHeadingLineSequence:O,setextHeadingText:T,strong:l(),thematicBreak:l()}};zo(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(M){let D={type:"root",children:[]};const H={stack:[D],tokenStack:[],config:t,enter:a,exit:u,buffer:o,resume:c,data:n},Y=[];let Z=-1;for(;++Z<M.length;)if(M[Z][1].type==="listOrdered"||M[Z][1].type==="listUnordered")if(M[Z][0]==="enter")Y.push(Z);else{const Ae=Y.pop();Z=s(M,Ae,Z)}for(Z=-1;++Z<M.length;){const Ae=t[M[Z][0]];Fo.call(Ae,M[Z][1].type)&&Ae[M[Z][1].type].call(Object.assign({sliceSerialize:M[Z][2].sliceSerialize},H),M[Z][1])}if(H.tokenStack.length>0){const Ae=H.tokenStack[H.tokenStack.length-1];(Ae[1]||xs).call(H,void 0,Ae[0])}for(D.position={start:Ge(M.length>0?M[0][1].start:{line:1,column:1,offset:0}),end:Ge(M.length>0?M[M.length-2][1].end:{line:1,column:1,offset:0})},Z=-1;++Z<t.transforms.length;)D=t.transforms[Z](D)||D;return D}function s(M,D,H){let Y=D-1,Z=-1,Ae=!1,Je,$e,pt,gt;for(;++Y<=H;){const ve=M[Y];switch(ve[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ve[0]==="enter"?Z++:Z--,gt=void 0;break}case"lineEndingBlank":{ve[0]==="enter"&&(Je&&!gt&&!Z&&!pt&&(pt=Y),gt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:gt=void 0}if(!Z&&ve[0]==="enter"&&ve[1].type==="listItemPrefix"||Z===-1&&ve[0]==="exit"&&(ve[1].type==="listUnordered"||ve[1].type==="listOrdered")){if(Je){let nt=Y;for($e=void 0;nt--;){const Ke=M[nt];if(Ke[1].type==="lineEnding"||Ke[1].type==="lineEndingBlank"){if(Ke[0]==="exit")continue;$e&&(M[$e][1].type="lineEndingBlank",Ae=!0),Ke[1].type="lineEnding",$e=nt}else if(!(Ke[1].type==="linePrefix"||Ke[1].type==="blockQuotePrefix"||Ke[1].type==="blockQuotePrefixWhitespace"||Ke[1].type==="blockQuoteMarker"||Ke[1].type==="listItemIndent"))break}pt&&(!$e||pt<$e)&&(Je._spread=!0),Je.end=Object.assign({},$e?M[$e][1].start:ve[1].end),M.splice($e||Y,0,["exit",Je,ve[2]]),Y++,H++}if(ve[1].type==="listItemPrefix"){const nt={type:"listItem",_spread:!1,start:Object.assign({},ve[1].start),end:void 0};Je=nt,M.splice(Y,0,["enter",nt,ve[2]]),Y++,H++,pt=void 0,gt=!0}}}return M[D][1]._spread=Ae,H}function i(M,D){return H;function H(Y){a.call(this,M(Y),Y),D&&D.call(this,Y)}}function o(){this.stack.push({type:"fragment",children:[]})}function a(M,D,H){this.stack[this.stack.length-1].children.push(M),this.stack.push(M),this.tokenStack.push([D,H||void 0]),M.position={start:Ge(D.start),end:void 0}}function l(M){return D;function D(H){M&&M.call(this,H),u.call(this,H)}}function u(M,D){const H=this.stack.pop(),Y=this.tokenStack.pop();if(Y)Y[0].type!==M.type&&(D?D.call(this,M,Y[0]):(Y[1]||xs).call(this,M,Y[0]));else throw new Error("Cannot close `"+M.type+"` ("+wt({start:M.start,end:M.end})+"): it’s not open");H.position.end=Ge(M.end)}function c(){return Ir(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function p(M){if(this.data.expectingFirstListItemValue){const D=this.stack[this.stack.length-2];D.start=Number.parseInt(this.sliceSerialize(M),10),this.data.expectingFirstListItemValue=void 0}}function f(){const M=this.resume(),D=this.stack[this.stack.length-1];D.lang=M}function y(){const M=this.resume(),D=this.stack[this.stack.length-1];D.meta=M}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M.replace(/(\r?\n|\r)$/g,"")}function v(M){const D=this.resume(),H=this.stack[this.stack.length-1];H.label=D,H.identifier=Ne(this.sliceSerialize(M)).toLowerCase()}function w(){const M=this.resume(),D=this.stack[this.stack.length-1];D.title=M}function N(){const M=this.resume(),D=this.stack[this.stack.length-1];D.url=M}function j(M){const D=this.stack[this.stack.length-1];if(!D.depth){const H=this.sliceSerialize(M).length;D.depth=H}}function T(){this.data.setextHeadingSlurpLineEnding=!0}function O(M){const D=this.stack[this.stack.length-1];D.depth=this.sliceSerialize(M).codePointAt(0)===61?1:2}function B(){this.data.setextHeadingSlurpLineEnding=void 0}function $(M){const H=this.stack[this.stack.length-1].children;let Y=H[H.length-1];(!Y||Y.type!=="text")&&(Y=Ua(),Y.position={start:Ge(M.start),end:void 0},H.push(Y)),this.stack.push(Y)}function C(M){const D=this.stack.pop();D.value+=this.sliceSerialize(M),D.position.end=Ge(M.end)}function R(M){const D=this.stack[this.stack.length-1];if(this.data.atHardBreak){const H=D.children[D.children.length-1];H.position.end=Ge(M.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(D.type)&&($.call(this,M),C.call(this,M))}function E(){this.data.atHardBreak=!0}function z(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M}function _(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M}function A(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M}function K(){const M=this.stack[this.stack.length-1];if(this.data.inReference){const D=this.data.referenceType||"shortcut";M.type+="Reference",M.referenceType=D,delete M.url,delete M.title}else delete M.identifier,delete M.label;this.data.referenceType=void 0}function L(){const M=this.stack[this.stack.length-1];if(this.data.inReference){const D=this.data.referenceType||"shortcut";M.type+="Reference",M.referenceType=D,delete M.url,delete M.title}else delete M.identifier,delete M.label;this.data.referenceType=void 0}function G(M){const D=this.sliceSerialize(M),H=this.stack[this.stack.length-2];H.label=Sf(D),H.identifier=Ne(D).toLowerCase()}function ae(){const M=this.stack[this.stack.length-1],D=this.resume(),H=this.stack[this.stack.length-1];if(this.data.inReference=!0,H.type==="link"){const Y=M.children;H.children=Y}else H.alt=D}function x(){const M=this.resume(),D=this.stack[this.stack.length-1];D.url=M}function oe(){const M=this.resume(),D=this.stack[this.stack.length-1];D.title=M}function re(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function he(M){const D=this.resume(),H=this.stack[this.stack.length-1];H.label=D,H.identifier=Ne(this.sliceSerialize(M)).toLowerCase(),this.data.referenceType="full"}function ke(M){this.data.characterReferenceType=M.type}function se(M){const D=this.sliceSerialize(M),H=this.data.characterReferenceType;let Y;H?(Y=Ro(D,H==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Y=Mr(D);const Z=this.stack[this.stack.length-1];Z.value+=Y}function pe(M){const D=this.stack.pop();D.position.end=Ge(M.end)}function xe(M){C.call(this,M);const D=this.stack[this.stack.length-1];D.url=this.sliceSerialize(M)}function Te(M){C.call(this,M);const D=this.stack[this.stack.length-1];D.url="mailto:"+this.sliceSerialize(M)}function Ie(){return{type:"blockquote",children:[]}}function Pe(){return{type:"code",lang:null,meta:null,value:""}}function Xe(){return{type:"inlineCode",value:""}}function ce(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function W(){return{type:"emphasis",children:[]}}function Ye(){return{type:"heading",depth:0,children:[]}}function je(){return{type:"break"}}function ze(){return{type:"html",value:""}}function Be(){return{type:"image",title:null,url:"",alt:null}}function Dt(){return{type:"link",title:null,url:"",children:[]}}function ft(M){return{type:"list",ordered:M.type==="listOrdered",start:null,spread:M._spread,children:[]}}function Ba(M){return{type:"listItem",spread:M._spread,checked:null,children:[]}}function $a(){return{type:"paragraph",children:[]}}function Ka(){return{type:"strong",children:[]}}function Ua(){return{type:"text",value:""}}function Va(){return{type:"thematicBreak"}}}function Ge(e){return{line:e.line,column:e.column,offset:e.offset}}function zo(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?zo(e,r):Cf(e,r)}}function Cf(e,t){let n;for(n in t)if(Fo.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 xs(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+wt({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+wt({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+wt({start:t.start,end:t.end})+") is still open")}function Tf(e){const t=this;t.parser=n;function n(r){return vf(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function If(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 Mf(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
6
|
-
`}]}function
|
|
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
|
|
5
|
+
`;break}case-2:{o=t?" ":" ";break}case-1:{if(!t&&s)continue;o=" ";break}default:o=String.fromCharCode(i)}s=i===-2,r.push(o)}return r.join("")}function yf(e){const r={constructs:Ro([ff,...(e||{}).extensions||[]]),content:s(Ld),defined:[],document:s(Pd),flow:s(Yh),lazy:{},string:s(ef),text:s(tf)};return r;function s(i){return o;function o(a){return pf(r,i,a)}}}function xf(e){for(;!Po(e););return e}const ys=/[\0\t\n\r]/g;function bf(){let e=1,t="",n=!0,r;return s;function s(i,o,a){const l=[];let u,c,d,p,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(o||void 0).decode(i)),d=0,t="",n&&(i.charCodeAt(0)===65279&&d++,n=void 0);d<i.length;){if(ys.lastIndex=d,u=ys.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 a&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Sf=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function kf(e){return e.replace(Sf,vf)}function vf(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const s=n.charCodeAt(1),i=s===120||s===88;return Ao(n.slice(i?2:1),i?16:10)}return Mr(n)||e}const zo={}.hasOwnProperty;function wf(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),Cf(n)(xf(yf(n).document().write(bf()(e,t,!0))))}function Cf(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Dt),autolinkProtocol:$,autolinkEmail:$,atxHeading:i(Ye),blockQuote:i(Ie),characterEscape:$,characterReference:$,codeFenced:i(Pe),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:i(Pe,o),codeText:i(Xe,o),codeTextData:$,data:$,codeFlowValue:$,definition:i(ce),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:i(W),hardBreakEscape:i(je),hardBreakTrailing:i(je),htmlFlow:i(ze,o),htmlFlowData:$,htmlText:i(ze,o),htmlTextData:$,image:i(Be),label:o,link:i(Dt),listItem:i(Ka),listItemValue:p,listOrdered:i(ft,d),listUnordered:i(ft),paragraph:i(Ua),reference:S,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:i(Ye),strong:i(Va),thematicBreak:i(qa)},exit:{atxHeading:l(),atxHeadingSequence:j,autolink:l(),autolinkEmail:Te,autolinkProtocol:xe,blockQuote:l(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:ke,characterReferenceMarkerNumeric:ke,characterReferenceValue:se,characterReference:pe,codeFenced:l(b),codeFencedFence:m,codeFencedFenceInfo:f,codeFencedFenceMeta:y,codeFlowValue:C,codeIndented:l(g),codeText:l(A),codeTextData:C,data:C,definition:l(),definitionDestinationString:N,definitionLabelString:v,definitionTitleString:w,emphasis:l(),hardBreakEscape:l(E),hardBreakTrailing:l(E),htmlFlow:l(z),htmlFlowData:C,htmlText:l(_),htmlTextData:C,image:l(L),label:ae,labelText:Q,lineEnding:R,link:l(K),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:he,resourceDestinationString:x,resourceTitleString:oe,resource:re,setextHeading:l(B),setextHeadingLineSequence:O,setextHeadingText:T,strong:l(),thematicBreak:l()}};Bo(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(M){let D={type:"root",children:[]};const H={stack:[D],tokenStack:[],config:t,enter:a,exit:u,buffer:o,resume:c,data:n},Y=[];let Z=-1;for(;++Z<M.length;)if(M[Z][1].type==="listOrdered"||M[Z][1].type==="listUnordered")if(M[Z][0]==="enter")Y.push(Z);else{const Ae=Y.pop();Z=s(M,Ae,Z)}for(Z=-1;++Z<M.length;){const Ae=t[M[Z][0]];zo.call(Ae,M[Z][1].type)&&Ae[M[Z][1].type].call(Object.assign({sliceSerialize:M[Z][2].sliceSerialize},H),M[Z][1])}if(H.tokenStack.length>0){const Ae=H.tokenStack[H.tokenStack.length-1];(Ae[1]||xs).call(H,void 0,Ae[0])}for(D.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})},Z=-1;++Z<t.transforms.length;)D=t.transforms[Z](D)||D;return D}function s(M,D,H){let Y=D-1,Z=-1,Ae=!1,Je,$e,pt,gt;for(;++Y<=H;){const ve=M[Y];switch(ve[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ve[0]==="enter"?Z++:Z--,gt=void 0;break}case"lineEndingBlank":{ve[0]==="enter"&&(Je&&!gt&&!Z&&!pt&&(pt=Y),gt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:gt=void 0}if(!Z&&ve[0]==="enter"&&ve[1].type==="listItemPrefix"||Z===-1&&ve[0]==="exit"&&(ve[1].type==="listUnordered"||ve[1].type==="listOrdered")){if(Je){let nt=Y;for($e=void 0;nt--;){const Ke=M[nt];if(Ke[1].type==="lineEnding"||Ke[1].type==="lineEndingBlank"){if(Ke[0]==="exit")continue;$e&&(M[$e][1].type="lineEndingBlank",Ae=!0),Ke[1].type="lineEnding",$e=nt}else if(!(Ke[1].type==="linePrefix"||Ke[1].type==="blockQuotePrefix"||Ke[1].type==="blockQuotePrefixWhitespace"||Ke[1].type==="blockQuoteMarker"||Ke[1].type==="listItemIndent"))break}pt&&(!$e||pt<$e)&&(Je._spread=!0),Je.end=Object.assign({},$e?M[$e][1].start:ve[1].end),M.splice($e||Y,0,["exit",Je,ve[2]]),Y++,H++}if(ve[1].type==="listItemPrefix"){const nt={type:"listItem",_spread:!1,start:Object.assign({},ve[1].start),end:void 0};Je=nt,M.splice(Y,0,["enter",nt,ve[2]]),Y++,H++,pt=void 0,gt=!0}}}return M[D][1]._spread=Ae,H}function i(M,D){return H;function H(Y){a.call(this,M(Y),Y),D&&D.call(this,Y)}}function o(){this.stack.push({type:"fragment",children:[]})}function a(M,D,H){this.stack[this.stack.length-1].children.push(M),this.stack.push(M),this.tokenStack.push([D,H||void 0]),M.position={start:Qe(D.start),end:void 0}}function l(M){return D;function D(H){M&&M.call(this,H),u.call(this,H)}}function u(M,D){const H=this.stack.pop(),Y=this.tokenStack.pop();if(Y)Y[0].type!==M.type&&(D?D.call(this,M,Y[0]):(Y[1]||xs).call(this,M,Y[0]));else throw new Error("Cannot close `"+M.type+"` ("+wt({start:M.start,end:M.end})+"): it’s not open");H.position.end=Qe(M.end)}function c(){return Ir(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function p(M){if(this.data.expectingFirstListItemValue){const D=this.stack[this.stack.length-2];D.start=Number.parseInt(this.sliceSerialize(M),10),this.data.expectingFirstListItemValue=void 0}}function f(){const M=this.resume(),D=this.stack[this.stack.length-1];D.lang=M}function y(){const M=this.resume(),D=this.stack[this.stack.length-1];D.meta=M}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M.replace(/(\r?\n|\r)$/g,"")}function v(M){const D=this.resume(),H=this.stack[this.stack.length-1];H.label=D,H.identifier=Ne(this.sliceSerialize(M)).toLowerCase()}function w(){const M=this.resume(),D=this.stack[this.stack.length-1];D.title=M}function N(){const M=this.resume(),D=this.stack[this.stack.length-1];D.url=M}function j(M){const D=this.stack[this.stack.length-1];if(!D.depth){const H=this.sliceSerialize(M).length;D.depth=H}}function T(){this.data.setextHeadingSlurpLineEnding=!0}function O(M){const D=this.stack[this.stack.length-1];D.depth=this.sliceSerialize(M).codePointAt(0)===61?1:2}function B(){this.data.setextHeadingSlurpLineEnding=void 0}function $(M){const H=this.stack[this.stack.length-1].children;let Y=H[H.length-1];(!Y||Y.type!=="text")&&(Y=Ha(),Y.position={start:Qe(M.start),end:void 0},H.push(Y)),this.stack.push(Y)}function C(M){const D=this.stack.pop();D.value+=this.sliceSerialize(M),D.position.end=Qe(M.end)}function R(M){const D=this.stack[this.stack.length-1];if(this.data.atHardBreak){const H=D.children[D.children.length-1];H.position.end=Qe(M.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(D.type)&&($.call(this,M),C.call(this,M))}function E(){this.data.atHardBreak=!0}function z(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M}function _(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M}function A(){const M=this.resume(),D=this.stack[this.stack.length-1];D.value=M}function K(){const M=this.stack[this.stack.length-1];if(this.data.inReference){const D=this.data.referenceType||"shortcut";M.type+="Reference",M.referenceType=D,delete M.url,delete M.title}else delete M.identifier,delete M.label;this.data.referenceType=void 0}function L(){const M=this.stack[this.stack.length-1];if(this.data.inReference){const D=this.data.referenceType||"shortcut";M.type+="Reference",M.referenceType=D,delete M.url,delete M.title}else delete M.identifier,delete M.label;this.data.referenceType=void 0}function Q(M){const D=this.sliceSerialize(M),H=this.stack[this.stack.length-2];H.label=kf(D),H.identifier=Ne(D).toLowerCase()}function ae(){const M=this.stack[this.stack.length-1],D=this.resume(),H=this.stack[this.stack.length-1];if(this.data.inReference=!0,H.type==="link"){const Y=M.children;H.children=Y}else H.alt=D}function x(){const M=this.resume(),D=this.stack[this.stack.length-1];D.url=M}function oe(){const M=this.resume(),D=this.stack[this.stack.length-1];D.title=M}function re(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function he(M){const D=this.resume(),H=this.stack[this.stack.length-1];H.label=D,H.identifier=Ne(this.sliceSerialize(M)).toLowerCase(),this.data.referenceType="full"}function ke(M){this.data.characterReferenceType=M.type}function se(M){const D=this.sliceSerialize(M),H=this.data.characterReferenceType;let Y;H?(Y=Ao(D,H==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Y=Mr(D);const Z=this.stack[this.stack.length-1];Z.value+=Y}function pe(M){const D=this.stack.pop();D.position.end=Qe(M.end)}function xe(M){C.call(this,M);const D=this.stack[this.stack.length-1];D.url=this.sliceSerialize(M)}function Te(M){C.call(this,M);const D=this.stack[this.stack.length-1];D.url="mailto:"+this.sliceSerialize(M)}function Ie(){return{type:"blockquote",children:[]}}function Pe(){return{type:"code",lang:null,meta:null,value:""}}function Xe(){return{type:"inlineCode",value:""}}function ce(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function W(){return{type:"emphasis",children:[]}}function Ye(){return{type:"heading",depth:0,children:[]}}function je(){return{type:"break"}}function ze(){return{type:"html",value:""}}function Be(){return{type:"image",title:null,url:"",alt:null}}function Dt(){return{type:"link",title:null,url:"",children:[]}}function ft(M){return{type:"list",ordered:M.type==="listOrdered",start:null,spread:M._spread,children:[]}}function Ka(M){return{type:"listItem",spread:M._spread,checked:null,children:[]}}function Ua(){return{type:"paragraph",children:[]}}function Va(){return{type:"strong",children:[]}}function Ha(){return{type:"text",value:""}}function qa(){return{type:"thematicBreak"}}}function Qe(e){return{line:e.line,column:e.column,offset:e.offset}}function Bo(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?Bo(e,r):Tf(e,r)}}function Tf(e,t){let n;for(n in t)if(zo.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 xs(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+wt({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+wt({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+wt({start:t.start,end:t.end})+") is still open")}function If(e){const t=this;t.parser=n;function n(r){return wf(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function Mf(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 Rf(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
6
|
+
`}]}function Af(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 Lf(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=ht(r.toLowerCase()),i=e.footnoteOrder.indexOf(r);let o,a=e.footnoteCounts.get(r);a===void 0?(a=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=i+1,a+=1,e.footnoteCounts.set(r,a);const l={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+s,id:n+"fnref-"+s+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function Pf(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 jf(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function $o(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 o=s[s.length-1];return o&&o.type==="text"?o.value+=r:s.push({type:"text",value:r}),s}function Df(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return $o(e,t);const s={src:ht(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 _f(e,t){const n={src:ht(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 Of(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 Ff(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return $o(e,t);const s={href:ht(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 zf(e,t){const n={href:ht(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 Bf(e,t,n){const r=e.all(t),s=n?$f(n):Ko(t),i={},o=[];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 a=-1;for(;++a<r.length;){const c=r[a];(s||a!==0||c.type!=="element"||c.tagName!=="p")&&o.push({type:"text",value:`
|
|
8
8
|
`}),c.type==="element"&&c.tagName==="p"&&!s?o.push(...c.children):o.push(c)}const l=r[r.length-1];l&&(s||l.type!=="element"||l.tagName!=="p")&&o.push({type:"text",value:`
|
|
9
|
-
`});const u={type:"element",tagName:"li",properties:i,children:o};return e.patch(t,u),e.applyData(t,u)}function
|
|
9
|
+
`});const u={type:"element",tagName:"li",properties:i,children:o};return e.patch(t,u),e.applyData(t,u)}function $f(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=Ko(n[r])}return t}function Ko(e){const t=e.spread;return t??e.children.length>1}function Kf(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 o=r[s];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.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 Uf(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Vf(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function Hf(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qf(e,t){const n=e.all(t),r=n.shift(),s=[];if(r){const o={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],o),s.push(o)}if(n.length>0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},a=vr(t.children[1]),l=ko(t.children[t.children.length-1]);a&&l&&(o.position={start:a,end:l}),s.push(o)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function Wf(e,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",o=n&&n.type==="table"?n.align:void 0,a=o?o.length:t.children.length;let l=-1;const u=[];for(;++l<a;){const d=t.children[l],p={},f=o?o[l]:void 0;f&&(p.align=f);let y={type:"element",tagName:i,properties:p,children:[]};d&&(y.children=e.all(d),e.patch(d,y),y=e.applyData(d,y)),u.push(y)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,c),e.applyData(t,c)}function Qf(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const bs=9,Ss=32;function Gf(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),s=0;const i=[];for(;r;)i.push(ks(t.slice(s,r.index),s>0,!0),r[0]),s=r.index+r[0].length,r=n.exec(t);return i.push(ks(t.slice(s),s>0,!1)),i.join("")}function ks(e,t,n){let r=0,s=e.length;if(t){let i=e.codePointAt(r);for(;i===bs||i===Ss;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(s-1);for(;i===bs||i===Ss;)s--,i=e.codePointAt(s-1)}return s>r?e.slice(r,s):""}function Xf(e,t){const n={type:"text",value:Gf(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Yf(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Jf={blockquote:Mf,break:Rf,code:Af,delete:Ef,emphasis:Lf,footnoteReference:Nf,heading:Pf,html:jf,imageReference:Df,image:_f,inlineCode:Of,linkReference:Ff,link:zf,listItem:Bf,list:Kf,paragraph:Uf,root:Vf,strong:Hf,table:qf,tableCell:Qf,tableRow:Wf,text:Xf,thematicBreak:Yf,toml:_t,yaml:_t,definition:_t,footnoteDefinition:_t};function _t(){}const Uo=-1,on=0,Tt=1,Qt=2,Ar=3,Er=4,Lr=5,Nr=6,Vo=7,Ho=8,vs=typeof self=="object"?self:globalThis,Zf=(e,t)=>{const n=(s,i)=>(e.set(i,s),s),r=s=>{if(e.has(s))return e.get(s);const[i,o]=t[s];switch(i){case on:case Uo:return n(o,s);case Tt:{const a=n([],s);for(const l of o)a.push(r(l));return a}case Qt:{const a=n({},s);for(const[l,u]of o)a[r(l)]=r(u);return a}case Ar:return n(new Date(o),s);case Er:{const{source:a,flags:l}=o;return n(new RegExp(a,l),s)}case Lr:{const a=n(new Map,s);for(const[l,u]of o)a.set(r(l),r(u));return a}case Nr:{const a=n(new Set,s);for(const l of o)a.add(r(l));return a}case Vo:{const{name:a,message:l}=o;return n(new vs[a](l),s)}case Ho:return n(BigInt(o),s);case"BigInt":return n(Object(BigInt(o)),s);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:a}=new Uint8Array(o);return n(new DataView(a),o)}}return n(new vs[i](o),s)};return r},ws=e=>Zf(new Map,e)(0),st="",{toString:ep}={},{keys:tp}=Object,bt=e=>{const t=typeof e;if(t!=="object"||!e)return[on,t];const n=ep.call(e).slice(8,-1);switch(n){case"Array":return[Tt,st];case"Object":return[Qt,st];case"Date":return[Ar,st];case"RegExp":return[Er,st];case"Map":return[Lr,st];case"Set":return[Nr,st];case"DataView":return[Tt,n]}return n.includes("Array")?[Tt,n]:n.includes("Error")?[Vo,n]:[Qt,n]},Ot=([e,t])=>e===on&&(t==="function"||t==="symbol"),np=(e,t,n,r)=>{const s=(o,a)=>{const l=r.push(o)-1;return n.set(a,l),l},i=o=>{if(n.has(o))return n.get(o);let[a,l]=bt(o);switch(a){case on:{let c=o;switch(l){case"bigint":a=Ho,c=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return s([Uo],o)}return s([a,c],o)}case Tt:{if(l){let p=o;return l==="DataView"?p=new Uint8Array(o.buffer):l==="ArrayBuffer"&&(p=new Uint8Array(o)),s([l,[...p]],o)}const c=[],d=s([a,c],o);for(const p of o)c.push(i(p));return d}case Qt:{if(l)switch(l){case"BigInt":return s([l,o.toString()],o);case"Boolean":case"Number":case"String":return s([l,o.valueOf()],o)}if(t&&"toJSON"in o)return i(o.toJSON());const c=[],d=s([a,c],o);for(const p of tp(o))(e||!Ot(bt(o[p])))&&c.push([i(p),i(o[p])]);return d}case Ar:return s([a,o.toISOString()],o);case Er:{const{source:c,flags:d}=o;return s([a,{source:c,flags:d}],o)}case Lr:{const c=[],d=s([a,c],o);for(const[p,f]of o)(e||!(Ot(bt(p))||Ot(bt(f))))&&c.push([i(p),i(f)]);return d}case Nr:{const c=[],d=s([a,c],o);for(const p of o)(e||!Ot(bt(p)))&&c.push(i(p));return d}}const{message:u}=o;return s([a,{name:l,message:u}],o)};return i},Cs=(e,{json:t,lossy:n}={})=>{const r=[];return np(!(t||n),!!t,new Map,r)(e),r},Gt=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?ws(Cs(e,t)):structuredClone(e):(e,t)=>ws(Cs(e,t));function rp(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 sp(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function ip(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||rp,r=e.options.footnoteBackLabel||sp,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];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=ht(d.toLowerCase());let f=0;const y=[],m=e.footnoteCounts.get(d);for(;m!==void 0&&++f<=m;){y.length>0&&y.push({type:"text",value:" "});let v=typeof n=="string"?n:n(l,f);typeof v=="string"&&(v={type:"text",value:v}),y.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(v)?v:[v]})}const b=c[c.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const v=b.children[b.children.length-1];v&&v.type==="text"?v.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...y)}else c.push(...y);const g={type:"element",tagName:"li",properties:{id:t+"fn-"+p},children:e.wrap(c,!0)};e.patch(u,g),a.push(g)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Gt(o),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:`
|
|
10
10
|
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:`
|
|
11
|
-
`}]}}const an=(function(e){if(e==null)return
|
|
11
|
+
`}]}}const an=(function(e){if(e==null)return up;if(typeof e=="function")return ln(e);if(typeof e=="object")return Array.isArray(e)?op(e):ap(e);if(typeof e=="string")return lp(e);throw new Error("Expected function, string, or object as test")});function op(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=an(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 ap(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 lp(e){return ln(t);function t(n){return n&&n.type===e}}function ln(e){return t;function t(n,r,s){return!!(cp(n)&&e.call(this,n,typeof r=="number"?r:void 0,s||void 0))}}function up(){return!0}function cp(e){return e!==null&&typeof e=="object"&&"type"in e}const qo=[],dp=!0,Qn=!1,hp="skip";function Wo(e,t,n,r){let s;typeof t=="function"&&typeof n!="function"?(r=n,n=t):s=t;const i=an(s),o=r?-1:1;a(e,void 0,[])();function a(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=qo,y,m,b;if((!t||i(l,u,c[c.length-1]||void 0))&&(f=fp(n(l,c)),f[0]===Qn))return f;if("children"in l&&l.children){const g=l;if(g.children&&f[0]!==hp)for(m=(r?g.children.length:-1)+o,b=c.concat(g);m>-1&&m<g.children.length;){const v=g.children[m];if(y=a(v,m,b)(),y[0]===Qn)return y;m=typeof y[1]=="number"?y[1]:m+o}}return f}}}function fp(e){return Array.isArray(e)?e:typeof e=="number"?[dp,e]:e==null?qo:[e]}function Pr(e,t,n,r){let s,i,o;typeof t=="function"&&typeof n!="function"?(i=void 0,o=t,s=n):(i=t,o=n,s=r),Wo(e,i,a,s);function a(l,u){const c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return o(l,d,c)}}const Gn={}.hasOwnProperty,pp={};function gp(e,t){const n=t||pp,r=new Map,s=new Map,i=new Map,o={...Jf,...n.handlers},a={all:u,applyData:yp,definitionById:r,footnoteById:s,footnoteCounts:i,footnoteOrder:[],handlers:o,one:l,options:n,patch:mp,wrap:bp};return Pr(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?r:s,p=String(c.identifier).toUpperCase();d.has(p)||d.set(p,c)}}),a;function l(c,d){const p=c.type,f=a.handlers[p];if(Gn.call(a.handlers,p)&&f)return f(a,c,d);if(a.options.passThrough&&a.options.passThrough.includes(p)){if("children"in c){const{children:m,...b}=c,g=Gt(b);return g.children=a.all(c),g}return Gt(c)}return(a.options.unknownHandler||xp)(a,c,d)}function u(c){const d=[];if("children"in c){const p=c.children;let f=-1;for(;++f<p.length;){const y=a.one(p[f],c);if(y){if(f&&p[f-1].type==="break"&&(!Array.isArray(y)&&y.type==="text"&&(y.value=Ts(y.value)),!Array.isArray(y)&&y.type==="element")){const m=y.children[0];m&&m.type==="text"&&(m.value=Ts(m.value))}Array.isArray(y)?d.push(...y):d.push(y)}}}return d}}function mp(e,t){e.position&&(t.position=rd(e))}function yp(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 o="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:o}}n.type==="element"&&i&&Object.assign(n.properties,Gt(i)),"children"in n&&n.children&&s!==null&&s!==void 0&&(n.children=s)}return n}function xp(e,t){const n=t.data||{},r="value"in t&&!(Gn.call(n,"hProperties")||Gn.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 bp(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:`
|
|
12
12
|
`});++r<e.length;)r&&n.push({type:"text",value:`
|
|
13
13
|
`}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
14
|
-
`}),n}function Ts(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Is(e,t){const n=
|
|
15
|
-
`},s),i}function bp(e,t){return e&&"run"in e?async function(n,r){const s=Is(n,{file:r,...t});await e.run(s,r)}:function(n,r){return Is(n,{file:r,...e||t})}}function Ms(e){if(e)throw e}var xn,Rs;function Sp(){if(Rs)return xn;Rs=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)},o=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},a=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return xn=function l(){var u,c,d,p,f,y,m=arguments[0],b=1,g=arguments.length,v=!1;for(typeof m=="boolean"&&(v=m,m=arguments[1]||{},b=2),(m==null||typeof m!="object"&&typeof m!="function")&&(m={});b<g;++b)if(u=arguments[b],u!=null)for(c in u)d=a(m,c),p=a(u,c),m!==p&&(v&&p&&(i(p)||(f=s(p)))?(f?(f=!1,y=d&&s(d)?d:[]):y=d&&i(d)?d:{},o(m,{name:c,newValue:l(v,y,p)})):typeof p<"u"&&o(m,{name:c,newValue:p}));return m},xn}var kp=Sp();const bn=Ci(kp);function Xn(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 vp(){const e=[],t={run:n,use:r};return t;function n(...s){let i=-1;const o=s.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);a(null,...s);function a(l,...u){const c=e[++i];let d=-1;if(l){o(l);return}for(;++d<s.length;)(u[d]===null||u[d]===void 0)&&(u[d]=s[d]);s=u,c?wp(c,a)(...u):o(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 wp(e,t){let n;return r;function r(...o){const a=e.length>o.length;let l;a&&o.push(s);try{l=e.apply(this,o)}catch(u){const c=u;if(a&&n)throw c;return s(c)}a||(l&&l.then&&typeof l.then=="function"?l.then(i,s):l instanceof Error?s(l):i(l))}function s(o,...a){n||(n=!0,t(o,...a))}function i(o){s(null,o)}}const _e={basename:Cp,dirname:Tp,extname:Ip,join:Mp,sep:"/"};function Cp(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');jt(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 o=-1,a=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else o<0&&(i=!0,o=s+1),a>-1&&(e.codePointAt(s)===t.codePointAt(a--)?a<0&&(r=s):(a=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Tp(e){if(jt(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 Ip(e){jt(e);let t=e.length,n=-1,r=0,s=-1,i=0,o;for(;t--;){const a=e.codePointAt(t);if(a===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),a===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 Mp(...e){let t=-1,n;for(;++t<e.length;)jt(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":Rp(n)}function Rp(e){jt(e);const t=e.codePointAt(0)===47;let n=Ap(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Ap(e,t){let n="",r=0,s=-1,i=0,o=-1,a,l;for(;++o<=e.length;){if(o<e.length)a=e.codePointAt(o);else{if(a===47)break;a=47}if(a===47){if(!(s===o-1||i===1))if(s!==o-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=o,i=0;continue}}else if(n.length>0){n="",r=0,s=o,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,o):n=e.slice(s+1,o),r=o-s-1;s=o,i=0}else a===46&&i>-1?i++:i=-1}return n}function jt(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Ep={cwd:Lp};function Lp(){return"/"}function Yn(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Np(e){if(typeof e=="string")e=new URL(e);else if(!Yn(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 Pp(e)}function Pp(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 Sn=["history","path","basename","stem","extname","dirname"];class Wo{constructor(t){let n;t?Yn(t)?n={path:t}:typeof t=="string"||jp(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Ep.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Sn.length;){const i=Sn[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)Sn.includes(s)||(this[s]=n[s])}get basename(){return typeof this.path=="string"?_e.basename(this.path):void 0}set basename(t){vn(t,"basename"),kn(t,"basename"),this.path=_e.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?_e.dirname(this.path):void 0}set dirname(t){As(this.basename,"dirname"),this.path=_e.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?_e.extname(this.path):void 0}set extname(t){if(kn(t,"extname"),As(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=_e.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Yn(t)&&(t=Np(t)),vn(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?_e.basename(this.path,this.extname):void 0}set stem(t){vn(t,"stem"),kn(t,"stem"),this.path=_e.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 kn(e,t){if(e&&e.includes(_e.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+_e.sep+"`")}function vn(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function As(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function jp(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Dp=(function(e){const r=this.constructor.prototype,s=r[e],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,r),i}),_p={}.hasOwnProperty;class jr extends Dp{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=vp()}copy(){const t=new jr;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(bn(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Tn("data",this.frozen),this.namespace[t]=n,this):_p.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Tn("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=Ft(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),Cn("process",this.compiler||this.Compiler),n?s(void 0,n):new Promise(s);function s(i,o){const a=Ft(t),l=r.parse(a);r.run(l,a,function(c,d,p){if(c||!d||!p)return u(c);const f=d,y=r.stringify(f,p);zp(y)?p.value=y:p.result=y,u(c,p)});function u(c,d){c||!d?o(c):i?i(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),wn("processSync",this.parser||this.Parser),Cn("processSync",this.compiler||this.Compiler),this.process(t,s),Ls("processSync","process",n),r;function s(i,o){n=!0,Ms(i),r=o}}run(t,n,r){Es(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(o,a){const l=Ft(n);s.run(t,l,u);function u(c,d,p){const f=d||t;c?a(c):o?o(f):r(void 0,f,p)}}}runSync(t,n){let r=!1,s;return this.run(t,n,i),Ls("runSync","run",r),s;function i(o,a){Ms(o),s=a,r=!0}}stringify(t,n){this.freeze();const r=Ft(n),s=this.compiler||this.Compiler;return Cn("stringify",s),Es(t),s(t,r)}use(t,...n){const r=this.attachers,s=this.namespace;if(Tn("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?a(t):o(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 o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(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");a(u.plugins),u.settings&&(s.settings=bn(!0,s.settings,u.settings))}function a(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,...y]=c;const m=r[p][1];Xn(m)&&Xn(f)&&(f=bn(!0,m,f)),r[p]=[u,f,...y]}}}}const Op=new jr().freeze();function wn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Cn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Tn(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 Es(e){if(!Xn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ls(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Ft(e){return Fp(e)?e:new Wo(e)}function Fp(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function zp(e){return typeof e=="string"||Bp(e)}function Bp(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const $p="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ns=[],Ps={allowDangerousHtml:!0},Kp=/^(https?|ircs?|mailto|xmpp)$/i,Up=[{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 Vp(e){const t=Hp(e),n=qp(e);return Wp(t.runSync(t.parse(n),n),e)}function Hp(e){const t=e.rehypePlugins||Ns,n=e.remarkPlugins||Ns,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Ps}:Ps;return Op().use(Tf).use(n).use(bp,r).use(t)}function qp(e){const t=e.children||"",n=new Wo;return typeof t=="string"&&(n.value=t),n}function Wp(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,o=t.skipHtml,a=t.unwrapDisallowed,l=t.urlTransform||Gp;for(const c of Up)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+$p+c.id,void 0);return Pr(e,u),ad(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 o?p.children.splice(d,1):p.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let f;for(f in gn)if(Object.hasOwn(gn,f)&&Object.hasOwn(c.properties,f)){const y=c.properties[f],m=gn[f];(m===null||m.includes(c.tagName))&&(c.properties[f]=l(String(y||""),f,c))}}if(c.type==="element"){let f=n?!n.includes(c.tagName):i?i.includes(c.tagName):!1;if(!f&&r&&typeof d=="number"&&(f=!r(c,d,p)),f&&p&&typeof d=="number")return a&&c.children?p.children.splice(d,1,...c.children):p.children.splice(d,1),d}}}function Gp(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||Kp.test(e.slice(0,t))?e:""}function js(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 Qp(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Xp(e,t,n){const s=an((n||{}).ignore||[]),i=Yp(t);let o=-1;for(;++o<i.length;)qo(e,"text",a);function a(u,c){let d=-1,p;for(;++d<c.length;){const f=c[d],y=p?p.children:void 0;if(s(f,y?y.indexOf(f):void 0,p))return;p=f}if(p)return l(u,c)}function l(u,c){const d=c[c.length-1],p=i[o][0],f=i[o][1];let y=0;const b=d.children.indexOf(u);let g=!1,v=[];p.lastIndex=0;let w=p.exec(u.value);for(;w;){const N=w.index,j={index:w.index,input:w.input,stack:[...c,u]};let T=f(...w,j);if(typeof T=="string"&&(T=T.length>0?{type:"text",value:T}:void 0),T===!1?p.lastIndex=N+1:(y!==N&&v.push({type:"text",value:u.value.slice(y,N)}),Array.isArray(T)?v.push(...T):T&&v.push(T),y=N+w[0].length,g=!0),!p.global)break;w=p.exec(u.value)}return g?(y<u.value.length&&v.push({type:"text",value:u.value.slice(y)}),d.children.splice(b,1,...v)):v=[u],b+v.length}}function Yp(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([Jp(s[0]),Zp(s[1])])}return t}function Jp(e){return typeof e=="string"?new RegExp(Qp(e),"g"):e}function Zp(e){return typeof e=="function"?e:function(){return e}}const In="phrasing",Mn=["autolink","link","image","label"];function eg(){return{transforms:[ag],enter:{literalAutolink:ng,literalAutolinkEmail:Rn,literalAutolinkHttp:Rn,literalAutolinkWww:Rn},exit:{literalAutolink:og,literalAutolinkEmail:ig,literalAutolinkHttp:rg,literalAutolinkWww:sg}}}function tg(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:In,notInConstruct:Mn},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:In,notInConstruct:Mn},{character:":",before:"[ps]",after:"\\/",inConstruct:In,notInConstruct:Mn}]}}function ng(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Rn(e){this.config.enter.autolinkProtocol.call(this,e)}function rg(e){this.config.exit.autolinkProtocol.call(this,e)}function sg(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 ig(e){this.config.exit.autolinkEmail.call(this,e)}function og(e){this.exit(e)}function ag(e){Xp(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,lg],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),ug]],{ignore:["link","linkReference"]})}function lg(e,t,n,r,s){let i="";if(!Go(s)||(/^w/i.test(t)&&(n=t+n,t="",i="http://"),!cg(n)))return!1;const o=dg(n+r);if(!o[0])return!1;const a={type:"link",title:null,url:i+t+o[0],children:[{type:"text",value:t+o[0]}]};return o[1]?[a,{type:"text",value:o[1]}]:a}function ug(e,t,n,r){return!Go(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function cg(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 dg(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=js(e,"(");let i=js(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 Go(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||et(n)||rn(n))&&(!t||n!==47)}Qo.peek=Sg;function hg(){this.buffer()}function fg(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function pg(){this.buffer()}function gg(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function mg(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(e)).toLowerCase(),n.label=t}function yg(e){this.exit(e)}function xg(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(e)).toLowerCase(),n.label=t}function bg(e){this.exit(e)}function Sg(){return"["}function Qo(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const o=n.enter("footnoteReference"),a=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),a(),o(),i+=s.move("]"),i}function kg(){return{enter:{gfmFootnoteCallString:hg,gfmFootnoteCall:fg,gfmFootnoteDefinitionLabelString:pg,gfmFootnoteDefinition:gg},exit:{gfmFootnoteCallString:mg,gfmFootnoteCall:yg,gfmFootnoteDefinitionLabelString:xg,gfmFootnoteDefinition:bg}}}function vg(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Qo},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,o){const a=i.createTracker(o);let l=a.move("[^");const u=i.enter("footnoteDefinition"),c=i.enter("label");return l+=a.move(i.safe(i.associationId(r),{before:l,after:"]"})),c(),l+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),l+=a.move((t?`
|
|
16
|
-
`:" ")+i.indentLines(i.containerFlow(r,a.current()),t?
|
|
17
|
-
`)}function
|
|
18
|
-
`&&
|
|
19
|
-
`}function
|
|
14
|
+
`}),n}function Ts(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Is(e,t){const n=gp(e,t),r=n.one(e,void 0),s=ip(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 Sp(e,t){return e&&"run"in e?async function(n,r){const s=Is(n,{file:r,...t});await e.run(s,r)}:function(n,r){return Is(n,{file:r,...e||t})}}function Ms(e){if(e)throw e}var xn,Rs;function kp(){if(Rs)return xn;Rs=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)},o=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},a=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return xn=function l(){var u,c,d,p,f,y,m=arguments[0],b=1,g=arguments.length,v=!1;for(typeof m=="boolean"&&(v=m,m=arguments[1]||{},b=2),(m==null||typeof m!="object"&&typeof m!="function")&&(m={});b<g;++b)if(u=arguments[b],u!=null)for(c in u)d=a(m,c),p=a(u,c),m!==p&&(v&&p&&(i(p)||(f=s(p)))?(f?(f=!1,y=d&&s(d)?d:[]):y=d&&i(d)?d:{},o(m,{name:c,newValue:l(v,y,p)})):typeof p<"u"&&o(m,{name:c,newValue:p}));return m},xn}var vp=kp();const bn=Ci(vp);function Xn(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 wp(){const e=[],t={run:n,use:r};return t;function n(...s){let i=-1;const o=s.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);a(null,...s);function a(l,...u){const c=e[++i];let d=-1;if(l){o(l);return}for(;++d<s.length;)(u[d]===null||u[d]===void 0)&&(u[d]=s[d]);s=u,c?Cp(c,a)(...u):o(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 Cp(e,t){let n;return r;function r(...o){const a=e.length>o.length;let l;a&&o.push(s);try{l=e.apply(this,o)}catch(u){const c=u;if(a&&n)throw c;return s(c)}a||(l&&l.then&&typeof l.then=="function"?l.then(i,s):l instanceof Error?s(l):i(l))}function s(o,...a){n||(n=!0,t(o,...a))}function i(o){s(null,o)}}const _e={basename:Tp,dirname:Ip,extname:Mp,join:Rp,sep:"/"};function Tp(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');jt(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 o=-1,a=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else o<0&&(i=!0,o=s+1),a>-1&&(e.codePointAt(s)===t.codePointAt(a--)?a<0&&(r=s):(a=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Ip(e){if(jt(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 Mp(e){jt(e);let t=e.length,n=-1,r=0,s=-1,i=0,o;for(;t--;){const a=e.codePointAt(t);if(a===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),a===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 Rp(...e){let t=-1,n;for(;++t<e.length;)jt(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":Ap(n)}function Ap(e){jt(e);const t=e.codePointAt(0)===47;let n=Ep(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Ep(e,t){let n="",r=0,s=-1,i=0,o=-1,a,l;for(;++o<=e.length;){if(o<e.length)a=e.codePointAt(o);else{if(a===47)break;a=47}if(a===47){if(!(s===o-1||i===1))if(s!==o-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=o,i=0;continue}}else if(n.length>0){n="",r=0,s=o,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,o):n=e.slice(s+1,o),r=o-s-1;s=o,i=0}else a===46&&i>-1?i++:i=-1}return n}function jt(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Lp={cwd:Np};function Np(){return"/"}function Yn(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Pp(e){if(typeof e=="string")e=new URL(e);else if(!Yn(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 jp(e)}function jp(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 Sn=["history","path","basename","stem","extname","dirname"];class Qo{constructor(t){let n;t?Yn(t)?n={path:t}:typeof t=="string"||Dp(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Lp.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Sn.length;){const i=Sn[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)Sn.includes(s)||(this[s]=n[s])}get basename(){return typeof this.path=="string"?_e.basename(this.path):void 0}set basename(t){vn(t,"basename"),kn(t,"basename"),this.path=_e.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?_e.dirname(this.path):void 0}set dirname(t){As(this.basename,"dirname"),this.path=_e.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?_e.extname(this.path):void 0}set extname(t){if(kn(t,"extname"),As(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=_e.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Yn(t)&&(t=Pp(t)),vn(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?_e.basename(this.path,this.extname):void 0}set stem(t){vn(t,"stem"),kn(t,"stem"),this.path=_e.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 kn(e,t){if(e&&e.includes(_e.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+_e.sep+"`")}function vn(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function As(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function Dp(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const _p=(function(e){const r=this.constructor.prototype,s=r[e],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,r),i}),Op={}.hasOwnProperty;class jr extends _p{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=wp()}copy(){const t=new jr;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(bn(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Tn("data",this.frozen),this.namespace[t]=n,this):Op.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Tn("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=Ft(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),Cn("process",this.compiler||this.Compiler),n?s(void 0,n):new Promise(s);function s(i,o){const a=Ft(t),l=r.parse(a);r.run(l,a,function(c,d,p){if(c||!d||!p)return u(c);const f=d,y=r.stringify(f,p);Bp(y)?p.value=y:p.result=y,u(c,p)});function u(c,d){c||!d?o(c):i?i(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),wn("processSync",this.parser||this.Parser),Cn("processSync",this.compiler||this.Compiler),this.process(t,s),Ls("processSync","process",n),r;function s(i,o){n=!0,Ms(i),r=o}}run(t,n,r){Es(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(o,a){const l=Ft(n);s.run(t,l,u);function u(c,d,p){const f=d||t;c?a(c):o?o(f):r(void 0,f,p)}}}runSync(t,n){let r=!1,s;return this.run(t,n,i),Ls("runSync","run",r),s;function i(o,a){Ms(o),s=a,r=!0}}stringify(t,n){this.freeze();const r=Ft(n),s=this.compiler||this.Compiler;return Cn("stringify",s),Es(t),s(t,r)}use(t,...n){const r=this.attachers,s=this.namespace;if(Tn("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?a(t):o(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 o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(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");a(u.plugins),u.settings&&(s.settings=bn(!0,s.settings,u.settings))}function a(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,...y]=c;const m=r[p][1];Xn(m)&&Xn(f)&&(f=bn(!0,m,f)),r[p]=[u,f,...y]}}}}const Fp=new jr().freeze();function wn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Cn(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Tn(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 Es(e){if(!Xn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ls(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Ft(e){return zp(e)?e:new Qo(e)}function zp(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Bp(e){return typeof e=="string"||$p(e)}function $p(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Kp="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ns=[],Ps={allowDangerousHtml:!0},Up=/^(https?|ircs?|mailto|xmpp)$/i,Vp=[{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 Hp(e){const t=qp(e),n=Wp(e);return Qp(t.runSync(t.parse(n),n),e)}function qp(e){const t=e.rehypePlugins||Ns,n=e.remarkPlugins||Ns,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Ps}:Ps;return Fp().use(If).use(n).use(Sp,r).use(t)}function Wp(e){const t=e.children||"",n=new Qo;return typeof t=="string"&&(n.value=t),n}function Qp(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,o=t.skipHtml,a=t.unwrapDisallowed,l=t.urlTransform||Gp;for(const c of Vp)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+Kp+c.id,void 0);return Pr(e,u),ld(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 o?p.children.splice(d,1):p.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let f;for(f in gn)if(Object.hasOwn(gn,f)&&Object.hasOwn(c.properties,f)){const y=c.properties[f],m=gn[f];(m===null||m.includes(c.tagName))&&(c.properties[f]=l(String(y||""),f,c))}}if(c.type==="element"){let f=n?!n.includes(c.tagName):i?i.includes(c.tagName):!1;if(!f&&r&&typeof d=="number"&&(f=!r(c,d,p)),f&&p&&typeof d=="number")return a&&c.children?p.children.splice(d,1,...c.children):p.children.splice(d,1),d}}}function Gp(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||Up.test(e.slice(0,t))?e:""}function js(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 Xp(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Yp(e,t,n){const s=an((n||{}).ignore||[]),i=Jp(t);let o=-1;for(;++o<i.length;)Wo(e,"text",a);function a(u,c){let d=-1,p;for(;++d<c.length;){const f=c[d],y=p?p.children:void 0;if(s(f,y?y.indexOf(f):void 0,p))return;p=f}if(p)return l(u,c)}function l(u,c){const d=c[c.length-1],p=i[o][0],f=i[o][1];let y=0;const b=d.children.indexOf(u);let g=!1,v=[];p.lastIndex=0;let w=p.exec(u.value);for(;w;){const N=w.index,j={index:w.index,input:w.input,stack:[...c,u]};let T=f(...w,j);if(typeof T=="string"&&(T=T.length>0?{type:"text",value:T}:void 0),T===!1?p.lastIndex=N+1:(y!==N&&v.push({type:"text",value:u.value.slice(y,N)}),Array.isArray(T)?v.push(...T):T&&v.push(T),y=N+w[0].length,g=!0),!p.global)break;w=p.exec(u.value)}return g?(y<u.value.length&&v.push({type:"text",value:u.value.slice(y)}),d.children.splice(b,1,...v)):v=[u],b+v.length}}function Jp(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([Zp(s[0]),eg(s[1])])}return t}function Zp(e){return typeof e=="string"?new RegExp(Xp(e),"g"):e}function eg(e){return typeof e=="function"?e:function(){return e}}const In="phrasing",Mn=["autolink","link","image","label"];function tg(){return{transforms:[lg],enter:{literalAutolink:rg,literalAutolinkEmail:Rn,literalAutolinkHttp:Rn,literalAutolinkWww:Rn},exit:{literalAutolink:ag,literalAutolinkEmail:og,literalAutolinkHttp:sg,literalAutolinkWww:ig}}}function ng(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:In,notInConstruct:Mn},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:In,notInConstruct:Mn},{character:":",before:"[ps]",after:"\\/",inConstruct:In,notInConstruct:Mn}]}}function rg(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Rn(e){this.config.enter.autolinkProtocol.call(this,e)}function sg(e){this.config.exit.autolinkProtocol.call(this,e)}function ig(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 og(e){this.config.exit.autolinkEmail.call(this,e)}function ag(e){this.exit(e)}function lg(e){Yp(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,ug],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),cg]],{ignore:["link","linkReference"]})}function ug(e,t,n,r,s){let i="";if(!Go(s)||(/^w/i.test(t)&&(n=t+n,t="",i="http://"),!dg(n)))return!1;const o=hg(n+r);if(!o[0])return!1;const a={type:"link",title:null,url:i+t+o[0],children:[{type:"text",value:t+o[0]}]};return o[1]?[a,{type:"text",value:o[1]}]:a}function cg(e,t,n,r){return!Go(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function dg(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 hg(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=js(e,"(");let i=js(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 Go(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||et(n)||rn(n))&&(!t||n!==47)}Xo.peek=kg;function fg(){this.buffer()}function pg(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function gg(){this.buffer()}function mg(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function yg(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(e)).toLowerCase(),n.label=t}function xg(e){this.exit(e)}function bg(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Sg(e){this.exit(e)}function kg(){return"["}function Xo(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const o=n.enter("footnoteReference"),a=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),a(),o(),i+=s.move("]"),i}function vg(){return{enter:{gfmFootnoteCallString:fg,gfmFootnoteCall:pg,gfmFootnoteDefinitionLabelString:gg,gfmFootnoteDefinition:mg},exit:{gfmFootnoteCallString:yg,gfmFootnoteCall:xg,gfmFootnoteDefinitionLabelString:bg,gfmFootnoteDefinition:Sg}}}function wg(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Xo},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,o){const a=i.createTracker(o);let l=a.move("[^");const u=i.enter("footnoteDefinition"),c=i.enter("label");return l+=a.move(i.safe(i.associationId(r),{before:l,after:"]"})),c(),l+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),l+=a.move((t?`
|
|
16
|
+
`:" ")+i.indentLines(i.containerFlow(r,a.current()),t?Yo:Cg))),u(),l}}function Cg(e,t,n){return t===0?e:Yo(e,t,n)}function Yo(e,t,n){return(n?"":" ")+e}const Tg=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Jo.peek=Eg;function Ig(){return{canContainEols:["delete"],enter:{strikethrough:Rg},exit:{strikethrough:Ag}}}function Mg(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Tg}],handlers:{delete:Jo}}}function Rg(e){this.enter({type:"delete",children:[]},e)}function Ag(e){this.exit(e)}function Jo(e,t,n,r){const s=n.createTracker(r),i=n.enter("strikethrough");let o=s.move("~~");return o+=n.containerPhrasing(e,{...s.current(),before:o,after:"~"}),o+=s.move("~~"),i(),o}function Eg(){return"~"}function Lg(e){return e.length}function Ng(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||Lg,i=[],o=[],a=[],l=[];let u=0,c=-1;for(;++c<e.length;){const m=[],b=[];let g=-1;for(e[c].length>u&&(u=e[c].length);++g<e[c].length;){const v=Pg(e[c][g]);if(n.alignDelimiters!==!1){const w=s(v);b[g]=w,(l[g]===void 0||w>l[g])&&(l[g]=w)}m.push(v)}o[c]=m,a[c]=b}let d=-1;if(typeof r=="object"&&"length"in r)for(;++d<u;)i[d]=Ds(r[d]);else{const m=Ds(r);for(;++d<u;)i[d]=m}d=-1;const p=[],f=[];for(;++d<u;){const m=i[d];let b="",g="";m===99?(b=":",g=":"):m===108?b=":":m===114&&(g=":");let v=n.alignDelimiters===!1?1:Math.max(1,l[d]-b.length-g.length);const w=b+"-".repeat(v)+g;n.alignDelimiters!==!1&&(v=b.length+v+g.length,v>l[d]&&(l[d]=v),f[d]=v),p[d]=w}o.splice(1,0,p),a.splice(1,0,f),c=-1;const y=[];for(;++c<o.length;){const m=o[c],b=a[c];d=-1;const g=[];for(;++d<u;){const v=m[d]||"";let w="",N="";if(n.alignDelimiters!==!1){const j=l[d]-(b[d]||0),T=i[d];T===114?w=" ".repeat(j):T===99?j%2?(w=" ".repeat(j/2+.5),N=" ".repeat(j/2-.5)):(w=" ".repeat(j/2),N=w):N=" ".repeat(j)}n.delimiterStart!==!1&&!d&&g.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&v==="")&&(n.delimiterStart!==!1||d)&&g.push(" "),n.alignDelimiters!==!1&&g.push(w),g.push(v),n.alignDelimiters!==!1&&g.push(N),n.padding!==!1&&g.push(" "),(n.delimiterEnd!==!1||d!==u-1)&&g.push("|")}y.push(n.delimiterEnd===!1?g.join("").replace(/ +$/,""):g.join(""))}return y.join(`
|
|
17
|
+
`)}function Pg(e){return e==null?"":String(e)}function Ds(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 jg(e,t,n,r){const s=n.enter("blockquote"),i=n.createTracker(r);i.move("> "),i.shift(2);const o=n.indentLines(n.containerFlow(e,i.current()),Dg);return s(),o}function Dg(e,t,n){return">"+(n?"":" ")+e}function _g(e,t){return _s(e,t.inConstruct,!0)&&!_s(e,t.notInConstruct,!1)}function _s(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 Os(e,t,n,r){let s=-1;for(;++s<n.unsafe.length;)if(n.unsafe[s].character===`
|
|
18
|
+
`&&_g(n.stack,n.unsafe[s]))return/[ \t]/.test(r.before)?"":" ";return`\\
|
|
19
|
+
`}function Og(e,t){const n=String(e);let r=n.indexOf(t),s=r,i=0,o=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===s?++i>o&&(o=i):i=1,s=r+t.length,r=n.indexOf(t,s);return o}function Fg(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 zg(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 Bg(e,t,n,r){const s=zg(n),i=e.value||"",o=s==="`"?"GraveAccent":"Tilde";if(Fg(e,n)){const d=n.enter("codeIndented"),p=n.indentLines(i,$g);return d(),p}const a=n.createTracker(r),l=s.repeat(Math.max(Og(i,s)+1,3)),u=n.enter("codeFenced");let c=a.move(l);if(e.lang){const d=n.enter(`codeFencedLang${o}`);c+=a.move(n.safe(e.lang,{before:c,after:" ",encode:["`"],...a.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${o}`);c+=a.move(" "),c+=a.move(n.safe(e.meta,{before:c,after:`
|
|
20
20
|
`,encode:["`"],...a.current()})),d()}return c+=a.move(`
|
|
21
21
|
`),i&&(c+=a.move(i+`
|
|
22
|
-
`)),c+=a.move(l),u(),c}function
|
|
23
|
-
`,...l.current()}))),a(),e.title&&(a=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),a()),o(),u}function
|
|
22
|
+
`)),c+=a.move(l),u(),c}function $g(e,t,n){return(n?"":" ")+e}function Dr(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 Kg(e,t,n,r){const s=Dr(n),i=s==='"'?"Quote":"Apostrophe",o=n.enter("definition");let a=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("]: "),a(),!e.url||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(a=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":`
|
|
23
|
+
`,...l.current()}))),a(),e.title&&(a=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),a()),o(),u}function Ug(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 Rt(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Xt(e,t,n){const r=ct(e),s=ct(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}}Zo.peek=Vg;function Zo(e,t,n,r){const s=Ug(n),i=n.enter("emphasis"),o=n.createTracker(r),a=o.move(s);let l=o.move(n.containerPhrasing(e,{after:s,before:a,...o.current()}));const u=l.charCodeAt(0),c=Xt(r.before.charCodeAt(r.before.length-1),u,s);c.inside&&(l=Rt(u)+l.slice(1));const d=l.charCodeAt(l.length-1),p=Xt(r.after.charCodeAt(0),d,s);p.inside&&(l=l.slice(0,-1)+Rt(d));const f=o.move(s);return i(),n.attentionEncodeSurroundingInfo={after:p.outside,before:c.outside},a+l+f}function Vg(e,t,n){return n.options.emphasis||"*"}function Hg(e,t){let n=!1;return Pr(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Qn}),!!((!e.depth||e.depth<3)&&Ir(e)&&(t.options.setext||n))}function qg(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(Hg(e,n)){const c=n.enter("headingSetext"),d=n.enter("phrasing"),p=n.containerPhrasing(e,{...i.current(),before:`
|
|
24
24
|
`,after:`
|
|
25
25
|
`});return d(),c(),p+`
|
|
26
26
|
`+(s===1?"=":"-").repeat(p.length-(Math.max(p.lastIndexOf("\r"),p.lastIndexOf(`
|
|
27
27
|
`))+1))}const o="#".repeat(s),a=n.enter("headingAtx"),l=n.enter("phrasing");i.move(o+" ");let u=n.containerPhrasing(e,{before:"# ",after:`
|
|
28
|
-
`,...i.current()});return/^[\t ]/.test(u)&&(u=Rt(u.charCodeAt(0))+u.slice(1)),u=u?o+" "+u:o,n.options.closeAtx&&(u+=" "+o),l(),a(),u}
|
|
28
|
+
`,...i.current()});return/^[\t ]/.test(u)&&(u=Rt(u.charCodeAt(0))+u.slice(1)),u=u?o+" "+u:o,n.options.closeAtx&&(u+=" "+o),l(),a(),u}ea.peek=Wg;function ea(e){return e.value||""}function Wg(){return"<"}ta.peek=Qg;function ta(e,t,n,r){const s=Dr(n),i=s==='"'?"Quote":"Apostrophe",o=n.enter("image");let a=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("]("),a(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(a=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),a(),e.title&&(a=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),a()),u+=l.move(")"),o(),u}function Qg(){return"!"}na.peek=Gg;function na(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let o=n.enter("label");const a=n.createTracker(r);let l=a.move("![");const u=n.safe(e.alt,{before:l,after:"]",...a.current()});l+=a.move(u+"]["),o();const c=n.stack;n.stack=[],o=n.enter("reference");const d=n.safe(n.associationId(e),{before:l,after:"]",...a.current()});return o(),n.stack=c,i(),s==="full"||!u||u!==d?l+=a.move(d+"]"):s==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function Gg(){return"!"}ra.peek=Xg;function ra(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 o=n.unsafe[i],a=n.compilePattern(o);let l;if(o.atBreak)for(;l=a.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 Xg(){return"`"}function sa(e,t){const n=Ir(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))}ia.peek=Yg;function ia(e,t,n,r){const s=Dr(n),i=s==='"'?"Quote":"Apostrophe",o=n.createTracker(r);let a,l;if(sa(e,n)){const c=n.stack;n.stack=[],a=n.enter("autolink");let d=o.move("<");return d+=o.move(n.containerPhrasing(e,{before:d,after:">",...o.current()})),d+=o.move(">"),a(),n.stack=c,d}a=n.enter("link"),l=n.enter("label");let u=o.move("[");return u+=o.move(n.containerPhrasing(e,{before:u,after:"](",...o.current()})),u+=o.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=o.move("<"),u+=o.move(n.safe(e.url,{before:u,after:">",...o.current()})),u+=o.move(">")):(l=n.enter("destinationRaw"),u+=o.move(n.safe(e.url,{before:u,after:e.title?" ":")",...o.current()}))),l(),e.title&&(l=n.enter(`title${i}`),u+=o.move(" "+s),u+=o.move(n.safe(e.title,{before:u,after:s,...o.current()})),u+=o.move(s),l()),u+=o.move(")"),a(),u}function Yg(e,t,n){return sa(e,n)?"<":"["}oa.peek=Jg;function oa(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let o=n.enter("label");const a=n.createTracker(r);let l=a.move("[");const u=n.containerPhrasing(e,{before:l,after:"]",...a.current()});l+=a.move(u+"]["),o();const c=n.stack;n.stack=[],o=n.enter("reference");const d=n.safe(n.associationId(e),{before:l,after:"]",...a.current()});return o(),n.stack=c,i(),s==="full"||!u||u!==d?l+=a.move(d+"]"):s==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function Jg(){return"["}function _r(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 Zg(e){const t=_r(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 em(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 aa(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 tm(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let o=e.ordered?em(n):_r(n);const a=e.ordered?o==="."?")":".":Zg(n);let l=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){const c=e.children?e.children[0]:void 0;if((o==="*"||o==="-")&&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),aa(n)===o&&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&&(o=a),n.bulletCurrent=o;const u=n.containerFlow(e,r);return n.bulletLastUsed=o,n.bulletCurrent=i,s(),u}function nm(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 rm(e,t,n,r){const s=nm(n);let i=n.bulletCurrent||_r(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 o=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);const a=n.createTracker(r);a.move(i+" ".repeat(o-i.length)),a.shift(o);const l=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,a.current()),c);return l(),u;function c(d,p,f){return p?(f?"":" ".repeat(o))+d:(f?i:i+" ".repeat(o-i.length))+d}}function sm(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),o=n.containerPhrasing(e,r);return i(),s(),o}const im=an(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function om(e,t,n,r){return(e.children.some(function(o){return im(o)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function am(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}la.peek=lm;function la(e,t,n,r){const s=am(n),i=n.enter("strong"),o=n.createTracker(r),a=o.move(s+s);let l=o.move(n.containerPhrasing(e,{after:s,before:a,...o.current()}));const u=l.charCodeAt(0),c=Xt(r.before.charCodeAt(r.before.length-1),u,s);c.inside&&(l=Rt(u)+l.slice(1));const d=l.charCodeAt(l.length-1),p=Xt(r.after.charCodeAt(0),d,s);p.inside&&(l=l.slice(0,-1)+Rt(d));const f=o.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:p.outside,before:c.outside},a+l+f}function lm(e,t,n){return n.options.strong||"*"}function um(e,t,n,r){return n.safe(e.value,r)}function cm(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 dm(e,t,n){const r=(aa(n)+(n.options.ruleSpaces?" ":"")).repeat(cm(n));return n.options.ruleSpaces?r.slice(0,-1):r}const ua={blockquote:jg,break:Os,code:Bg,definition:Kg,emphasis:Zo,hardBreak:Os,heading:qg,html:ea,image:ta,imageReference:na,inlineCode:ra,link:ia,linkReference:oa,list:tm,listItem:rm,paragraph:sm,root:om,strong:la,text:um,thematicBreak:dm};function hm(){return{enter:{table:fm,tableData:Fs,tableHeader:Fs,tableRow:gm},exit:{codeText:mm,table:pm,tableData:An,tableHeader:An,tableRow:An}}}function fm(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 pm(e){this.exit(e),this.data.inTable=void 0}function gm(e){this.enter({type:"tableRow",children:[]},e)}function An(e){this.exit(e)}function Fs(e){this.enter({type:"tableCell",children:[]},e)}function mm(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,ym));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function ym(e,t){return t==="|"?t:e}function xm(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
29
29
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:p,table:o,tableCell:l,tableRow:a}};function o(f,y,m,b){return u(c(f,m,b),f.align)}function a(f,y,m,b){const g=d(f,m,b),v=u([g]);return v.slice(0,v.indexOf(`
|
|
30
|
-
`))}function l(f,y,m,b){const g=m.enter("tableCell"),v=m.enter("phrasing"),w=m.containerPhrasing(f,{...b,before:i,after:i});return v(),g(),w}function u(f,y){return Lg(f,{align:y,alignDelimiters:r,padding:n,stringLength:s})}function c(f,y,m){const b=f.children;let g=-1;const v=[],w=y.enter("table");for(;++g<b.length;)v[g]=d(b[g],y,m);return w(),v}function d(f,y,m){const b=f.children;let g=-1;const v=[],w=y.enter("tableRow");for(;++g<b.length;)v[g]=l(b[g],f,y,m);return w(),v}function p(f,y,m){let b=la.inlineCode(f,y,m);return m.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function xm(){return{exit:{taskListCheckValueChecked:zs,taskListCheckValueUnchecked:zs,paragraph:Sm}}}function bm(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:km}}}function zs(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function Sm(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,o;for(;++i<s.length;){const a=s[i];if(a.type==="paragraph"){o=a;break}}o===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 km(e,t,n,r){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",a=n.createTracker(r);i&&a.move(o);let l=la.listItem(e,t,n,{...r,...a.current()});return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+o}}function vm(){return[eg(),kg(),Tg(),dm(),xm()]}function wm(e){return{extensions:[tg(),vg(e),Ig(),ym(e),bm()]}}const Cm={tokenize:Em,partial:!0},ua={tokenize:Lm,partial:!0},ca={tokenize:Nm,partial:!0},da={tokenize:Pm,partial:!0},Tm={tokenize:jm,partial:!0},ha={name:"wwwAutolink",tokenize:Rm,previous:pa},fa={name:"protocolAutolink",tokenize:Am,previous:ga},We={name:"emailAutolink",tokenize:Mm,previous:ma},Fe={};function Im(){return{text:Fe}}let Ze=48;for(;Ze<123;)Fe[Ze]=We,Ze++,Ze===58?Ze=65:Ze===91&&(Ze=97);Fe[43]=We;Fe[45]=We;Fe[46]=We;Fe[95]=We;Fe[72]=[We,fa];Fe[104]=[We,fa];Fe[87]=[We,ha];Fe[119]=[We,ha];function Mm(e,t,n){const r=this;let s,i;return o;function o(d){return!Jn(d)||!ma.call(r,r.previous)||Or(r.events)?n(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),a(d))}function a(d){return Jn(d)?(e.consume(d),a):d===64?(e.consume(d),l):n(d)}function l(d){return d===46?e.check(Tm,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&&ye(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):n(d)}}function Rm(e,t,n){const r=this;return s;function s(o){return o!==87&&o!==119||!pa.call(r,r.previous)||Or(r.events)?n(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Cm,e.attempt(ua,e.attempt(ca,i),n),n)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function Am(e,t,n){const r=this;let s="",i=!1;return o;function o(d){return(d===72||d===104)&&ga.call(r,r.previous)&&!Or(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(d),e.consume(d),a):n(d)}function a(d){if(ye(d)&&s.length<5)return s+=String.fromCodePoint(d),e.consume(d),a;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||Wt(d)||ee(d)||et(d)||rn(d)?n(d):e.attempt(ua,e.attempt(ca,c),n)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function Em(e,t,n){let r=0;return s;function s(o){return(o===87||o===119)&&r<3?(r++,e.consume(o),s):o===46&&r===3?(e.consume(o),i):n(o)}function i(o){return o===null?n(o):t(o)}}function Lm(e,t,n){let r,s,i;return o;function o(u){return u===46||u===95?e.check(da,l,a)(u):u===null||ee(u)||et(u)||u!==45&&rn(u)?l(u):(i=!0,e.consume(u),o)}function a(u){return u===95?r=!0:(s=r,r=void 0),e.consume(u),o}function l(u){return s||r||!i?n(u):t(u)}}function Nm(e,t){let n=0,r=0;return s;function s(o){return o===40?(n++,e.consume(o),s):o===41&&r<n?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(da,t,i)(o):o===null||ee(o)||et(o)?t(o):(e.consume(o),s)}function i(o){return o===41&&r++,e.consume(o),s}}function Pm(e,t,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(e.consume(a),r):a===38?(e.consume(a),i):a===93?(e.consume(a),s):a===60||a===null||ee(a)||et(a)?t(a):n(a)}function s(a){return a===null||a===40||a===91||ee(a)||et(a)?t(a):r(a)}function i(a){return ye(a)?o(a):n(a)}function o(a){return a===59?(e.consume(a),r):ye(a)?(e.consume(a),o):n(a)}}function jm(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return ge(i)?n(i):t(i)}}function pa(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ee(e)}function ga(e){return!ye(e)}function ma(e){return!(e===47||Jn(e))}function Jn(e){return e===43||e===45||e===46||e===95||ge(e)}function Or(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 Dm={tokenize:Um,partial:!0};function _m(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Bm,continuation:{tokenize:$m},exit:Km}},text:{91:{name:"gfmFootnoteCall",tokenize:zm},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Om,resolveTo:Fm}}}}function Om(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;s--;){const l=r.events[s][1];if(l.type==="labelImage"){o=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return a;function a(l){if(!o||!o._balanced)return n(l);const u=Ne(r.sliceSerialize({start:o.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 Fm(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)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[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",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function zm(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,o;return a;function a(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&&!o||d===null||d===91||ee(d))return n(d);if(d===93){e.exit("chunkString");const p=e.exit("gfmFootnoteCallString");return s.includes(Ne(r.sliceSerialize(p)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return ee(d)||(o=!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 Bm(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,o=0,a;return l;function l(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(y)}function c(y){if(o>999||y===93&&!a||y===null||y===91||ee(y))return n(y);if(y===93){e.exit("chunkString");const m=e.exit("gfmFootnoteDefinitionLabelString");return i=Ne(r.sliceSerialize(m)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),p}return ee(y)||(a=!0),o++,e.consume(y),y===92?d:c}function d(y){return y===91||y===92||y===93?(e.consume(y),o++,c):c(y)}function p(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),s.includes(i)||s.push(i),J(e,f,"gfmFootnoteDefinitionWhitespace")):n(y)}function f(y){return t(y)}}function $m(e,t,n){return e.check(Pt,t,e.attempt(Dm,t,n))}function Km(e){e.exit("gfmFootnoteDefinition")}function Um(e,t,n){const r=this;return J(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):n(i)}}function Vm(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(o,a){let l=-1;for(;++l<o.length;)if(o[l][0]==="enter"&&o[l][1].type==="strikethroughSequenceTemporary"&&o[l][1]._close){let u=l;for(;u--;)if(o[u][0]==="exit"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._open&&o[l][1].end.offset-o[l][1].start.offset===o[u][1].end.offset-o[u][1].start.offset){o[l][1].type="strikethroughSequence",o[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},o[u][1].start),end:Object.assign({},o[l][1].end)},d={type:"strikethroughText",start:Object.assign({},o[u][1].end),end:Object.assign({},o[l][1].start)},p=[["enter",c,a],["enter",o[u][1],a],["exit",o[u][1],a],["enter",d,a]],f=a.parser.constructs.insideSpan.null;f&&Ce(p,p.length,0,sn(f,o.slice(u+1,l),a)),Ce(p,p.length,0,[["exit",d,a],["enter",o[l][1],a],["exit",o[l][1],a],["exit",c,a]]),Ce(o,u-1,l-u+3,p),l=u+p.length-2;break}}for(l=-1;++l<o.length;)o[l][1].type==="strikethroughSequenceTemporary"&&(o[l][1].type="data");return o}function i(o,a,l){const u=this.previous,c=this.events;let d=0;return p;function p(y){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(y):(o.enter("strikethroughSequenceTemporary"),f(y))}function f(y){const m=ct(u);if(y===126)return d>1?l(y):(o.consume(y),d++,f);if(d<2&&!n)return l(y);const b=o.exit("strikethroughSequenceTemporary"),g=ct(y);return b._open=!g||g===2&&!!m,b._close=!m||m===2&&!!g,a(y)}}}class Hm{constructor(){this.map=[]}add(t,n,r){qm(this,t,n,r)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[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 qm(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 Wm(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 Gm(){return{flow:{null:{name:"table",tokenize:Qm,resolveAll:Xm}}}}function Qm(e,t,n){const r=this;let s=0,i=0,o;return a;function a(C){let R=r.events.length-1;for(;R>-1;){const _=r.events[R][1].type;if(_==="lineEnding"||_==="linePrefix")R--;else break}const E=R>-1?r.events[R][1].type:null,z=E==="tableHead"||E==="tableRow"?T:l;return z===T&&r.parser.lazy[r.now().line]?n(C):z(C)}function l(C){return e.enter("tableHead"),e.enter("tableRow"),u(C)}function u(C){return C===124||(o=!0,i+=1),c(C)}function c(C){return C===null?n(C):U(C)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),f):n(C):Q(C)?J(e,c,"whitespace")(C):(i+=1,o&&(o=!1,s+=1),C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),o=!0,c):(e.enter("data"),d(C)))}function d(C){return C===null||C===124||ee(C)?(e.exit("data"),c(C)):(e.consume(C),C===92?p:d)}function p(C){return C===92||C===124?(e.consume(C),d):d(C)}function f(C){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(C):(e.enter("tableDelimiterRow"),o=!1,Q(C)?J(e,y,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):y(C))}function y(C){return C===45||C===58?b(C):C===124?(o=!0,e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),m):j(C)}function m(C){return Q(C)?J(e,b,"whitespace")(C):b(C)}function b(C){return C===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),g):C===45?(i+=1,g(C)):C===null||U(C)?N(C):j(C)}function g(C){return C===45?(e.enter("tableDelimiterFiller"),v(C)):j(C)}function v(C){return C===45?(e.consume(C),v):C===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(C))}function w(C){return Q(C)?J(e,N,"whitespace")(C):N(C)}function N(C){return C===124?y(C):C===null||U(C)?!o||s!==i?j(C):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(C)):j(C)}function j(C){return n(C)}function T(C){return e.enter("tableRow"),O(C)}function O(C){return C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),O):C===null||U(C)?(e.exit("tableRow"),t(C)):Q(C)?J(e,O,"whitespace")(C):(e.enter("data"),B(C))}function B(C){return C===null||C===124||ee(C)?(e.exit("data"),O(C)):(e.consume(C),C===92?$:B)}function $(C){return C===92||C===124?(e.consume(C),B):B(C)}}function Xm(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],o=[0,0,0,0],a=!1,l=0,u,c,d;const p=new Hm;for(;++n<e.length;){const f=e[n],y=f[1];f[0]==="enter"?y.type==="tableHead"?(a=!1,l!==0&&(Bs(p,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},y.start),end:Object.assign({},y.end)},p.add(n,0,[["enter",u,t]])):y.type==="tableRow"||y.type==="tableDelimiterRow"?(r=!0,d=void 0,i=[0,0,0,0],o=[0,n+1,0,0],a&&(a=!1,c={type:"tableBody",start:Object.assign({},y.start),end:Object.assign({},y.end)},p.add(n,0,[["enter",c,t]])),s=y.type==="tableDelimiterRow"?2:c?3:1):s&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")?(r=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],d=zt(p,t,i,s,void 0,d),i=[0,0,0,0]),o[2]=n)):y.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(o[0]=o[1],d=zt(p,t,i,s,void 0,d)),i=o,o=[i[1],n,0,0])):y.type==="tableHead"?(a=!0,l=n):y.type==="tableRow"||y.type==="tableDelimiterRow"?(l=n,i[1]!==0?(o[0]=o[1],d=zt(p,t,i,s,n,d)):o[1]!==0&&(d=zt(p,t,o,s,n,d)),s=0):s&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")&&(o[3]=n)}for(l!==0&&Bs(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=Wm(t.events,n))}return e}function zt(e,t,n,r,s,i){const o=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(i.end=Object.assign({},ot(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const l=ot(t.events,n[1]);if(i={type:o,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const u=ot(t.events,n[2]),c=ot(t.events,n[3]),d={type:a,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 y=n[2]+1,m=n[3]-n[2]-1;e.add(y,m,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},ot(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function Bs(e,t,n,r,s){const i=[],o=ot(t.events,n);s&&(s.end=Object.assign({},o),i.push(["exit",s,t])),r.end=Object.assign({},o),i.push(["exit",r,t]),e.add(n+1,0,i)}function ot(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const Ym={name:"tasklistCheck",tokenize:Zm};function Jm(){return{text:{91:Ym}}}function Zm(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 ee(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),o):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),o):n(l)}function o(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(l)}function a(l){return U(l)?t(l):Q(l)?e.check({tokenize:ey},t,n)(l):n(l)}}function ey(e,t,n){return J(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function ty(e){return Mo([Im(),_m(),Vm(e),Gm(),Jm()])}const ny={};function ry(e){const t=this,n=e||ny,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(ty(n)),i.push(vm()),o.push(wm(n))}function sy(){var e;return typeof navigator<"u"&&typeof((e=navigator.clipboard)==null?void 0:e.writeText)=="function"}function iy(e){if(typeof document>"u")return;const t=document.getSelection();t&&(t.removeAllRanges(),e.forEach(n=>t.addRange(n)))}function $s(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()):[],o=document.createElement("textarea");o.value=e,o.setAttribute("readonly",""),o.setAttribute("aria-hidden","true"),o.style.position="fixed",o.style.top="0",o.style.left="-9999px",o.style.opacity="0",o.style.pointerEvents="none",o.style.fontSize="12pt",document.body.appendChild(o);try{o.focus({preventScroll:!0})}catch{o.focus()}o.select(),o.setSelectionRange(0,o.value.length);let a=!1;try{a=typeof document.execCommand=="function"&&document.execCommand("copy")}catch{a=!1}if(o.remove(),t)try{t.focus({preventScroll:!0})}catch{t.focus()}return n&&r?n.setSelectionRange(r.start,r.end):iy(i),a}async function oy(e){if(!e)return!1;if(sy())try{return await navigator.clipboard.writeText(e),!0}catch{return $s(e)}return $s(e)}const ay=1300;function ly(e){const[t,n]=k.useState(!1),r=k.useCallback(async()=>{if(!e.text)return;const s=await oy(e.text);n(!!s)},[e.text]);return k.useEffect(()=>{if(!t||typeof window>"u")return;const s=window.setTimeout(()=>n(!1),e.resetDelayMs??ay);return()=>window.clearTimeout(s)},[t,e.resetDelayMs]),{copied:t,copy:r}}const uy=/language-([a-z0-9-]+)/i;function ya(e){return typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(ya).join(""):""}function cy(e){const t=ya(e);return t.endsWith(`
|
|
31
|
-
`)?t.slice(0,-1):t}function
|
|
30
|
+
`))}function l(f,y,m,b){const g=m.enter("tableCell"),v=m.enter("phrasing"),w=m.containerPhrasing(f,{...b,before:i,after:i});return v(),g(),w}function u(f,y){return Ng(f,{align:y,alignDelimiters:r,padding:n,stringLength:s})}function c(f,y,m){const b=f.children;let g=-1;const v=[],w=y.enter("table");for(;++g<b.length;)v[g]=d(b[g],y,m);return w(),v}function d(f,y,m){const b=f.children;let g=-1;const v=[],w=y.enter("tableRow");for(;++g<b.length;)v[g]=l(b[g],f,y,m);return w(),v}function p(f,y,m){let b=ua.inlineCode(f,y,m);return m.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function bm(){return{exit:{taskListCheckValueChecked:zs,taskListCheckValueUnchecked:zs,paragraph:km}}}function Sm(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:vm}}}function zs(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function km(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,o;for(;++i<s.length;){const a=s[i];if(a.type==="paragraph"){o=a;break}}o===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 vm(e,t,n,r){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",a=n.createTracker(r);i&&a.move(o);let l=ua.listItem(e,t,n,{...r,...a.current()});return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+o}}function wm(){return[tg(),vg(),Ig(),hm(),bm()]}function Cm(e){return{extensions:[ng(),wg(e),Mg(),xm(e),Sm()]}}const Tm={tokenize:Lm,partial:!0},ca={tokenize:Nm,partial:!0},da={tokenize:Pm,partial:!0},ha={tokenize:jm,partial:!0},Im={tokenize:Dm,partial:!0},fa={name:"wwwAutolink",tokenize:Am,previous:ga},pa={name:"protocolAutolink",tokenize:Em,previous:ma},We={name:"emailAutolink",tokenize:Rm,previous:ya},Fe={};function Mm(){return{text:Fe}}let Ze=48;for(;Ze<123;)Fe[Ze]=We,Ze++,Ze===58?Ze=65:Ze===91&&(Ze=97);Fe[43]=We;Fe[45]=We;Fe[46]=We;Fe[95]=We;Fe[72]=[We,pa];Fe[104]=[We,pa];Fe[87]=[We,fa];Fe[119]=[We,fa];function Rm(e,t,n){const r=this;let s,i;return o;function o(d){return!Jn(d)||!ya.call(r,r.previous)||Or(r.events)?n(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),a(d))}function a(d){return Jn(d)?(e.consume(d),a):d===64?(e.consume(d),l):n(d)}function l(d){return d===46?e.check(Im,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&&ye(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):n(d)}}function Am(e,t,n){const r=this;return s;function s(o){return o!==87&&o!==119||!ga.call(r,r.previous)||Or(r.events)?n(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Tm,e.attempt(ca,e.attempt(da,i),n),n)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function Em(e,t,n){const r=this;let s="",i=!1;return o;function o(d){return(d===72||d===104)&&ma.call(r,r.previous)&&!Or(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(d),e.consume(d),a):n(d)}function a(d){if(ye(d)&&s.length<5)return s+=String.fromCodePoint(d),e.consume(d),a;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||Wt(d)||ee(d)||et(d)||rn(d)?n(d):e.attempt(ca,e.attempt(da,c),n)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function Lm(e,t,n){let r=0;return s;function s(o){return(o===87||o===119)&&r<3?(r++,e.consume(o),s):o===46&&r===3?(e.consume(o),i):n(o)}function i(o){return o===null?n(o):t(o)}}function Nm(e,t,n){let r,s,i;return o;function o(u){return u===46||u===95?e.check(ha,l,a)(u):u===null||ee(u)||et(u)||u!==45&&rn(u)?l(u):(i=!0,e.consume(u),o)}function a(u){return u===95?r=!0:(s=r,r=void 0),e.consume(u),o}function l(u){return s||r||!i?n(u):t(u)}}function Pm(e,t){let n=0,r=0;return s;function s(o){return o===40?(n++,e.consume(o),s):o===41&&r<n?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(ha,t,i)(o):o===null||ee(o)||et(o)?t(o):(e.consume(o),s)}function i(o){return o===41&&r++,e.consume(o),s}}function jm(e,t,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(e.consume(a),r):a===38?(e.consume(a),i):a===93?(e.consume(a),s):a===60||a===null||ee(a)||et(a)?t(a):n(a)}function s(a){return a===null||a===40||a===91||ee(a)||et(a)?t(a):r(a)}function i(a){return ye(a)?o(a):n(a)}function o(a){return a===59?(e.consume(a),r):ye(a)?(e.consume(a),o):n(a)}}function Dm(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return ge(i)?n(i):t(i)}}function ga(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ee(e)}function ma(e){return!ye(e)}function ya(e){return!(e===47||Jn(e))}function Jn(e){return e===43||e===45||e===46||e===95||ge(e)}function Or(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 _m={tokenize:Vm,partial:!0};function Om(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:$m,continuation:{tokenize:Km},exit:Um}},text:{91:{name:"gfmFootnoteCall",tokenize:Bm},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Fm,resolveTo:zm}}}}function Fm(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;s--;){const l=r.events[s][1];if(l.type==="labelImage"){o=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return a;function a(l){if(!o||!o._balanced)return n(l);const u=Ne(r.sliceSerialize({start:o.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 zm(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)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[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",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function Bm(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,o;return a;function a(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&&!o||d===null||d===91||ee(d))return n(d);if(d===93){e.exit("chunkString");const p=e.exit("gfmFootnoteCallString");return s.includes(Ne(r.sliceSerialize(p)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return ee(d)||(o=!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 $m(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,o=0,a;return l;function l(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(y)}function c(y){if(o>999||y===93&&!a||y===null||y===91||ee(y))return n(y);if(y===93){e.exit("chunkString");const m=e.exit("gfmFootnoteDefinitionLabelString");return i=Ne(r.sliceSerialize(m)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),p}return ee(y)||(a=!0),o++,e.consume(y),y===92?d:c}function d(y){return y===91||y===92||y===93?(e.consume(y),o++,c):c(y)}function p(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),s.includes(i)||s.push(i),J(e,f,"gfmFootnoteDefinitionWhitespace")):n(y)}function f(y){return t(y)}}function Km(e,t,n){return e.check(Pt,t,e.attempt(_m,t,n))}function Um(e){e.exit("gfmFootnoteDefinition")}function Vm(e,t,n){const r=this;return J(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):n(i)}}function Hm(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(o,a){let l=-1;for(;++l<o.length;)if(o[l][0]==="enter"&&o[l][1].type==="strikethroughSequenceTemporary"&&o[l][1]._close){let u=l;for(;u--;)if(o[u][0]==="exit"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._open&&o[l][1].end.offset-o[l][1].start.offset===o[u][1].end.offset-o[u][1].start.offset){o[l][1].type="strikethroughSequence",o[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},o[u][1].start),end:Object.assign({},o[l][1].end)},d={type:"strikethroughText",start:Object.assign({},o[u][1].end),end:Object.assign({},o[l][1].start)},p=[["enter",c,a],["enter",o[u][1],a],["exit",o[u][1],a],["enter",d,a]],f=a.parser.constructs.insideSpan.null;f&&Ce(p,p.length,0,sn(f,o.slice(u+1,l),a)),Ce(p,p.length,0,[["exit",d,a],["enter",o[l][1],a],["exit",o[l][1],a],["exit",c,a]]),Ce(o,u-1,l-u+3,p),l=u+p.length-2;break}}for(l=-1;++l<o.length;)o[l][1].type==="strikethroughSequenceTemporary"&&(o[l][1].type="data");return o}function i(o,a,l){const u=this.previous,c=this.events;let d=0;return p;function p(y){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(y):(o.enter("strikethroughSequenceTemporary"),f(y))}function f(y){const m=ct(u);if(y===126)return d>1?l(y):(o.consume(y),d++,f);if(d<2&&!n)return l(y);const b=o.exit("strikethroughSequenceTemporary"),g=ct(y);return b._open=!g||g===2&&!!m,b._close=!m||m===2&&!!g,a(y)}}}class qm{constructor(){this.map=[]}add(t,n,r){Wm(this,t,n,r)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[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 Wm(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 Qm(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 Gm(){return{flow:{null:{name:"table",tokenize:Xm,resolveAll:Ym}}}}function Xm(e,t,n){const r=this;let s=0,i=0,o;return a;function a(C){let R=r.events.length-1;for(;R>-1;){const _=r.events[R][1].type;if(_==="lineEnding"||_==="linePrefix")R--;else break}const E=R>-1?r.events[R][1].type:null,z=E==="tableHead"||E==="tableRow"?T:l;return z===T&&r.parser.lazy[r.now().line]?n(C):z(C)}function l(C){return e.enter("tableHead"),e.enter("tableRow"),u(C)}function u(C){return C===124||(o=!0,i+=1),c(C)}function c(C){return C===null?n(C):U(C)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),f):n(C):G(C)?J(e,c,"whitespace")(C):(i+=1,o&&(o=!1,s+=1),C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),o=!0,c):(e.enter("data"),d(C)))}function d(C){return C===null||C===124||ee(C)?(e.exit("data"),c(C)):(e.consume(C),C===92?p:d)}function p(C){return C===92||C===124?(e.consume(C),d):d(C)}function f(C){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(C):(e.enter("tableDelimiterRow"),o=!1,G(C)?J(e,y,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):y(C))}function y(C){return C===45||C===58?b(C):C===124?(o=!0,e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),m):j(C)}function m(C){return G(C)?J(e,b,"whitespace")(C):b(C)}function b(C){return C===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),g):C===45?(i+=1,g(C)):C===null||U(C)?N(C):j(C)}function g(C){return C===45?(e.enter("tableDelimiterFiller"),v(C)):j(C)}function v(C){return C===45?(e.consume(C),v):C===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(C))}function w(C){return G(C)?J(e,N,"whitespace")(C):N(C)}function N(C){return C===124?y(C):C===null||U(C)?!o||s!==i?j(C):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(C)):j(C)}function j(C){return n(C)}function T(C){return e.enter("tableRow"),O(C)}function O(C){return C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),O):C===null||U(C)?(e.exit("tableRow"),t(C)):G(C)?J(e,O,"whitespace")(C):(e.enter("data"),B(C))}function B(C){return C===null||C===124||ee(C)?(e.exit("data"),O(C)):(e.consume(C),C===92?$:B)}function $(C){return C===92||C===124?(e.consume(C),B):B(C)}}function Ym(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],o=[0,0,0,0],a=!1,l=0,u,c,d;const p=new qm;for(;++n<e.length;){const f=e[n],y=f[1];f[0]==="enter"?y.type==="tableHead"?(a=!1,l!==0&&(Bs(p,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},y.start),end:Object.assign({},y.end)},p.add(n,0,[["enter",u,t]])):y.type==="tableRow"||y.type==="tableDelimiterRow"?(r=!0,d=void 0,i=[0,0,0,0],o=[0,n+1,0,0],a&&(a=!1,c={type:"tableBody",start:Object.assign({},y.start),end:Object.assign({},y.end)},p.add(n,0,[["enter",c,t]])),s=y.type==="tableDelimiterRow"?2:c?3:1):s&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")?(r=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],d=zt(p,t,i,s,void 0,d),i=[0,0,0,0]),o[2]=n)):y.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(o[0]=o[1],d=zt(p,t,i,s,void 0,d)),i=o,o=[i[1],n,0,0])):y.type==="tableHead"?(a=!0,l=n):y.type==="tableRow"||y.type==="tableDelimiterRow"?(l=n,i[1]!==0?(o[0]=o[1],d=zt(p,t,i,s,n,d)):o[1]!==0&&(d=zt(p,t,o,s,n,d)),s=0):s&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")&&(o[3]=n)}for(l!==0&&Bs(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=Qm(t.events,n))}return e}function zt(e,t,n,r,s,i){const o=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(i.end=Object.assign({},ot(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const l=ot(t.events,n[1]);if(i={type:o,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const u=ot(t.events,n[2]),c=ot(t.events,n[3]),d={type:a,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 y=n[2]+1,m=n[3]-n[2]-1;e.add(y,m,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},ot(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function Bs(e,t,n,r,s){const i=[],o=ot(t.events,n);s&&(s.end=Object.assign({},o),i.push(["exit",s,t])),r.end=Object.assign({},o),i.push(["exit",r,t]),e.add(n+1,0,i)}function ot(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const Jm={name:"tasklistCheck",tokenize:ey};function Zm(){return{text:{91:Jm}}}function ey(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 ee(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),o):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),o):n(l)}function o(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(l)}function a(l){return U(l)?t(l):G(l)?e.check({tokenize:ty},t,n)(l):n(l)}}function ty(e,t,n){return J(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function ny(e){return Ro([Mm(),Om(),Hm(e),Gm(),Zm()])}const ry={};function sy(e){const t=this,n=e||ry,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(ny(n)),i.push(wm()),o.push(Cm(n))}function iy(){var e;return typeof navigator<"u"&&typeof((e=navigator.clipboard)==null?void 0:e.writeText)=="function"}function oy(e){if(typeof document>"u")return;const t=document.getSelection();t&&(t.removeAllRanges(),e.forEach(n=>t.addRange(n)))}function $s(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()):[],o=document.createElement("textarea");o.value=e,o.setAttribute("readonly",""),o.setAttribute("aria-hidden","true"),o.style.position="fixed",o.style.top="0",o.style.left="-9999px",o.style.opacity="0",o.style.pointerEvents="none",o.style.fontSize="12pt",document.body.appendChild(o);try{o.focus({preventScroll:!0})}catch{o.focus()}o.select(),o.setSelectionRange(0,o.value.length);let a=!1;try{a=typeof document.execCommand=="function"&&document.execCommand("copy")}catch{a=!1}if(o.remove(),t)try{t.focus({preventScroll:!0})}catch{t.focus()}return n&&r?n.setSelectionRange(r.start,r.end):oy(i),a}async function ay(e){if(!e)return!1;if(iy())try{return await navigator.clipboard.writeText(e),!0}catch{return $s(e)}return $s(e)}const ly=1300;function uy(e){const[t,n]=k.useState(!1),r=k.useCallback(async()=>{if(!e.text)return;const s=await ay(e.text);n(!!s)},[e.text]);return k.useEffect(()=>{if(!t||typeof window>"u")return;const s=window.setTimeout(()=>n(!1),e.resetDelayMs??ly);return()=>window.clearTimeout(s)},[t,e.resetDelayMs]),{copied:t,copy:r}}const cy=/language-([a-z0-9-]+)/i;function xa(e){return typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(xa).join(""):""}function dy(e){const t=xa(e);return t.endsWith(`
|
|
31
|
+
`)?t.slice(0,-1):t}function hy(e){var n;const t=e?cy.exec(e):null;return((n=t==null?void 0:t[1])==null?void 0:n.toLowerCase())||"text"}function fy(e){const t=k.useMemo(()=>hy(e.className),[e.className]),n=k.useMemo(()=>dy(e.children),[e.children]),{copied:r,copy:s}=uy({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(Jt,{className:"h-3.5 w-3.5"}):h.jsx(yl,{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 Ks=14e4,py=new Set(["http:","https:","mailto:","tel:"]);function gy(e){return e.length<=Ks?e:`${e.slice(0,Ks)}
|
|
32
32
|
|
|
33
|
-
...`}function Us(e){if(!e)return null;if(e.startsWith("#")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))return e;try{const t=new URL(e);return
|
|
34
|
-
`)?h.jsx("code",{...i,className:de("chat-inline-code",r),children:s}):h.jsx(
|
|
35
|
-
`),r=n?`${t.slice(0,Vs)}...`: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:[by(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 ky(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 vy(e){const{message:t,texts:n}=e,{role:r}=t,s=r==="user";return h.jsx("div",{className:de("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,o)=>i.type==="markdown"?h.jsx(my,{text:i.text,role:r,texts:n},`markdown-${o}`):i.type==="reasoning"?h.jsx(xy,{label:i.label,text:i.text,isUser:s},`reasoning-${o}`):i.type==="tool-card"?h.jsx("div",{className:"mt-0.5",children:h.jsx(Sy,{card:i.card})},`tool-${o}`):i.type==="file"?h.jsx(yy,{file:i.file},`file-${o}`):i.type==="unknown"?h.jsx(ky,{label:i.label,rawType:i.rawType,text:i.text},`unknown-${o}`):null)})})}function wy(e){return h.jsxs("div",{className:de("px-1 text-[11px] leading-4 text-gray-400",e.isUser?"text-right":"text-left"),children:[e.roleLabel," · ",e.timestampLabel]})}const Cy=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Ty(e){const t=e.trim();return t?t.replace(Cy,"").trim().length>0:!1}function Iy(e){return e.parts.some(t=>t.type==="markdown"||t.type==="reasoning"?Ty(t.text):!0)}function My(e){const t=e.messages.filter(Iy),n=t.some(r=>r.role==="assistant"&&(r.status==="streaming"||r.status==="pending"));return h.jsxs("div",{className:de("space-y-5",e.className),children:[t.map(r=>{const s=r.role==="user";return h.jsxs("div",{className:de("flex gap-3",s?"justify-end":"justify-start"),children:[s?null:h.jsx(hn,{role:r.role}),h.jsxs("div",{className:de("w-fit max-w-[92%] space-y-2",s&&"flex flex-col items-end"),children:[h.jsx(vy,{message:r,texts:e.texts}),h.jsx(wy,{roleLabel:r.roleLabel,timestampLabel:r.timestampLabel,isUser:s})]}),s?h.jsx(hn,{role:r.role}):null]},r.id)}),e.isSending&&!n?h.jsxs("div",{className:"flex justify-start gap-3",children:[h.jsx(hn,{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 Ry=10;function Hs(e){e.scrollTop=e.scrollHeight}function Ay(e){const t=k.useRef(!0),n=k.useRef(!1),r=k.useRef(null),s=k.useRef(!1),i=k.useCallback(()=>{if(n.current){n.current=!1;return}const o=e.scrollRef.current;if(!o)return;const a=o.scrollHeight-o.scrollTop-o.clientHeight;t.current=a<=(e.stickyThresholdPx??Ry)},[e.scrollRef,e.stickyThresholdPx]);return k.useEffect(()=>{r.current!==e.resetKey&&(r.current=e.resetKey,t.current=!0,s.current=!0)},[e.resetKey]),k.useLayoutEffect(()=>{if(!s.current||e.isLoading||!e.hasContent)return;const o=e.scrollRef.current;o&&(s.current=!1,n.current=!0,Hs(o))},[e.hasContent,e.isLoading,e.scrollRef]),k.useLayoutEffect(()=>{if(!t.current||!e.hasContent)return;const o=e.scrollRef.current;o&&(n.current=!0,Hs(o))},[e.contentVersion,e.hasContent,e.scrollRef]),{onScroll:i}}function Fr(){return xr()}function xa(e){return dc(e)}function Zn(e){return fc(e)}function er(e){return nn(e,"skill")}function Ey(e){return nn(e,"file")}function ba(e,t,n){const r=new Set(t),s=br(e,l=>l.tokenKind==="skill"&&!r.has(l.tokenKey)),i=nn(s,"skill"),o=new Map(n.map(l=>[l.spec,l])),a=t.filter(l=>!i.includes(l)).map(l=>{var u;return yr({tokenKind:"skill",tokenKey:l,label:((u=o.get(l))==null?void 0:u.label)||l})});return a.length===0?s:ut([...s,...a])}function qs(e,t){const n=new Set(t.map(r=>r.id));return br(e,r=>r.tokenKind==="file"&&!n.has(r.tokenKey))}function Ly(e,t){const n=new Set(Ey(e));return t.filter(r=>n.has(r.id))}function Ny(e,t){const n=new Map(t.map(s=>[s.id,s])),r=[];for(const s of e){if(s.type==="text"){s.text.length>0&&r.push({type:"text",text:s.text});continue}if(s.tokenKind!=="file")continue;const i=n.get(s.tokenKey);i&&r.push({type:"file",name:i.name,mimeType:i.mimeType,contentBase64:i.contentBase64,sizeBytes:i.sizeBytes})}return r}const Py={isProviderStateResolved:!1,composerNodes:Fr(),attachments:[],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:[]},V=Zt(e=>({snapshot:Py,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),jy={sessionRunStatusByKey:new Map,isLocallyRunning:!1,activeBackendRunId:null},tr=Zt(e=>({snapshot:jy,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),Dy={sessions:[],selectedSessionKey:null,selectedAgentId:"main",query:"",isLoading:!1},ie=Zt(e=>({snapshot:Dy,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function _y(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),r=n-864e5,s=n-7*864e5,i=[],o=[],a=[],l=[];for(const c of e){const d=new Date(c.updatedAt).getTime();d>=n?i.push(c):d>=r?o.push(c):d>=s?a.push(c):l.push(c)}const u=[];return i.length>0&&u.push({label:I("chatSidebarToday"),sessions:i}),o.length>0&&u.push({label:I("chatSidebarYesterday"),sessions:o}),a.length>0&&u.push({label:I("chatSidebarPrevious7Days"),sessions:a}),l.length>0&&u.push({label:I("chatSidebarOlder"),sessions:l}),u}function Oy(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}function Fy(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(" ")}function zy(e){var t;return e.ready===!1?((t=e.reasonMessage)==null?void 0:t.trim())||I("statusSetup"):I("statusReady")}const By=[{target:"/cron",label:()=>I("chatSidebarScheduledTasks"),icon:hr},{target:"/skills",label:()=>I("chatSidebarSkills"),icon:cr}];function $y(){var A,K;const e=mr(),t=Ol(),n=en(),[r,s]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(""),[u,c]=k.useState(null),d=V(L=>L.snapshot),p=ie(L=>L.snapshot),f=tr(L=>L.snapshot),y=Fl(L=>L.connectionStatus),{language:m,setLanguage:b}=gr(),{theme:g,setTheme:v}=zl(),w=Bu(),N=Fi(n.search),j=I(((A=Br.find(L=>L.value===g))==null?void 0:A.labelKey)??"themeWarm"),T=((K=$r.find(L=>L.value===m))==null?void 0:K.label)??m,O=k.useMemo(()=>_y(p.sessions),[p.sessions]),B=d.defaultSessionType||"native",$=k.useMemo(()=>d.sessionTypeOptions.filter(L=>L.value!==B),[B,d.sessionTypeOptions]),C=L=>{m!==L&&(b(L),window.location.reload())},R=(L,G)=>{const{sessions:ae}=ie.getState().snapshot;ie.getState().setSnapshot({sessions:ae.map(x=>x.key===L?{...x,...G?{label:G}:{label:void 0}}:x)})},E=L=>{var G;o(L.key),l(((G=L.label)==null?void 0:G.trim())??"")},z=()=>{o(null),l(""),c(null)},_=async L=>{var x;const G=a.trim(),ae=((x=L.label)==null?void 0:x.trim())??"";if(G===ae){z();return}c(L.key);try{await w({chatChain:N,sessionKey:L.key,label:G||null}),R(L.key,G||void 0),z()}catch{c(null)}};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(Bl,{className:"flex items-center gap-2.5 min-w-0",suffix:h.jsx(Fu,{status:y})})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsxs(Ve,{variant:"primary",className:Le("min-w-0 rounded-xl",$.length>0?"flex-1 rounded-r-md":"w-full"),onClick:()=>{s(!1),e.chatSessionListManager.createSession(B)},children:[h.jsx(kl,{className:"h-4 w-4 mr-2"}),I("chatSidebarNewTask")]}),$.length>0?h.jsxs(wu,{open:r,onOpenChange:s,children:[h.jsx(Cu,{asChild:!0,children:h.jsx(Ve,{variant:"primary",size:"icon",className:"h-9 w-10 shrink-0 rounded-xl rounded-l-md","aria-label":I("chatSessionTypeLabel"),children:h.jsx(ur,{className:"h-4 w-4"})})}),h.jsxs(Tu,{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:I("chatSessionTypeLabel")}),h.jsx("div",{className:"mt-1 space-y-1",children:$.map(L=>h.jsxs("button",{type:"button",onClick:()=>{e.chatSessionListManager.createSession(L.value),s(!1)},className:"w-full rounded-xl px-3 py-2 text-left transition-colors hover:bg-gray-100",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("div",{className:"text-[13px] font-medium text-gray-900",children:L.label}),h.jsx("span",{className:Le("shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold",L.ready===!1?"bg-amber-100 text-amber-800":"bg-emerald-100 text-emerald-700"),children:L.ready===!1?I("statusSetup"):I("statusReady")})]}),h.jsx("div",{className:"mt-0.5 text-[11px] text-gray-500",children:zy(L)})]},L.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(pr,{value:p.query,onChange:L=>e.chatSessionListManager.setQuery(L.target.value),placeholder:I("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:By.map(L=>h.jsx("li",{children:h.jsx(Kr,{to:L.target,label:L.label(),icon:L.icon,density:"compact"})},L.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:p.isLoading?h.jsx("div",{className:"text-xs text-gray-500 p-3",children:I("sessionsLoading")}):O.length===0?h.jsxs("div",{className:"p-4 text-center",children:[h.jsx(vl,{className:"h-6 w-6 mx-auto mb-2 text-gray-300"}),h.jsx("div",{className:"text-xs text-gray-500",children:I("sessionsEmpty")})]}):h.jsx("div",{className:"space-y-3",children:O.map(L=>h.jsxs("div",{children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider",children:L.label}),h.jsx("div",{className:"space-y-0.5",children:L.sessions.map(G=>{const ae=p.selectedSessionKey===G.key,x=f.sessionRunStatusByKey.get(G.key),oe=Fy(G.sessionType,d.sessionTypeOptions),re=i===G.key,S=u===G.key;return h.jsx(zu,{session:G,active:ae,runStatus:x,sessionTypeLabel:oe,title:Oy(G),isEditing:re,draftLabel:a,isSaving:S,onSelect:()=>e.chatSessionListManager.selectSession(G.key),onStartEditing:()=>E(G),onDraftLabelChange:l,onSave:()=>_(G),onCancel:z},G.key)})})]},L.label))})}),h.jsxs("div",{className:"px-3 py-3 border-t border-gray-200/60 space-y-0.5",children:[h.jsx(Kr,{to:"/settings",label:I("settings"),icon:wl,density:"compact"}),h.jsx($l,{onClick:()=>t.open(void 0,{kind:"docs",newTab:!0,title:"Docs"}),icon:Cl,label:I("docBrowserHelp"),density:"compact"}),h.jsx(Ur,{value:g,onValueChange:L=>v(L),icon:Tl,label:I("theme"),valueLabel:j,density:"compact",children:Br.map(L=>h.jsx(vt,{value:L.value,className:"text-xs",children:I(L.labelKey)},L.value))}),h.jsx(Ur,{value:m,onValueChange:L=>C(L),icon:Il,label:I("language"),valueLabel:T,density:"compact",children:$r.map(L=>h.jsx(vt,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})}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||{}),Ws=/\[\[\s*reply_to_current\s*\]\]/gi,Gs=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function nr(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function Ky(e,t){var i;let n=e,r;Ws.test(n)&&(r=nr(t),n=n.replace(Ws,"").trim());const s=(i=n.match(Gs))==null?void 0:i[1];return s&&(r=nr(s),n=n.replace(Gs,"").trim()),r?{content:n,replyTo:r}:{content:n}}function Uy(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=nr(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:o,replyTo:a}=Ky(i.text,t),l=a??s,u=e.parts.flatMap((c,d)=>d!==n||c.type!=="text"?[c]:o.length===0?[]:[{...c,text:o}]);return l?{...e,parts:u,metadata:{...r,reply_to:l}}:{...e,parts:u,metadata:r}}function Ht(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function En(e){return Ht(Uy(e))}function Vy(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 Hy(e,t){return t.trim()?e.id.startsWith("tool-")?!0:e.parts.some(n=>n.type==="tool-invocation"):!1}function qy(e,t,n){for(const[r,s]of e)s===t&&e.set(r,n)}function Ln(e,t,n){for(const[r,s]of e)s===n&&(e.delete(r),t.delete(r))}function rr(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 Qs(e,t){const n=rr(e,t);return(n==null?void 0:n.toolName)??null}function St(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 Wy="assistant",Gy=class{constructor(){F(this,"messages",[]);F(this,"streamingMessage",null);F(this,"error",null);F(this,"activeRun",null);F(this,"listeners",new Set);F(this,"toolCallMessageIdByCallId",new Map);F(this,"toolCallArgsRawByCallId",new Map);F(this,"snapshotCache",null);F(this,"snapshotVersion",-1);F(this,"stateVersion",0)}getSnapshot(){if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;const e={messages:this.messages.map(t=>Ht(t)),streamingMessage:this.streamingMessage?Ht(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=>En(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?Ln(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):Ln(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=St(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=St(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:Qs(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 St(n.parts,s)})){const n=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),r=St(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){this.settleStreamingMessage("final"),this.setError(null),this.clearActiveRun()}handleRunError(e){this.settleStreamingMessage("error"),this.setError(Vy(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){var t,n,r;if(e.code==="abort-error"){this.handleMessageAbort({sessionId:((t=this.activeRun)==null?void 0:t.sessionId)??((n=this.streamingMessage)==null?void 0:n.sessionId)??"",...(r=this.streamingMessage)!=null&&r.id?{messageId:this.streamingMessage.id}:{}});return}this.settleStreamingMessage("error"),this.clearActiveRun(),this.setError(e)}applyToolCallArgs(e,t,n,r){const s=this.resolveToolCallTargetMessage(e,t,r),i=Qs(s.parts,t)??"unknown",o=St(s.parts,{type:"tool-invocation",toolCallId:t,toolName:i,state:"partial-call",args:n});this.replaceStreamingMessage({...s,parts:o,status:"streaming"})}ensureStreamingMessage(e,t,n){var o;if(((o=this.streamingMessage)==null?void 0:o.id)===t){if(this.streamingMessage.status===n)return this.streamingMessage;const a={...this.streamingMessage,status:n};return this.replaceStreamingMessage(a),a}const r=this.messages.findIndex(a=>a.id===t);if(r>=0){const a=Ht(this.messages[r]),l=[...this.messages];l.splice(r,1),this.messages=l,this.stateVersion+=1;const u={...a,sessionId:e,status:n};return this.replaceStreamingMessage(u),u}const s=this.streamingMessage;if(s&&s.id!==t&&s.sessionId===e&&Hy(s,t)){const a={...s,id:t,sessionId:e,status:n};return qy(this.toolCallMessageIdByCallId,s.id,t),this.replaceStreamingMessage(a),a}const i={id:t,sessionId:e,role:Wy,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=rr(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=rr(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=En(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?En(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)}settleStreamingMessage(e){if(!this.streamingMessage)return;const t={...this.streamingMessage,status:e};this.upsertMessage(t),this.replaceStreamingMessage(null),Ln(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)}notifyListeners(){const e=this.getSnapshot();for(const t of this.listeners)t(e)}};function Qy(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 Xy(e){return e.parts.some(t=>t.type==="text"||t.type==="rich-text"||t.type==="reasoning"?t.text.trim().length>0:!0)}function Yy(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 Xy(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function Jy(e){const t=k.useRef();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new Gy}),t.current.manager}function Zy({sessionId:e,client:t,manager:n}){var p;const r=k.useSyncExternalStore(f=>n.subscribe(()=>f()),()=>n.getSnapshot(),()=>n.getSnapshot()),[s,i]=k.useState(!1);k.useEffect(()=>{i(!1)},[e]),k.useEffect(()=>{const f=t.subscribe(y=>{Qy(y,e)&&n.dispatch(y)});return()=>{f(),t.stop()}},[t,n,e]);const o=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,a=((p=r.activeRun)==null?void 0:p.runId)??null,l=!!r.activeRun;return{snapshot:r,visibleMessages:o,activeRunId:a,isRunning:l,isSending:s,send:async f=>{if(s||l)return;const y=Yy(f,e);if(y){i(!0),await n.dispatch({type:ne.MessageSent,payload:{sessionId:e,message:y.message,metadata:y.metadata}});try{await t.send(y)}finally{i(!1)}}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{r.activeRun&&await t.stream({sessionId:e})}}}function Xs(e){return e instanceof Error?e:new Error(String(e))}function ex({sessionId:e,client:t,loadSeed:n,autoResumeRunningSession:r=!0}){const s=Jy(e),i=Zy({sessionId:e,client:t,manager:s}),[o,a]=k.useState(!0),[l,u]=k.useState(null),c=k.useRef({requestId:0,controller:null}),d=k.useCallback(async()=>{var y;(y=c.current.controller)==null||y.abort();const p=new AbortController,f=c.current.requestId+1;c.current={requestId:f,controller:p},await t.stop(),s.reset(),u(null),a(!0);try{const m=await n(e,p.signal);if(p.signal.aborted||c.current.requestId!==f)return;s.hydrate({sessionId:e,messages:m.messages,activeRun:m.status==="running"?{runId:null,sessionId:e,abortDisabledReason:null}:null}),u(null),a(!1),m.status==="running"&&r&&t.stream({sessionId:e}).catch(b=>{c.current.requestId===f&&u(Xs(b))})}catch(m){if(p.signal.aborted||c.current.requestId!==f)return;u(Xs(m)),a(!1)}finally{c.current.controller===p&&(c.current.controller=null)}},[r,t,n,s,e]);return k.useEffect(()=>(d(),()=>{var p;(p=c.current.controller)==null||p.abort(),c.current.controller=null}),[d]),{...i,isHydrating:o,hydrateError:l,reloadSeed:d}}var tx="image/png,image/jpeg,image/webp,image/gif",nx=["image/png","image/jpeg","image/webp","image/gif"],Sa=10*1024*1024;function rx(){return`ncp-file-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function sx(e){return new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error??new Error(`Failed to read ${e.name}`)),r.onload=()=>{if(typeof r.result!="string"){n(new Error(`Unexpected FileReader result for ${e.name}`));return}t(r.result)},r.readAsDataURL(e)})}function ix(e){const t=e.indexOf(",");return t>=0?e.slice(t+1):e}function ox(e){var s;const t=e.parts&&e.parts.length>0?e.parts.map(i=>structuredClone(i)):[...((s=e.text)==null?void 0:s.trim())??""?[{type:"text",text:e.text.trim()}]:[],...(e.attachments??[]).map(i=>({type:"file",name:i.name,mimeType:i.mimeType,contentBase64:i.contentBase64,sizeBytes:i.sizeBytes}))];if(t.length===0)return null;const n=e.timestamp??new Date().toISOString(),r=e.messageId??`user-${Date.now().toString(36)}`;return{sessionId:e.sessionId,message:{id:r,sessionId:e.sessionId,role:"user",status:"final",parts:t,timestamp:n,...e.metadata?{metadata:e.metadata}:{}},...e.metadata?{metadata:e.metadata}:{}}}async function ax(e,t={}){const n=new Set(t.acceptedMimeTypes??nx),r=t.maxBytes??Sa,s=[],i=[];for(const o of e){const a=o.type.trim().toLowerCase();if(!n.has(a)){i.push({fileName:o.name,mimeType:a,sizeBytes:o.size,reason:"unsupported-type"});continue}if(o.size>r){i.push({fileName:o.name,mimeType:a,sizeBytes:o.size,reason:"too-large"});continue}try{const l=await sx(o);s.push({id:rx(),name:o.name,mimeType:a,contentBase64:ix(l),sizeBytes:o.size})}catch{i.push({fileName:o.name,mimeType:a,sizeBytes:o.size,reason:"read-failed"})}}return{attachments:s,rejected:i}}const De={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function Bt(e){return(e??"").trim().toLowerCase()}function Ys(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 lx(e,t){const n=Bt(t);if(!n)return De.fallback;const r=Bt(e.key),s=Bt(e.label||e.key),i=Bt(`${e.descriptionZh??""} ${e.description??""}`),o=s.split(/[\s/_-]+/).filter(Boolean);return r===n?De.exactSpec:s===n?De.exactLabel:r.startsWith(n)?De.prefixSpec:s.startsWith(n)?De.prefixLabel:o.some(a=>a.startsWith(n))?De.prefixToken:r.includes(n)?De.containsSpec:s.includes(n)?De.containsLabel:i.includes(n)?De.containsDescription:Ys(n,s)||Ys(n,r)?De.subsequence:0}function ux(e,t,n){const r=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0});return e.map((s,i)=>({record:s,order:i,score:lx(s,t)})).filter(s=>s.score>0).sort((s,i)=>{if(i.score!==s.score)return i.score-s.score;const o=(s.record.label||s.record.key).trim(),a=(i.record.label||i.record.key).trim(),l=r.compare(o,a);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 cx(e){return e.map(t=>({key:t.key,label:t.label,description:t.descriptionZh||t.description||"",badgeLabel:t.badgeLabel}))}function dx(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:cx(e.skillRecords),selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}function hx(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 fx(e){const t=e.modelOptions.find(i=>i.value===e.selectedModel),n=e.modelOptions[0],r=t??n;return{key:"model",value:e.hasModelOptions?r==null?void 0:r.value:void 0,placeholder:e.texts.modelSelectPlaceholder,selectedLabel:r?`${r.providerLabel}/${r.modelLabel}`:void 0,icon:"sparkles",options:e.modelOptions.map(i=>({value:i.value,label:i.modelLabel,description:i.providerLabel})),disabled:!e.hasModelOptions,loading:e.isModelOptionsLoading,emptyLabel:e.texts.modelNoOptionsLabel,onValueChange:e.onValueChange}}function px(e){const t=[];for(const n of["off",...e])t.includes(n)||t.push(n);return t}function gx(e){if(e.supportedLevels.length===0)return null;const t=px(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 mx(){return{off:I("chatThinkingLevelOff"),minimal:I("chatThinkingLevelMinimal"),low:I("chatThinkingLevelLow"),medium:I("chatThinkingLevelMedium"),high:I("chatThinkingLevelHigh"),adaptive:I("chatThinkingLevelAdaptive"),xhigh:I("chatThinkingLevelXhigh")}}function yx(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 xx(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 bx(){var C;const e=mr(),{language:t}=gr(),n=V(R=>R.snapshot),[r,s]=k.useState(null),i=k.useRef(null),o=k.useRef(null),a=k.useMemo(()=>I("chatSkillsPickerOfficial"),[t]),l=k.useMemo(()=>({slashSkillSubtitle:I("chatSlashTypeSkill"),slashSkillSpecLabel:I("chatSlashSkillSpec"),noSkillDescription:I("chatSkillsPickerNoDescription")}),[t]),u=k.useMemo(()=>yx(n.skillRecords,a),[n.skillRecords,a]),c=k.useMemo(()=>xx(n.modelOptions),[n.modelOptions]),d=c.length>0,p=!n.isProviderStateResolved&&!d,f=n.isProviderStateResolved&&!d,y=(p||f)&&!n.isSending||n.sessionTypeUnavailable,m=typeof e.chatInputManager.addAttachments=="function",b=p?"":d?I("chatInputPlaceholder"):I("chatModelNoOptions"),g=k.useMemo(()=>ux(u,r??"",l),[r,u,l]),v=c.find(R=>R.value===n.selectedModel),w=v==null?void 0:v.thinkingCapability,N=(w==null?void 0:w.supported)??[],j=n.stopDisabledReason==="__preparing__"?I("chatStopPreparing"):((C=n.stopDisabledReason)==null?void 0:C.trim())||I("chatStopUnavailable"),T=k.useCallback(R=>{if(R==="unsupported-type"){kt.error(I("chatInputImageUnsupported"));return}if(R==="too-large"){kt.error(I("chatInputImageTooLarge").replace("{maxMb}",String(Sa/(1024*1024))));return}kt.error(I("chatInputImageReadFailed"))},[]),O=k.useCallback(async R=>{var z,_,A;if(!m||R.length===0)return;const E=await ax(R);if(E.attachments.length>0){const K=((_=(z=e.chatInputManager).addAttachments)==null?void 0:_.call(z,E.attachments))??[];K.length>0&&((A=i.current)==null||A.insertFileTokens(K.map(L=>({tokenKey:L.id,label:L.name}))))}E.rejected.length>0&&T(E.rejected[0].reason)},[m,e.chatInputManager,T]),B=[fx({modelOptions:c,selectedModel:n.selectedModel,isModelOptionsLoading:p,hasModelOptions:d,onValueChange:e.chatInputManager.selectModel,texts:{modelSelectPlaceholder:I("chatSelectModel"),modelNoOptionsLabel:I("chatModelNoOptions")}}),gx({supportedLevels:N,selectedThinkingLevel:n.selectedThinkingLevel,defaultThinkingLevel:(w==null?void 0:w.default)??null,onValueChange:R=>e.chatInputManager.selectThinkingLevel(R),texts:{thinkingLabels:mx()}})].filter(R=>R!==null),$=dx({skillRecords:u,selectedSkills:n.selectedSkills,isLoading:n.isSkillsLoading,onSelectedKeysChange:e.chatInputManager.selectSkills,texts:{title:I("chatSkillsPickerTitle"),searchPlaceholder:I("chatSkillsPickerSearchPlaceholder"),emptyLabel:I("chatSkillsPickerEmpty"),loadingLabel:I("sessionsLoading"),manageLabel:I("chatSkillsPickerManage")}});return h.jsxs(h.Fragment,{children:[h.jsx(ho,{ref:i,composer:{nodes:n.composerNodes,placeholder:b,disabled:y,onNodesChange:e.chatInputManager.setComposerNodes,...m?{onFilesAdd:O}:{},onSlashQueryChange:s},slashMenu:{isLoading:n.isSkillsLoading,items:g,texts:{slashLoadingLabel:I("chatSlashLoading"),slashSectionLabel:I("chatSlashSectionSkills"),slashEmptyLabel:I("chatSlashNoResult"),slashHintLabel:I("chatSlashHint"),slashSkillHintLabel:I("chatSlashSkillHint")}},hint:hx({isModelOptionsLoading:p,isModelOptionsEmpty:f,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:I("chatModelNoOptions"),configureProviderLabel:I("chatGoConfigureProvider")}}),toolbar:{selects:B,accessories:[{key:"attach",label:I("chatInputAttach"),icon:"paperclip",iconOnly:!0,disabled:!m||y||n.isSending,...m?{onClick:()=>{var R;return(R=o.current)==null?void 0:R.click()}}:{tooltip:I("chatInputAttachComingSoon")}}],skillPicker:$,actions:{sendError:n.sendError,isSending:n.isSending,canStopGeneration:n.canStopGeneration,sendDisabled:n.draft.trim().length===0&&n.attachments.length===0||!d||n.sessionTypeUnavailable,stopDisabled:!n.canStopGeneration,stopHint:j,sendButtonLabel:I("chatSend"),stopButtonLabel:I("chatStop"),onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}}),m?h.jsx("input",{ref:o,type:"file",accept:tx,multiple:!0,className:"hidden",onChange:async R=>{const E=Array.from(R.target.files??[]);R.currentTarget.value="",await O(E)}}):null]})}function qe(e){return typeof e=="function"}function ka(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 Nn=ka(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
33
|
+
...`}function Us(e){if(!e)return null;if(e.startsWith("#")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))return e;try{const t=new URL(e);return py.has(t.protocol)?e:null}catch{return null}}function my(e){return/^https?:\/\//i.test(e)}function yy(e){const t=e.role==="user",n=k.useMemo(()=>({a:({href:r,children:s,...i})=>{const o=Us(r);if(!o)return h.jsx("span",{className:"chat-link-invalid",children:s});const a=my(o);return h.jsx("a",{...i,href:o,target:a?"_blank":void 0,rel:a?"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 o=Us(r);return o?h.jsx("img",{...i,src:o,alt:s||"",loading:"lazy",decoding:"async"}):null},code:({className:r,children:s,...i})=>{const o=String(s??"");return!r&&!o.includes(`
|
|
34
|
+
`)?h.jsx("code",{...i,className:de("chat-inline-code",r),children:s}):h.jsx(fy,{className:r,texts:e.texts,children:s})}}),[e.texts]);return h.jsx("div",{className:de("chat-markdown",t?"chat-markdown-user":"chat-markdown-assistant"),children:h.jsx(Hp,{skipHtml:!0,remarkPlugins:[sy],components:n,children:gy(e.text)})})}function xy({file:e}){return e.isImage&&e.dataUrl?h.jsx("img",{src:e.dataUrl,alt:e.label,className:"block max-h-80 max-w-full rounded-2xl object-contain"}):e.dataUrl?h.jsxs("a",{href:e.dataUrl,download:e.label,target:"_blank",rel:"noreferrer",className:"block rounded-2xl border border-black/8 bg-black/6 px-3 py-2 text-sm transition hover:bg-black/8",children:[h.jsx("div",{className:"font-medium",children:e.label}),h.jsx("div",{className:"text-xs opacity-75",children:e.mimeType})]}):h.jsxs("div",{className:"rounded-2xl border border-black/8 bg-black/6 px-3 py-2 text-sm",children:[h.jsx("div",{className:"font-medium",children:e.label}),h.jsx("div",{className:"text-xs opacity-75",children:e.mimeType})]})}function by(e){return h.jsxs("details",{className:"mt-3",open:!0,children:[h.jsx("summary",{className:de("cursor-pointer text-xs",e.isUser?"text-primary-100":"text-gray-500"),children:e.label}),h.jsx("pre",{className:de("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 Vs=220;function Sy(e){const t=e.toLowerCase();return t.includes("exec")||t.includes("shell")||t.includes("command")?h.jsx(xl,{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(bl,{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(kl,{className:"h-3.5 w-3.5"}):t.includes("cron")||t.includes("schedule")?h.jsx(vl,{className:"h-3.5 w-3.5"}):h.jsx(vi,{className:"h-3.5 w-3.5"})}function ky({card:e}){var i;const t=((i=e.output)==null?void 0:i.trim())??"",n=t.length>Vs||t.includes(`
|
|
35
|
+
`),r=n?`${t.slice(0,Vs)}...`: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:[Sy(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 vy(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 wy(e){const{message:t,texts:n}=e,{role:r}=t,s=r==="user";return h.jsx("div",{className:de("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,o)=>i.type==="markdown"?h.jsx(yy,{text:i.text,role:r,texts:n},`markdown-${o}`):i.type==="reasoning"?h.jsx(by,{label:i.label,text:i.text,isUser:s},`reasoning-${o}`):i.type==="tool-card"?h.jsx("div",{className:"mt-0.5",children:h.jsx(ky,{card:i.card})},`tool-${o}`):i.type==="file"?h.jsx(xy,{file:i.file},`file-${o}`):i.type==="unknown"?h.jsx(vy,{label:i.label,rawType:i.rawType,text:i.text},`unknown-${o}`):null)})})}function Cy(e){return h.jsxs("div",{className:de("px-1 text-[11px] leading-4 text-gray-400",e.isUser?"text-right":"text-left"),children:[e.roleLabel," · ",e.timestampLabel]})}const Ty=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Iy(e){const t=e.trim();return t?t.replace(Ty,"").trim().length>0:!1}function My(e){return e.parts.some(t=>t.type==="markdown"||t.type==="reasoning"?Iy(t.text):!0)}function Ry(e){const t=e.messages.filter(My),n=t.some(r=>r.role==="assistant"&&(r.status==="streaming"||r.status==="pending"));return h.jsxs("div",{className:de("space-y-5",e.className),children:[t.map(r=>{const s=r.role==="user";return h.jsxs("div",{className:de("flex gap-3",s?"justify-end":"justify-start"),children:[s?null:h.jsx(hn,{role:r.role}),h.jsxs("div",{className:de("w-fit max-w-[92%] space-y-2",s&&"flex flex-col items-end"),children:[h.jsx(wy,{message:r,texts:e.texts}),h.jsx(Cy,{roleLabel:r.roleLabel,timestampLabel:r.timestampLabel,isUser:s})]}),s?h.jsx(hn,{role:r.role}):null]},r.id)}),e.isSending&&!n?h.jsxs("div",{className:"flex justify-start gap-3",children:[h.jsx(hn,{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 Ay=10;function Hs(e){e.scrollTop=e.scrollHeight}function Ey(e){const t=k.useRef(!0),n=k.useRef(!1),r=k.useRef(null),s=k.useRef(!1),i=k.useCallback(()=>{if(n.current){n.current=!1;return}const o=e.scrollRef.current;if(!o)return;const a=o.scrollHeight-o.scrollTop-o.clientHeight;t.current=a<=(e.stickyThresholdPx??Ay)},[e.scrollRef,e.stickyThresholdPx]);return k.useEffect(()=>{r.current!==e.resetKey&&(r.current=e.resetKey,t.current=!0,s.current=!0)},[e.resetKey]),k.useLayoutEffect(()=>{if(!s.current||e.isLoading||!e.hasContent)return;const o=e.scrollRef.current;o&&(s.current=!1,n.current=!0,Hs(o))},[e.hasContent,e.isLoading,e.scrollRef]),k.useLayoutEffect(()=>{if(!t.current||!e.hasContent)return;const o=e.scrollRef.current;o&&(n.current=!0,Hs(o))},[e.contentVersion,e.hasContent,e.scrollRef]),{onScroll:i}}function Fr(){return xr()}function ba(e){return hc(e)}function Zn(e){return pc(e)}function er(e){return nn(e,"skill")}function Ly(e){return nn(e,"file")}function Sa(e,t,n){const r=new Set(t),s=br(e,l=>l.tokenKind==="skill"&&!r.has(l.tokenKey)),i=nn(s,"skill"),o=new Map(n.map(l=>[l.spec,l])),a=t.filter(l=>!i.includes(l)).map(l=>{var u;return yr({tokenKind:"skill",tokenKey:l,label:((u=o.get(l))==null?void 0:u.label)||l})});return a.length===0?s:ut([...s,...a])}function qs(e,t){const n=new Set(t.map(r=>r.id));return br(e,r=>r.tokenKind==="file"&&!n.has(r.tokenKey))}function Ny(e,t){const n=new Set(Ly(e));return t.filter(r=>n.has(r.id))}function Py(e,t){const n=new Map(t.map(s=>[s.id,s])),r=[];for(const s of e){if(s.type==="text"){s.text.length>0&&r.push({type:"text",text:s.text});continue}if(s.tokenKind!=="file")continue;const i=n.get(s.tokenKey);i&&r.push({type:"file",name:i.name,mimeType:i.mimeType,...i.attachmentUri?{attachmentUri:i.attachmentUri}:{},...i.url?{url:i.url}:{},...i.contentBase64?{contentBase64:i.contentBase64}:{},sizeBytes:i.sizeBytes})}return r}const jy={isProviderStateResolved:!1,composerNodes:Fr(),attachments:[],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:[]},V=Zt(e=>({snapshot:jy,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),Dy={sessionRunStatusByKey:new Map,isLocallyRunning:!1,activeBackendRunId:null},tr=Zt(e=>({snapshot:Dy,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))})),_y={sessions:[],selectedSessionKey:null,selectedAgentId:"main",query:"",isLoading:!1},ie=Zt(e=>({snapshot:_y,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function Oy(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),r=n-864e5,s=n-7*864e5,i=[],o=[],a=[],l=[];for(const c of e){const d=new Date(c.updatedAt).getTime();d>=n?i.push(c):d>=r?o.push(c):d>=s?a.push(c):l.push(c)}const u=[];return i.length>0&&u.push({label:I("chatSidebarToday"),sessions:i}),o.length>0&&u.push({label:I("chatSidebarYesterday"),sessions:o}),a.length>0&&u.push({label:I("chatSidebarPrevious7Days"),sessions:a}),l.length>0&&u.push({label:I("chatSidebarOlder"),sessions:l}),u}function Fy(e){if(e.label&&e.label.trim())return e.label.trim();const t=e.key.split(":");return t[t.length-1]||e.key}function zy(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(" ")}function By(e){var t;return e.ready===!1?((t=e.reasonMessage)==null?void 0:t.trim())||I("statusSetup"):I("statusReady")}const $y=[{target:"/cron",label:()=>I("chatSidebarScheduledTasks"),icon:hr},{target:"/skills",label:()=>I("chatSidebarSkills"),icon:cr}];function Ky(){var A,K;const e=mr(),t=zl(),n=en(),[r,s]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(""),[u,c]=k.useState(null),d=V(L=>L.snapshot),p=ie(L=>L.snapshot),f=tr(L=>L.snapshot),y=Bl(L=>L.connectionStatus),{language:m,setLanguage:b}=gr(),{theme:g,setTheme:v}=$l(),w=$u(),N=zi(n.search),j=I(((A=Br.find(L=>L.value===g))==null?void 0:A.labelKey)??"themeWarm"),T=((K=$r.find(L=>L.value===m))==null?void 0:K.label)??m,O=k.useMemo(()=>Oy(p.sessions),[p.sessions]),B=d.defaultSessionType||"native",$=k.useMemo(()=>d.sessionTypeOptions.filter(L=>L.value!==B),[B,d.sessionTypeOptions]),C=L=>{m!==L&&(b(L),window.location.reload())},R=(L,Q)=>{const{sessions:ae}=ie.getState().snapshot;ie.getState().setSnapshot({sessions:ae.map(x=>x.key===L?{...x,...Q?{label:Q}:{label:void 0}}:x)})},E=L=>{var Q;o(L.key),l(((Q=L.label)==null?void 0:Q.trim())??"")},z=()=>{o(null),l(""),c(null)},_=async L=>{var x;const Q=a.trim(),ae=((x=L.label)==null?void 0:x.trim())??"";if(Q===ae){z();return}c(L.key);try{await w({chatChain:N,sessionKey:L.key,label:Q||null}),R(L.key,Q||void 0),z()}catch{c(null)}};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(Kl,{className:"flex items-center gap-2.5 min-w-0",suffix:h.jsx(zu,{status:y})})}),h.jsx("div",{className:"px-4 pb-3",children:h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsxs(Ve,{variant:"primary",className:Le("min-w-0 rounded-xl",$.length>0?"flex-1 rounded-r-md":"w-full"),onClick:()=>{s(!1),e.chatSessionListManager.createSession(B)},children:[h.jsx(wl,{className:"h-4 w-4 mr-2"}),I("chatSidebarNewTask")]}),$.length>0?h.jsxs(Cu,{open:r,onOpenChange:s,children:[h.jsx(Tu,{asChild:!0,children:h.jsx(Ve,{variant:"primary",size:"icon",className:"h-9 w-10 shrink-0 rounded-xl rounded-l-md","aria-label":I("chatSessionTypeLabel"),children:h.jsx(ur,{className:"h-4 w-4"})})}),h.jsxs(Iu,{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:I("chatSessionTypeLabel")}),h.jsx("div",{className:"mt-1 space-y-1",children:$.map(L=>h.jsxs("button",{type:"button",onClick:()=>{e.chatSessionListManager.createSession(L.value),s(!1)},className:"w-full rounded-xl px-3 py-2 text-left transition-colors hover:bg-gray-100",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("div",{className:"text-[13px] font-medium text-gray-900",children:L.label}),h.jsx("span",{className:Le("shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold",L.ready===!1?"bg-amber-100 text-amber-800":"bg-emerald-100 text-emerald-700"),children:L.ready===!1?I("statusSetup"):I("statusReady")})]}),h.jsx("div",{className:"mt-0.5 text-[11px] text-gray-500",children:By(L)})]},L.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(pr,{value:p.query,onChange:L=>e.chatSessionListManager.setQuery(L.target.value),placeholder:I("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:$y.map(L=>h.jsx("li",{children:h.jsx(Kr,{to:L.target,label:L.label(),icon:L.icon,density:"compact"})},L.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:p.isLoading?h.jsx("div",{className:"text-xs text-gray-500 p-3",children:I("sessionsLoading")}):O.length===0?h.jsxs("div",{className:"p-4 text-center",children:[h.jsx(Cl,{className:"h-6 w-6 mx-auto mb-2 text-gray-300"}),h.jsx("div",{className:"text-xs text-gray-500",children:I("sessionsEmpty")})]}):h.jsx("div",{className:"space-y-3",children:O.map(L=>h.jsxs("div",{children:[h.jsx("div",{className:"px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider",children:L.label}),h.jsx("div",{className:"space-y-0.5",children:L.sessions.map(Q=>{const ae=p.selectedSessionKey===Q.key,x=f.sessionRunStatusByKey.get(Q.key),oe=zy(Q.sessionType,d.sessionTypeOptions),re=i===Q.key,S=u===Q.key;return h.jsx(Bu,{session:Q,active:ae,runStatus:x,sessionTypeLabel:oe,title:Fy(Q),isEditing:re,draftLabel:a,isSaving:S,onSelect:()=>e.chatSessionListManager.selectSession(Q.key),onStartEditing:()=>E(Q),onDraftLabelChange:l,onSave:()=>_(Q),onCancel:z},Q.key)})})]},L.label))})}),h.jsxs("div",{className:"px-3 py-3 border-t border-gray-200/60 space-y-0.5",children:[h.jsx(Kr,{to:"/settings",label:I("settings"),icon:Tl,density:"compact"}),h.jsx(Ul,{onClick:()=>t.open(void 0,{kind:"docs",newTab:!0,title:"Docs"}),icon:Il,label:I("docBrowserHelp"),density:"compact"}),h.jsx(Ur,{value:g,onValueChange:L=>v(L),icon:Ml,label:I("theme"),valueLabel:j,density:"compact",children:Br.map(L=>h.jsx(vt,{value:L.value,className:"text-xs",children:I(L.labelKey)},L.value))}),h.jsx(Ur,{value:m,onValueChange:L=>C(L),icon:Rl,label:I("language"),valueLabel:T,density:"compact",children:$r.map(L=>h.jsx(vt,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})}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||{}),Ws=/\[\[\s*reply_to_current\s*\]\]/gi,Qs=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function nr(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function Uy(e,t){var i;let n=e,r;Ws.test(n)&&(r=nr(t),n=n.replace(Ws,"").trim());const s=(i=n.match(Qs))==null?void 0:i[1];return s&&(r=nr(s),n=n.replace(Qs,"").trim()),r?{content:n,replyTo:r}:{content:n}}function Vy(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=nr(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:o,replyTo:a}=Uy(i.text,t),l=a??s,u=e.parts.flatMap((c,d)=>d!==n||c.type!=="text"?[c]:o.length===0?[]:[{...c,text:o}]);return l?{...e,parts:u,metadata:{...r,reply_to:l}}:{...e,parts:u,metadata:r}}function Ht(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function En(e){return Ht(Vy(e))}function Hy(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 qy(e,t){return t.trim()?e.id.startsWith("tool-")?!0:e.parts.some(n=>n.type==="tool-invocation"):!1}function Wy(e,t,n){for(const[r,s]of e)s===t&&e.set(r,n)}function Ln(e,t,n){for(const[r,s]of e)s===n&&(e.delete(r),t.delete(r))}function rr(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 Gs(e,t){const n=rr(e,t);return(n==null?void 0:n.toolName)??null}function St(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 Qy="assistant",Gy=class{constructor(){F(this,"messages",[]);F(this,"streamingMessage",null);F(this,"error",null);F(this,"activeRun",null);F(this,"listeners",new Set);F(this,"toolCallMessageIdByCallId",new Map);F(this,"toolCallArgsRawByCallId",new Map);F(this,"snapshotCache",null);F(this,"snapshotVersion",-1);F(this,"stateVersion",0)}getSnapshot(){if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;const e={messages:this.messages.map(t=>Ht(t)),streamingMessage:this.streamingMessage?Ht(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=>En(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?Ln(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):Ln(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=St(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=St(t.parts,{type:"tool-invocation",toolCallId:e.toolCallId,toolName:Gs(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 St(n.parts,s)})){const n=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),r=St(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){this.settleStreamingMessage("final"),this.setError(null),this.clearActiveRun()}handleRunError(e){this.settleStreamingMessage("error"),this.setError(Hy(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){var t,n,r;if(e.code==="abort-error"){this.handleMessageAbort({sessionId:((t=this.activeRun)==null?void 0:t.sessionId)??((n=this.streamingMessage)==null?void 0:n.sessionId)??"",...(r=this.streamingMessage)!=null&&r.id?{messageId:this.streamingMessage.id}:{}});return}this.settleStreamingMessage("error"),this.clearActiveRun(),this.setError(e)}applyToolCallArgs(e,t,n,r){const s=this.resolveToolCallTargetMessage(e,t,r),i=Gs(s.parts,t)??"unknown",o=St(s.parts,{type:"tool-invocation",toolCallId:t,toolName:i,state:"partial-call",args:n});this.replaceStreamingMessage({...s,parts:o,status:"streaming"})}ensureStreamingMessage(e,t,n){var o;if(((o=this.streamingMessage)==null?void 0:o.id)===t){if(this.streamingMessage.status===n)return this.streamingMessage;const a={...this.streamingMessage,status:n};return this.replaceStreamingMessage(a),a}const r=this.messages.findIndex(a=>a.id===t);if(r>=0){const a=Ht(this.messages[r]),l=[...this.messages];l.splice(r,1),this.messages=l,this.stateVersion+=1;const u={...a,sessionId:e,status:n};return this.replaceStreamingMessage(u),u}const s=this.streamingMessage;if(s&&s.id!==t&&s.sessionId===e&&qy(s,t)){const a={...s,id:t,sessionId:e,status:n};return Wy(this.toolCallMessageIdByCallId,s.id,t),this.replaceStreamingMessage(a),a}const i={id:t,sessionId:e,role:Qy,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=rr(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=rr(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=En(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?En(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)}settleStreamingMessage(e){if(!this.streamingMessage)return;const t={...this.streamingMessage,status:e};this.upsertMessage(t),this.replaceStreamingMessage(null),Ln(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)}notifyListeners(){const e=this.getSnapshot();for(const t of this.listeners)t(e)}};function Xy(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 Yy(e){return e.parts.some(t=>t.type==="text"||t.type==="rich-text"||t.type==="reasoning"?t.text.trim().length>0:!0)}function Jy(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 Yy(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function Zy(e){const t=k.useRef();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new Gy}),t.current.manager}function ex({sessionId:e,client:t,manager:n}){var p;const r=k.useSyncExternalStore(f=>n.subscribe(()=>f()),()=>n.getSnapshot(),()=>n.getSnapshot()),[s,i]=k.useState(!1);k.useEffect(()=>{i(!1)},[e]),k.useEffect(()=>{const f=t.subscribe(y=>{Xy(y,e)&&n.dispatch(y)});return()=>{f(),t.stop()}},[t,n,e]);const o=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,a=((p=r.activeRun)==null?void 0:p.runId)??null,l=!!r.activeRun;return{snapshot:r,visibleMessages:o,activeRunId:a,isRunning:l,isSending:s,send:async f=>{if(s||l)return;const y=Jy(f,e);if(y){i(!0),await n.dispatch({type:ne.MessageSent,payload:{sessionId:e,message:y.message,metadata:y.metadata}});try{await t.send(y)}finally{i(!1)}}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{r.activeRun&&await t.stream({sessionId:e})}}}function Xs(e){return e instanceof Error?e:new Error(String(e))}function tx({sessionId:e,client:t,loadSeed:n,autoResumeRunningSession:r=!0}){const s=Zy(e),i=ex({sessionId:e,client:t,manager:s}),[o,a]=k.useState(!0),[l,u]=k.useState(null),c=k.useRef({requestId:0,controller:null}),d=k.useCallback(async()=>{var y;(y=c.current.controller)==null||y.abort();const p=new AbortController,f=c.current.requestId+1;c.current={requestId:f,controller:p},await t.stop(),s.reset(),u(null),a(!0);try{const m=await n(e,p.signal);if(p.signal.aborted||c.current.requestId!==f)return;s.hydrate({sessionId:e,messages:m.messages,activeRun:m.status==="running"?{runId:null,sessionId:e,abortDisabledReason:null}:null}),u(null),a(!1),m.status==="running"&&r&&t.stream({sessionId:e}).catch(b=>{c.current.requestId===f&&u(Xs(b))})}catch(m){if(p.signal.aborted||c.current.requestId!==f)return;u(Xs(m)),a(!1)}finally{c.current.controller===p&&(c.current.controller=null)}},[r,t,n,s,e]);return k.useEffect(()=>(d(),()=>{var p;(p=c.current.controller)==null||p.abort(),c.current.controller=null}),[d]),{...i,isHydrating:o,hydrateError:l,reloadSeed:d}}var ka=10*1024*1024,nx="application/octet-stream";function va(e){const t=e.type.trim().toLowerCase();return t.length>0?t:nx}function rx(e,t){const n=t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0?new Set(t.acceptedMimeTypes.map(i=>i.trim().toLowerCase())):null,r=t.maxBytes??ka,s=va(e);return n&&!n.has(s)?{ok:!1,rejected:{fileName:e.name,mimeType:s,sizeBytes:e.size,reason:"unsupported-type"}}:e.size>r?{ok:!1,rejected:{fileName:e.name,mimeType:s,sizeBytes:e.size,reason:"too-large"}}:{ok:!0,mimeType:s}}function sx(e){var s;const t=e.parts&&e.parts.length>0?e.parts.map(i=>structuredClone(i)):[...((s=e.text)==null?void 0:s.trim())??""?[{type:"text",text:e.text.trim()}]:[],...(e.attachments??[]).map(i=>{var o,a,l;return{type:"file",name:i.name,mimeType:i.mimeType,...(o=i.attachmentUri)!=null&&o.trim()?{attachmentUri:i.attachmentUri.trim()}:{},...(a=i.url)!=null&&a.trim()?{url:i.url.trim()}:{},...(l=i.contentBase64)!=null&&l.trim()?{contentBase64:i.contentBase64.trim()}:{},sizeBytes:i.sizeBytes}})];if(t.length===0)return null;const n=e.timestamp??new Date().toISOString(),r=e.messageId??`user-${Date.now().toString(36)}`;return{sessionId:e.sessionId,message:{id:r,sessionId:e.sessionId,role:"user",status:"final",parts:t,timestamp:n,...e.metadata?{metadata:e.metadata}:{}},...e.metadata?{metadata:e.metadata}:{}}}async function ix(e,t){const n=[],r=[];for(const s of e){const i=rx(s,t);if(!i.ok){r.push(i.rejected);continue}n.push(s)}if(n.length===0)return{attachments:[],rejected:r};try{return{attachments:await t.uploadBatch(n),rejected:r}}catch{return r.push(...n.map(s=>({fileName:s.name,mimeType:va(s),sizeBytes:s.size,reason:"read-failed"}))),{attachments:[],rejected:r}}}function ox(e,t){if(!e||typeof e!="object"||Array.isArray(e))return t;const n=e.error;if(!n||typeof n!="object"||Array.isArray(n))return t;const r=n.message;return typeof r=="string"&&r.trim().length>0?r:t}async function ax(e){const t=new FormData;for(const s of e)t.append("files",s);const n=await fetch(`${Li}/api/ncp/attachments`,{method:"POST",body:t,credentials:"include"}),r=await n.json();if(!n.ok||!r.ok)throw new Error(ox(r,"Failed to upload attachments."));return r.data.attachments.map(s=>({id:s.id,name:s.name,mimeType:s.mimeType,sizeBytes:s.sizeBytes,attachmentUri:s.attachmentUri,url:s.url}))}const De={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function Bt(e){return(e??"").trim().toLowerCase()}function Ys(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 lx(e,t){const n=Bt(t);if(!n)return De.fallback;const r=Bt(e.key),s=Bt(e.label||e.key),i=Bt(`${e.descriptionZh??""} ${e.description??""}`),o=s.split(/[\s/_-]+/).filter(Boolean);return r===n?De.exactSpec:s===n?De.exactLabel:r.startsWith(n)?De.prefixSpec:s.startsWith(n)?De.prefixLabel:o.some(a=>a.startsWith(n))?De.prefixToken:r.includes(n)?De.containsSpec:s.includes(n)?De.containsLabel:i.includes(n)?De.containsDescription:Ys(n,s)||Ys(n,r)?De.subsequence:0}function ux(e,t,n){const r=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0});return e.map((s,i)=>({record:s,order:i,score:lx(s,t)})).filter(s=>s.score>0).sort((s,i)=>{if(i.score!==s.score)return i.score-s.score;const o=(s.record.label||s.record.key).trim(),a=(i.record.label||i.record.key).trim(),l=r.compare(o,a);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 cx(e){return e.map(t=>({key:t.key,label:t.label,description:t.descriptionZh||t.description||"",badgeLabel:t.badgeLabel}))}function dx(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:cx(e.skillRecords),selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}function hx(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 fx(e){const t=e.modelOptions.find(i=>i.value===e.selectedModel),n=e.modelOptions[0],r=t??n;return{key:"model",value:e.hasModelOptions?r==null?void 0:r.value:void 0,placeholder:e.texts.modelSelectPlaceholder,selectedLabel:r?`${r.providerLabel}/${r.modelLabel}`:void 0,icon:"sparkles",options:e.modelOptions.map(i=>({value:i.value,label:i.modelLabel,description:i.providerLabel})),disabled:!e.hasModelOptions,loading:e.isModelOptionsLoading,emptyLabel:e.texts.modelNoOptionsLabel,onValueChange:e.onValueChange}}function px(e){const t=[];for(const n of["off",...e])t.includes(n)||t.push(n);return t}function gx(e){if(e.supportedLevels.length===0)return null;const t=px(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 mx(){return{off:I("chatThinkingLevelOff"),minimal:I("chatThinkingLevelMinimal"),low:I("chatThinkingLevelLow"),medium:I("chatThinkingLevelMedium"),high:I("chatThinkingLevelHigh"),adaptive:I("chatThinkingLevelAdaptive"),xhigh:I("chatThinkingLevelXhigh")}}function yx(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 xx(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 bx(){var C;const e=mr(),{language:t}=gr(),n=V(R=>R.snapshot),[r,s]=k.useState(null),i=k.useRef(null),o=k.useRef(null),a=k.useMemo(()=>I("chatSkillsPickerOfficial"),[t]),l=k.useMemo(()=>({slashSkillSubtitle:I("chatSlashTypeSkill"),slashSkillSpecLabel:I("chatSlashSkillSpec"),noSkillDescription:I("chatSkillsPickerNoDescription")}),[t]),u=k.useMemo(()=>yx(n.skillRecords,a),[n.skillRecords,a]),c=k.useMemo(()=>xx(n.modelOptions),[n.modelOptions]),d=c.length>0,p=!n.isProviderStateResolved&&!d,f=n.isProviderStateResolved&&!d,y=(p||f)&&!n.isSending||n.sessionTypeUnavailable,m=typeof e.chatInputManager.addAttachments=="function",b=p?"":d?I("chatInputPlaceholder"):I("chatModelNoOptions"),g=k.useMemo(()=>ux(u,r??"",l),[r,u,l]),v=c.find(R=>R.value===n.selectedModel),w=v==null?void 0:v.thinkingCapability,N=(w==null?void 0:w.supported)??[],j=n.stopDisabledReason==="__preparing__"?I("chatStopPreparing"):((C=n.stopDisabledReason)==null?void 0:C.trim())||I("chatStopUnavailable"),T=k.useCallback(R=>{if(R==="unsupported-type"){kt.error(I("chatInputAttachmentUnsupported"));return}if(R==="too-large"){kt.error(I("chatInputAttachmentTooLarge").replace("{maxMb}",String(ka/(1024*1024))));return}kt.error(I("chatInputAttachmentReadFailed"))},[]),O=k.useCallback(async R=>{var z,_,A;if(!m||R.length===0)return;const E=await ix(R,{uploadBatch:ax});if(E.attachments.length>0){const K=((_=(z=e.chatInputManager).addAttachments)==null?void 0:_.call(z,E.attachments))??[];K.length>0&&((A=i.current)==null||A.insertFileTokens(K.map(L=>({tokenKey:L.id,label:L.name}))))}E.rejected.length>0&&T(E.rejected[0].reason)},[m,e.chatInputManager,T]),B=[fx({modelOptions:c,selectedModel:n.selectedModel,isModelOptionsLoading:p,hasModelOptions:d,onValueChange:e.chatInputManager.selectModel,texts:{modelSelectPlaceholder:I("chatSelectModel"),modelNoOptionsLabel:I("chatModelNoOptions")}}),gx({supportedLevels:N,selectedThinkingLevel:n.selectedThinkingLevel,defaultThinkingLevel:(w==null?void 0:w.default)??null,onValueChange:R=>e.chatInputManager.selectThinkingLevel(R),texts:{thinkingLabels:mx()}})].filter(R=>R!==null),$=dx({skillRecords:u,selectedSkills:n.selectedSkills,isLoading:n.isSkillsLoading,onSelectedKeysChange:e.chatInputManager.selectSkills,texts:{title:I("chatSkillsPickerTitle"),searchPlaceholder:I("chatSkillsPickerSearchPlaceholder"),emptyLabel:I("chatSkillsPickerEmpty"),loadingLabel:I("sessionsLoading"),manageLabel:I("chatSkillsPickerManage")}});return h.jsxs(h.Fragment,{children:[h.jsx(fo,{ref:i,composer:{nodes:n.composerNodes,placeholder:b,disabled:y,onNodesChange:e.chatInputManager.setComposerNodes,...m?{onFilesAdd:O}:{},onSlashQueryChange:s},slashMenu:{isLoading:n.isSkillsLoading,items:g,texts:{slashLoadingLabel:I("chatSlashLoading"),slashSectionLabel:I("chatSlashSectionSkills"),slashEmptyLabel:I("chatSlashNoResult"),slashHintLabel:I("chatSlashHint"),slashSkillHintLabel:I("chatSlashSkillHint")}},hint:hx({isModelOptionsLoading:p,isModelOptionsEmpty:f,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:I("chatModelNoOptions"),configureProviderLabel:I("chatGoConfigureProvider")}}),toolbar:{selects:B,accessories:[{key:"attach",label:I("chatInputAttach"),icon:"paperclip",iconOnly:!0,disabled:!m||y||n.isSending,...m?{onClick:()=>{var R;return(R=o.current)==null?void 0:R.click()}}:{tooltip:I("chatInputAttachComingSoon")}}],skillPicker:$,actions:{sendError:n.sendError,isSending:n.isSending,canStopGeneration:n.canStopGeneration,sendDisabled:n.draft.trim().length===0&&n.attachments.length===0||!d||n.sessionTypeUnavailable,stopDisabled:!n.canStopGeneration,stopHint:j,sendButtonLabel:I("chatSend"),stopButtonLabel:I("chatStop"),onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}}),m?h.jsx("input",{ref:o,type:"file",multiple:!0,className:"hidden",onChange:async R=>{const E=Array.from(R.target.files??[]);R.currentTarget.value="",await O(E)}}):null]})}function qe(e){return typeof e=="function"}function wa(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 Nn=wa(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
36
36
|
`+n.map(function(r,s){return s+1+") "+r.toString()}).join(`
|
|
37
|
-
`):"",this.name="UnsubscriptionError",this.errors=n}});function sr(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 o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=On(o),l=a.next();!l.done;l=a.next()){var u=l.value;u.remove(this)}}catch(m){t={error:m}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var c=this.initialTeardown;if(qe(c))try{c()}catch(m){i=m instanceof Nn?m.errors:[m]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var p=On(d),f=p.next();!f.done;f=p.next()){var y=f.value;try{Js(y)}catch(m){i=i??[],m instanceof Nn?i=Fn(Fn([],zn(i)),zn(m.errors)):i.push(m)}}}catch(m){r={error:m}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}if(i)throw new Nn(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Js(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)&&sr(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&sr(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),va=un.EMPTY;function wa(e){return e instanceof un||e&&"closed"in e&&qe(e.remove)&&qe(e.add)&&qe(e.unsubscribe)}function Js(e){qe(e)?e():e.unsubscribe()}var Sx={Promise:void 0},kx={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Fn([e,t],zn(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function vx(e){kx.setTimeout(function(){throw e})}function Zs(){}function qt(e){e()}var Ca=(function(e){At(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,wa(n)&&n.add(r)):r.destination=Tx,r}return t.create=function(n,r,s){return new ir(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),wx=(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){$t(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){$t(r)}else $t(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){$t(n)}},e})(),ir=(function(e){At(t,e);function t(n,r,s){var i=e.call(this)||this,o;return qe(n)||!n?o={next:n??void 0,error:r??void 0,complete:s??void 0}:o=n,i.destination=new wx(o),i}return t})(Ca);function $t(e){vx(e)}function Cx(e){throw e}var Tx={closed:!0,next:Zs,error:Cx,complete:Zs},Ix=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Mx(e){return e}function Rx(e){return e.length===0?Mx:e.length===1?e[0]:function(n){return e.reduce(function(r,s){return s(r)},n)}}var Yt=(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=Ex(t)?t:new ir(t,n,r);return qt(function(){var o=s,a=o.operator,l=o.source;i.add(a?a.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=ei(n),new n(function(s,i){var o=new ir({next:function(a){try{t(a)}catch(l){i(l),o.unsubscribe()}},error:i,complete:s});r.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Ix]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Rx(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=ei(t),new t(function(r,s){var i;n.subscribe(function(o){return i=o},function(o){return s(o)},function(){return r(i)})})},e.create=function(t){return new e(t)},e})();function ei(e){var t;return(t=e??Sx.Promise)!==null&&t!==void 0?t:Promise}function Ax(e){return e&&qe(e.next)&&qe(e.error)&&qe(e.complete)}function Ex(e){return e&&e instanceof Ca||Ax(e)&&wa(e)}var Lx=ka(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ue=(function(e){At(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 ti(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new Lx},t.prototype.next=function(n){var r=this;qt(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=On(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(n)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(n){var r=this;qt(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;qt(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,o=s.isStopped,a=s.observers;return i||o?va:(this.currentObservers=null,a.push(n),new un(function(){r.currentObservers=null,sr(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,s=r.hasError,i=r.thrownError,o=r.isStopped;s?n.error(i):o&&n.complete()},t.prototype.asObservable=function(){var n=new Yt;return n.source=this,n},t.create=function(n,r){return new ti(n,r)},t})(Yt),ti=(function(e){At(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:va},t})(Ue),it=(function(e){At(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})(Ue);const fe=[];for(let e=0;e<256;++e)fe.push((e+256).toString(16).slice(1));function Nx(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 Pn;const Px=new Uint8Array(16);function jx(){if(!Pn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pn=crypto.getRandomValues.bind(crypto)}return Pn(Px)}const Dx=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ni={randomUUID:Dx};function or(e,t,n){var s;if(ni.randomUUID&&!e)return ni.randomUUID();e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??jx();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,Nx(r)}var ue=(e=>(e.CALL="call",e.RESULT="result",e.PARTIAL_CALL="partial-call",e.ERROR="error",e.CANCELLED="cancelled",e))(ue||{}),X=(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))(X||{});function _x(e){return!e||e.remoteStopCapable&&e.remoteRunId?null:e.remoteStopCapable?"__preparing__":e.remoteStopReason??""}const Ox=e=>{try{return JSON.parse(e)}catch{return}},ri=e=>({toolCallId:e.id,toolName:e.function.name,args:e.function.arguments,parsedArgs:Ox(e.function.arguments),status:ue.CALL});function Fx(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"||![ue.CALL,ue.PARTIAL_CALL].includes(i.toolInvocation.status))return i;let o;if(typeof i.toolInvocation.args=="string")try{o=JSON.parse(i.toolInvocation.args)}catch{return{...i,toolInvocation:{...i.toolInvocation,args:JSON.stringify({}),parsedArgs:o,status:ue.RESULT,result:{error:"invalid_args",raw:i.toolInvocation.args}}}}return{...i,toolInvocation:{...i.toolInvocation,args:i.toolInvocation.args,parsedArgs:o,status:ue.RESULT,result:n}}})}:r})}function ar(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 si(e){if(e instanceof Error){const n=e.message.trim();if(n)return n}return String(e??"").trim()||"Failed to send message"}function ii(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 zx{constructor(t){F(this,"currentMessageId");F(this,"currentReasoningMessageId");F(this,"currentReasoningContent","");F(this,"currentToolCallId");F(this,"currentToolCallMessageId");F(this,"currentToolCallName");F(this,"currentToolCallArgs","");F(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(a=>a.type==="tool-invocation"&&a.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===ue.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 X.RUN_STARTED:break;case X.TEXT_START:this.handleTextStart(t);break;case X.TEXT_DELTA:this.handleTextContent(t);break;case X.TEXT_END:this.handleTextEnd();break;case X.REASONING_START:this.handleReasoningStart(t);break;case X.REASONING_DELTA:this.handleReasoningContent(t);break;case X.REASONING_END:this.handleReasoningEnd();break;case X.TOOL_CALL_START:this.handleToolCallStart(t);break;case X.TOOL_CALL_ARGS_DELTA:this.handleToolCallArgsDelta(t);break;case X.TOOL_CALL_ARGS:this.handleToolCallArgs(t);break;case X.TOOL_CALL_END:this.handleToolCallEnd(),this.emitToolCallEvents();break;case X.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 o=r.length-1;o>=0;o-=1)if(((i=r[o])==null?void 0:i.type)==="reasoning"){s=o;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(o=>o.role==="assistant"&&o.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:ue.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 o=this.findAssistantMessageByToolCallId(this.currentToolCallId);if(o){this.currentToolCallMessageId=o.id;const u=o.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 a=r[r.length-1];if(a&&a.role==="assistant")this.currentToolCallMessageId=a.id,this.sessionManager.updateMessage({...a,parts:[...a.parts||[],n]});else{const u=or();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 o=r[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===t.toolCallId){let a;try{a=JSON.parse(this.currentToolCallArgs)}catch{}r[i]={...o,toolInvocation:{...o.toolInvocation,status:ue.PARTIAL_CALL,args:this.currentToolCallArgs,parsedArgs:a}};break}}this.sessionManager.updateMessage({...n,parts:r})}handleToolCallArgs(t){this.currentToolCallId===t.toolCallId&&(this.currentToolCallArgs=t.args,this.handleToolCallArgsDelta({type:X.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 o=s[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===this.currentToolCallId){s[i]={...o,toolInvocation:{...ri(n),status:ue.CALL}};break}}this.sessionManager.updateMessage({...r,parts:s})}else{const s=((t=this.currentToolCallMessageId)==null?void 0:t.trim())||or();this.sessionManager.addMessages([{id:s,role:"assistant",parts:[{type:"tool-invocation",toolInvocation:{...ri(n),status:ue.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:ue.RESULT})}}class Bx{constructor(){F(this,"disposables",[]);F(this,"addDisposable",t=>{this.disposables.push(t)});F(this,"dispose",()=>{this.disposables.forEach(t=>t()),this.disposables=[]})}}class $x extends Bx{constructor(n=null,r){super();F(this,"_messages$",new it([]));F(this,"messages$");F(this,"threadId$",new it(null));F(this,"isAgentResponding$",new it(!1));F(this,"activeRun$",new it(null));F(this,"lastError$",new it(null));F(this,"isAwaitingResponse$",new it(!1));F(this,"runCompleted$",new Ue);F(this,"runError$",new Ue);F(this,"runMetadata$",new Ue);F(this,"activeSubscription",null);F(this,"addMessagesEvent$",new Ue);F(this,"updateMessageEvent$",new Ue);F(this,"setMessagesEvent$",new Ue);F(this,"toolCall$",new Ue);F(this,"eventHandler",new zx(this));F(this,"runIdCounter",0);F(this,"metadataParsers");F(this,"callbacks");F(this,"getMessages",()=>this._messages$.getValue());F(this,"setMessages",n=>{this._messages$.next(n),this.setMessagesEvent$.next({messages:n})});F(this,"handleEvent",n=>{this.eventHandler.handleEvent(n)});F(this,"setCallbacks",n=>{this.callbacks=n});F(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});F(this,"addMessages",n=>{const s=[...this.getMessages()];for(const i of n){const o=s.findIndex(a=>a.id===i.id);o>=0?s[o]=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)});F(this,"removeMessages",n=>{n.length!==0&&this._messages$.next(this.getMessages().filter(r=>!n.includes(r.id)))});F(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)});F(this,"addToolResult",(n,r)=>{const s=this.getMessages().find(o=>o.parts.find(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===n.toolCallId));if(!s)return;const i={...s,parts:s.parts.map(o=>o.type==="tool-invocation"&&o.toolInvocation.toolCallId===n.toolCallId?{...o,toolInvocation:{...o.toolInvocation,result:n.result??void 0,status:n.status,error:n.error??void 0,cancelled:n.cancelled??void 0}}:o)};this.updateMessage(i)});F(this,"send",async n=>{(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun(),this.lastError$.next(null);const r=n.message.trim();r&&(this.addMessages([{id:or(),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}))});F(this,"resume",async n=>{var o,a;const r=(o=n.remoteRunId)==null?void 0:o.trim(),s=(a=n.sessionId)==null?void 0:a.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})))});F(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}))});F(this,"handleAgentResponse",n=>{this.activeSubscription&&this.activeSubscription.unsubscribe(),this.activeSubscription=n.subscribe(r=>{var s,i,o,a,l,u,c,d,p;if(r.type===X.RUN_METADATA){const f=r,y=this.activeRun$.getValue(),m=((s=f.runId)==null?void 0:s.trim())||(y?`ui-${y.localRunId}`:"");this.metadataParsers&&y&&this.isMatchingRun(y,m)&&this.processRunMetadata(y,f.metadata),this.runMetadata$.next({runId:m,metadata:f.metadata});return}if(this.handleEvent(r),r.type===X.RUN_FINISHED){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),y=((i=r.runId)==null?void 0:i.trim())||(f?`ui-${f.localRunId}`:"");if(!f||!this.isMatchingRun(f,y))return;const m=f.sessionId;this.activeRun$.next(null),m&&((a=(o=this.callbacks).onRunSettled)==null||a.call(o,{sourceSessionId:m}))}else if(r.type===X.RUN_ERROR){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),y=((l=r.runId)==null?void 0:l.trim())||(f?`ui-${f.localRunId}`:""),m=ar(r.error);if(this.runError$.next({runId:y,error:r.error,isAbort:m}),!f||!this.isMatchingRun(f,y)){this.activeRun$.next(null);return}const b=f.sessionId;if(m){this.activeRun$.next(null),b&&((c=(u=this.callbacks).onRunSettled)==null||c.call(u,{sourceSessionId:b}));return}const g=si(r.error);this.lastError$.next(g),this.activeRun$.next(null),b&&this.addMessages([ii(g,{sessionKey:b,status:"error"})]),(p=(d=this.callbacks).onRunError)==null||p.call(d,{error:g,sourceMessage:f.sourceMessage,restoreDraft:f.restoreDraftOnError})}})});F(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)});F(this,"runAgent",async n=>{var o,a,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=Fx(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=ar(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=si(c);this.lastError$.next(f),p.sessionId&&this.addMessages([ii(f,{sessionKey:p.sessionId,status:"error"})]),(a=(o=this.callbacks).onRunError)==null||a.call(o,{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}))}});F(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)});F(this,"applyReadyMetadata",(n,r)=>{var i,o,a,l,u;const s={...n};(i=r.remoteRunId)!=null&&i.trim()&&(s.remoteRunId=r.remoteRunId.trim()),typeof r.stopCapable=="boolean"&&(s.remoteStopCapable=r.stopCapable),(o=r.stopReason)!=null&&o.trim()&&(s.remoteStopReason=r.stopReason.trim()),(a=r.sessionId)!=null&&a.trim()&&(s.sessionId=r.sessionId.trim(),(u=(l=this.callbacks).onSessionChanged)==null||u.call(l,s.sessionId)),this.activeRun$.next(s)});F(this,"applyFinalMetadata",(n,r)=>{var o,a,l,u;const s=n.sessionId,i=r.sessionId;i&&i!==s&&((a=(o=this.callbacks).onSessionChanged)==null||a.call(o,i)),this.activeRun$.next(null),s&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:s,resultSessionId:i}))});F(this,"isMatchingRun",(n,r)=>r.trim()?r===`ui-${n.localRunId}`:!1);F(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 o=JSON.parse(r.function.arguments),a=await s(o);this.addToolResult({toolCallId:r.id,result:a,status:ue.RESULT}),this.runAgent()}catch(o){console.error("[AgentChatController] handleAddToolResult error",o),this.addToolResult({toolCallId:r.id,error:o instanceof Error?o.message:String(o),status:ue.ERROR}),this.runAgent()}});return()=>n.unsubscribe()});this.agentProvider=n;const{initialMessages:s=[],metadataParsers:i,callbacks:o={}}=r||{};this.metadataParsers=i??null,this.callbacks=o,this._messages$.next(s),this.messages$=this._messages$.asObservable(),this.agentProvider&&this.addDisposable(this.connectToolExecutor())}}const Kx=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Ux(e){return typeof e=="object"&&e!==null}function Vx(e){return e.type==="text"&&typeof e.text=="string"}function Hx(e){return e.type==="reasoning"&&typeof e.reasoning=="string"}function qx(e){return e.type==="file"&&typeof e.mimeType=="string"&&typeof e.data=="string"}function Wx(e){return e.type!=="tool-invocation"||!Ux(e.toolInvocation)?!1:typeof e.toolInvocation.toolName=="string"}function Gx(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 Qx(e,t){return e==="user"?t.user:e==="assistant"?t.assistant:e==="tool"?t.tool:e==="system"?t.system:t.fallback}function Xx(e){return e==="user"||e==="assistant"||e==="tool"||e==="system"?e:"message"}function Yx(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 oi(e){const t=e.trim();return t&&t.replace(Kx,"").trim()?t:null}function Jx(e){return e.uiMessages.map(t=>{var n;return{id:t.id,role:Xx(t.role),roleLabel:Qx(t.role,e.texts.roleLabels),timestampLabel:e.formatTimestamp(Gx(t)),status:(n=t.meta)==null?void 0:n.status,parts:t.parts.map(r=>{if(Vx(r)){const s=oi(r.text);return s?{type:"markdown",text:s}:null}if(Hx(r)){const s=oi(r.reasoning);return s?{type:"reasoning",text:s,label:e.texts.reasoningLabel}:null}if(qx(r)){const s=r.mimeType.startsWith("image/");return{type:"file",file:{label:typeof r.name=="string"&&r.name.trim()?r.name.trim():s?e.texts.imageAttachmentLabel:e.texts.fileAttachmentLabel,mimeType:r.mimeType,dataUrl:`data:${r.mimeType};base64,${r.data}`,isImage:s}}}if(Wx(r)){const s=r.toolInvocation,i=uu(s.parsedArgs??s.args),o=typeof s.error=="string"&&s.error.trim()?s.error.trim():s.result!=null?Vr(s.result).trim():"",a=s.status==="result"||s.status==="error"||s.status==="cancelled",l={kind:a?"result":"call",name:s.toolName,detail:i,text:o||void 0,callId:s.toolCallId||void 0,hasResult:a};return{type:"tool-card",card:Yx(l,e.texts)}}return{type:"unknown",label:e.texts.unknownPartLabel,rawType:typeof r.type=="string"?r.type:"unknown",text:Vr(r)}}).filter(r=>r!==null)}})}function Zx(e){const{language:t}=gr(),n=k.useMemo(()=>e.uiMessages.map(s=>{var i,o;return{id:s.id,role:s.role,meta:{timestamp:(i=s.meta)==null?void 0:i.timestamp,status:(o=s.meta)==null?void 0:o.status},parts:s.parts}}),[e.uiMessages]),r=k.useMemo(()=>Jx({uiMessages:n,formatTimestamp:s=>tn(s,t),texts:{roleLabels:{user:I("chatRoleUser"),assistant:I("chatRoleAssistant"),tool:I("chatRoleTool"),system:I("chatRoleSystem"),fallback:I("chatRoleMessage")},reasoningLabel:I("chatReasoning"),toolCallLabel:I("chatToolCall"),toolResultLabel:I("chatToolResult"),toolNoOutputLabel:I("chatToolNoOutput"),toolOutputLabel:I("chatToolOutput"),imageAttachmentLabel:I("chatImageAttachment"),fileAttachmentLabel:I("chatFileAttachment"),unknownPartLabel:I("chatUnknownPart")}}),[t,n]);return h.jsx(My,{messages:r,isSending:e.isSending,hasAssistantDraft:e.uiMessages.some(s=>{var i,o;return s.role==="assistant"&&(((i=s.meta)==null?void 0:i.status)==="streaming"||((o=s.meta)==null?void 0:o.status)==="pending")}),className:e.className,texts:{copyCodeLabel:I("chatCodeCopy"),copiedCodeLabel:I("chatCodeCopied"),typingLabel:I("chatTyping")}})}const eb=[{icon:Ml,titleKey:"chatWelcomeCapability1Title",descKey:"chatWelcomeCapability1Desc"},{icon:cr,titleKey:"chatWelcomeCapability2Title",descKey:"chatWelcomeCapability2Desc"},{icon:hr,titleKey:"chatWelcomeCapability3Title",descKey:"chatWelcomeCapability3Desc"}];function tb({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(wi,{className:"h-8 w-8 text-primary"})}),h.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:I("chatWelcomeTitle")}),h.jsx("p",{className:"text-sm text-gray-500 mb-8",children:I("chatWelcomeSubtitle")}),h.jsx("div",{className:"grid grid-cols-3 gap-3",children:eb.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:I(t.titleKey)}),h.jsx("div",{className:"text-[11px] text-gray-500 leading-relaxed",children:I(t.descKey)})]},t.titleKey)})})]})})}const nb={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},He=Zt(e=>({snapshot:nb,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function rb(){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 sb(){var d;const e=mr(),t=He(p=>p.snapshot),n=k.useRef(null),r=t.threadRef??n,s=!!(t.selectedSessionKey||t.sessionTypeLabel),i=t.sessionDisplayName||t.selectedSessionKey||I("chatSidebarNewTask"),o=!t.selectedSessionKey&&t.uiMessages.length===0&&!t.isSending,a=t.modelOptions.length>0,l=t.isProviderStateResolved&&!a,u=t.isHistoryLoading&&t.uiMessages.length===0&&!t.isSending&&!t.isAwaitingAssistantOutput,{onScroll:c}=Ay({scrollRef:r,resetKey:t.selectedSessionKey,isLoading:t.isHistoryLoading,hasContent:t.uiMessages.length>0,contentVersion:t.uiMessages});return t.isProviderStateResolved?h.jsxs("section",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white",children:[h.jsxs("div",{className:Le("px-5 border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200",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(Ve,{variant:"ghost",size:"icon",className:"rounded-lg shrink-0 text-gray-400 hover:text-destructive",onClick:e.chatThreadManager.deleteSession,disabled:!t.canDeleteSession||t.isDeletePending,children:h.jsx(Ti,{className:"h-4 w-4"})}):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:I("chatModelNoOptions")}),h.jsx("button",{type:"button",onClick:e.chatThreadManager.goToProviders,className:"text-xs font-semibold text-amber-900 underline-offset-2 hover:underline",children:I("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:o?h.jsx(tb,{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:I("chatNoMessages")}):h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Zx,{uiMessages:t.uiMessages,isSending:t.isSending&&t.isAwaitingAssistantOutput})})}),h.jsx(bx,{})]}):h.jsx(rb,{})}function ai(e){return tn(e??void 0)}function ib(e){return typeof e!="number"||!Number.isFinite(e)?"-":tn(new Date(e))}function ob(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 ab(e){const t=e.schedule;return t.kind==="cron"?t.expr?`cron ${t.expr}`:"cron":t.kind==="every"?`every ${ob(t.everyMs)}`:t.kind==="at"?`at ${ib(t.atMs)}`:"-"}function lb(e){if(!e.payload.deliver)return"-";const t=e.payload.channel??"-",n=e.payload.to??"-";return`${t}:${n}`}function ub(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 cb(e,t){return t==="all"?!0:t==="enabled"?e.enabled:!e.enabled}function db(){var y;const[e,t]=k.useState(""),[n,r]=k.useState("all"),s=Kl({all:!0}),i=Ul(),o=Vl(),a=Hl(),{confirm:l,ConfirmDialog:u}=fr(),c=k.useMemo(()=>{var b;return(((b=s.data)==null?void 0:b.jobs)??[]).filter(g=>ub(g,e)).filter(g=>cb(g,n))},[s.data,e,n]),d=async m=>{await l({title:`${I("cronDeleteConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,variant:"destructive",confirmLabel:I("delete")})&&i.mutate({id:m.id})},p=async m=>{const b=!m.enabled;await l({title:b?`${I("cronEnableConfirm")}?`:`${I("cronDisableConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,variant:b?"default":"destructive",confirmLabel:b?I("cronEnable"):I("cronDisable")})&&o.mutate({id:m.id,enabled:b})},f=async m=>{const b=!m.enabled;await l({title:b?`${I("cronRunForceConfirm")}?`:`${I("cronRunConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,confirmLabel:I("cronRunNow")})&&a.mutate({id:m.id,force:b})};return h.jsxs(Iu,{fullHeight:!0,children:[h.jsx(Mu,{title:I("cronPageTitle"),description:I("cronPageDescription"),actions:h.jsx(Ve,{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(Rl,{className:Le("h-4 w-4",s.isFetching&&"animate-spin")})})}),h.jsx("div",{className:"mb-6",children:h.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[h.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[h.jsx(pr,{value:e,onChange:m=>t(m.target.value),placeholder:I("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(ql,{value:n,onValueChange:m=>r(m),children:[h.jsx(Wl,{className:"w-full",children:h.jsx(Gl,{placeholder:I("cronStatusLabel")})}),h.jsxs(Ql,{children:[h.jsx(vt,{value:"all",children:I("cronStatusAll")}),h.jsx(vt,{value:"enabled",children:I("cronStatusEnabled")}),h.jsx(vt,{value:"disabled",children:I("cronStatusDisabled")})]})]})}),h.jsxs("div",{className:"text-xs text-gray-500 ml-auto",children:[I("cronTotalLabel"),": ",((y=s.data)==null?void 0:y.total)??0," / ",c.length]})]})}),h.jsx("div",{className:"flex-1 overflow-auto custom-scrollbar",children:s.isLoading?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronLoading")}):c.length===0?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronEmpty")}):h.jsx("div",{className:"space-y-4",children:c.map(m=>h.jsx(Xl,{className:"border border-gray-200",children:h.jsx(Yl,{className:"pt-5 pb-5",children:h.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[h.jsxs("div",{className:"min-w-[220px] flex-1",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:m.name||m.id}),h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500",children:m.id}),h.jsx("span",{className:Le("text-[10px] font-semibold px-2 py-0.5 rounded-full",m.enabled?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"),children:m.enabled?I("enabled"):I("disabled")}),m.deleteAfterRun&&h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:I("cronOneShot")})]}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronScheduleLabel"),": ",ab(m)]}),h.jsx("div",{className:"mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words",children:m.payload.message}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronDeliverTo"),": ",lb(m)]})]}),h.jsxs("div",{className:"min-w-[220px] text-xs text-gray-500 space-y-2",children:[h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronNextRun"),":"]})," ",ai(m.state.nextRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastRun"),":"]})," ",ai(m.state.lastRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastStatus"),":"]})," ",m.state.lastStatus??"-"]}),m.state.lastError&&h.jsx("div",{className:"text-[11px] text-red-500 break-words",children:m.state.lastError})]}),h.jsxs("div",{className:"flex items-start gap-2 flex-wrap justify-end",children:[h.jsxs(Ve,{variant:"subtle",size:"sm",onClick:()=>f(m),className:"gap-1",children:[h.jsx(Al,{className:"h-3.5 w-3.5"}),I("cronRunNow")]}),h.jsxs(Ve,{variant:m.enabled?"outline":"primary",size:"sm",onClick:()=>p(m),className:"gap-1",children:[h.jsx(El,{className:"h-3.5 w-3.5"}),m.enabled?I("cronDisable"):I("cronEnable")]}),h.jsxs(Ve,{variant:"destructive",size:"sm",onClick:()=>d(m),className:"gap-1",children:[h.jsx(Ti,{className:"h-3.5 w-3.5"}),I("delete")]})]})]})})},m.id))})}),h.jsx(u,{})]})}function Ta(e){const{view:t,routeSessionKey:n,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:i,setSelectedAgentId:o,selectedSessionKeyRef:a,resetStreamState:l,resolveAgentIdFromSessionKey:u}=e;k.useEffect(()=>{if(t==="chat"){if(n){r!==n&&i(n);return}r!==null&&(i(null),l())}},[l,n,r,i,t]),k.useEffect(()=>{const c=r?u(r):null;c&&s!==c&&o(c)},[u,s,r,o]),k.useEffect(()=>{a.current=r},[r,a])}function Ia({view:e,confirmDialog:t}){return h.jsxs("div",{className:"h-full flex",children:[h.jsx($y,{}),e==="chat"?h.jsx(sb,{}):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(db,{})})}):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(xu,{forcedType:"skills"})})})}),t]})}const lr="sid_";function Ma(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 hb(e){const t=Math.random().toString(36).slice(2,8);return`agent:${e}:ui:direct:web-${Date.now().toString(36)}${t}`}function fb(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`${lr}${r}`}function pb(e){if(!e.startsWith(lr))return null;const t=e.slice(lr.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 Ra(e){if(!e)return null;const t=pb(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function gb(e){return`/chat/${fb(e)}`}function mb(e){const t=e.trim();return t.length>0?t:null}function yb(e){return e??null}class Aa{constructor(t){this.updateSession=t,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{const n=V.getState().snapshot,s=ie.getState().snapshot.selectedSessionKey;s&&this.enqueue({sessionKey:s,patch:{preferredModel:mb(n.selectedModel),preferredThinking:yb(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 xb{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.sessionPreferenceSync=new Aa(Bn),this.hasSnapshotChanges=r=>{const s=V.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.isSameStringArray=(r,s)=>r.length===s.length&&r.every((i,o)=>i===s[o]),this.syncComposerSnapshot=r=>{V.getState().setSnapshot({composerNodes:r,draft:Zn(r),selectedSkills:er(r)})},this.syncSnapshot=r=>{if(this.hasSnapshotChanges(r)&&(V.getState().setSnapshot(r),Object.prototype.hasOwnProperty.call(r,"modelOptions")||Object.prototype.hasOwnProperty.call(r,"selectedModel")||Object.prototype.hasOwnProperty.call(r,"selectedThinkingLevel"))){const{selectedModel:s}=V.getState().snapshot;this.reconcileThinkingForModel(s)}},this.setDraft=r=>{const s=V.getState().snapshot.draft,i=this.resolveUpdateValue(s,r);i!==s&&this.syncComposerSnapshot(xa(i))},this.setComposerNodes=r=>{const s=V.getState().snapshot.composerNodes,i=this.resolveUpdateValue(s,r);Object.is(i,s)||this.syncComposerSnapshot(i)},this.setPendingSessionType=r=>{const s=V.getState().snapshot.pendingSessionType,i=this.resolveUpdateValue(s,r);i!==s&&V.getState().setSnapshot({pendingSessionType:i})},this.send=async()=>{const r=V.getState().snapshot,s=ie.getState().snapshot,i=r.draft.trim();if(!i)return;const{selectedSkills:o,composerNodes:a}=r,l=!!s.selectedSessionKey,u=s.selectedSessionKey??hb(s.selectedAgentId);l||this.uiManager.goToSession(u,{replace:!0}),this.setComposerNodes(Fr()),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:o,restoreDraftOnError:!0,composerNodes:a})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=r=>{const s=V.getState().snapshot.selectedModel,i=this.resolveUpdateValue(s,r);i!==s&&(V.getState().setSnapshot({selectedModel:i}),this.reconcileThinkingForModel(i))},this.setSelectedThinkingLevel=r=>{const s=V.getState().snapshot.selectedThinkingLevel,i=this.resolveUpdateValue(s,r);i!==s&&V.getState().setSnapshot({selectedThinkingLevel:i})},this.selectSessionType=r=>{const s=Oe(r);V.getState().setSnapshot({selectedSessionType:s,pendingSessionType:s}),this.syncRemoteSessionType(s)},this.setSelectedSkills=r=>{const s=V.getState().snapshot,{selectedSkills:i}=s,o=this.resolveUpdateValue(i,r);this.isSameStringArray(o,i)||this.syncComposerSnapshot(ba(s.composerNodes,o,s.skillRecords))},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=ie.getState().snapshot,{selectedSessionKey:i}=s;if(!i)return;const o=s.sessions.find(a=>a.key===i);o!=null&&o.sessionTypeMutable&&Oe(o.sessionType)!==r&&await Bn(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=V.getState().snapshot,r=n.modelOptions.find(o=>o.value===t),{selectedThinkingLevel:s}=n,i=this.resolveThinkingForModel(r,s);i!==s&&V.getState().setSnapshot({selectedThinkingLevel:i})}}const bb={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 Sb(e,t){return{driver:"nextbot-stream",mode:"send",payload:e,requestedSkills:t}}function kb(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 vb(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 Ea{constructor(){this.syncSnapshot=t=>{const n=tr.getState().snapshot,r=t.sessionRunStatusByKey;(!r||vb(n.sessionRunStatusByKey,r))&&(t.isLocallyRunning===void 0||Object.is(n.isLocallyRunning,t.isLocallyRunning))&&(t.activeBackendRunId===void 0||Object.is(n.activeBackendRunId,t.activeBackendRunId))||tr.getState().setSnapshot(t)}}}class La{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=ie.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.syncSnapshot=r=>{this.hasSnapshotChanges(r)&&ie.getState().setSnapshot(r)},this.setSelectedAgentId=r=>{const s=ie.getState().snapshot.selectedAgentId,i=this.resolveUpdateValue(s,r);i!==s&&ie.getState().setSnapshot({selectedAgentId:i})},this.setSelectedSessionKey=r=>{const s=ie.getState().snapshot.selectedSessionKey,i=this.resolveUpdateValue(s,r);i!==s&&ie.getState().setSnapshot({selectedSessionKey:i})},this.createSession=r=>{const{snapshot:s}=V.getState(),{defaultSessionType:i}=s,o=i||"native",a=typeof r=="string"&&r.trim().length>0?r.trim():o;this.streamActionsManager.resetStreamState(),V.getState().setSnapshot({pendingSessionType:a}),this.uiManager.goToChatRoot()},this.selectSession=r=>{this.uiManager.goToSession(r)},this.setQuery=r=>{const s=ie.getState().snapshot.query,i=this.resolveUpdateValue(s,r);i!==s&&ie.getState().setSnapshot({query:i})}}}const jn=async()=>{},li=()=>{};class Na{constructor(){this.actions={sendMessage:jn,stopCurrentRun:jn,resumeRun:jn,resetStreamState:li,applyHistoryMessages:li},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 wb=async()=>{};class Cb{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:wb},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=He.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&He.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=ie.getState();if(!(!s||!await this.uiManager.confirm({title:I("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:I("delete")}))){He.getState().setSnapshot({isDeletePending:!0});try{await Jl(s),this.streamActionsManager.resetStreamState(),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{He.getState().setSnapshot({isDeletePending:!1})}}}}}const Tb=async e=>!1;class Pa{constructor(){this.state={pathname:""},this.actions={navigate:null,confirm:Tb},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(gb(t),n)}}}function Ib(e){return e.delta?e.started?[{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[{type:X.TEXT_START,messageId:e.messageId},{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[]}function Mb(e){return!1}function Rb(e){var n,r;return((r=(n=e.message)==null?void 0:n.role)==null?void 0:r.toLowerCase().trim())==="assistant"}function Ab(e){var o;const{event:t,messageId:n}=e,r=t.message;if(!r)return[];const s=(o=r.role)==null?void 0:o.toLowerCase().trim();if(!s)return[];const i=[];if(typeof r.reasoning_content=="string"&&r.reasoning_content.trim()&&(i.push({type:X.REASONING_START,messageId:n}),i.push({type:X.REASONING_DELTA,messageId:n,delta:r.reasoning_content.trim()}),i.push({type:X.REASONING_END,messageId:n})),Array.isArray(r.tool_calls))for(let a=0;a<r.tool_calls.length;a+=1){const l=r.tool_calls[a];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}-${a}`,y=typeof(d==null?void 0:d.name)=="string"?d.name:typeof u.name=="string"?u.name:"tool",m=(d==null?void 0:d.arguments)??u.arguments??"",b=typeof m=="string"?m:JSON.stringify(m??{});i.push({type:X.TOOL_CALL_START,messageId:n,toolCallId:f,toolName:y}),i.push({type:X.TOOL_CALL_ARGS,toolCallId:f,args:b}),i.push({type:X.TOOL_CALL_END,toolCallId:f})}if(s==="tool"||s==="tool_result"||s==="toolresult"||s==="function"){const a=typeof r.tool_call_id=="string"?r.tool_call_id.trim():"";a&&i.push({type:X.TOOL_CALL_RESULT,toolCallId:a,content:r.content})}return i}function ja(){return`stream-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Eb(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 Lb(e){let t="",n=null;const s=await Li.openStream({method:"POST",path:"/api/chat/turn/stream",body:Eb(e.item,e.requestedSkills),signal:e.signal,onEvent:i=>{var o;if(i.name==="ready"){const a=i.payload??{};typeof a.sessionKey=="string"&&a.sessionKey.trim()&&(t=a.sessionKey),e.onReady(a);return}if(i.name==="delta"){e.onDelta(i.payload??{delta:""});return}if(i.name==="session_event"){e.onSessionEvent({data:i.payload});return}if(i.name==="final"){const a=i.payload??{};n={sessionKey:typeof a.sessionKey=="string"&&a.sessionKey.trim()?a.sessionKey:t,reply:typeof a.reply=="string"?a.reply:""};return}if(i.name==="error"){const a=i.payload??{};throw new Error(((o=a.message)==null?void 0:o.trim())||"chat stream failed")}}}).finished;return n!==null?n:{sessionKey:typeof(s==null?void 0:s.sessionKey)=="string"&&s.sessionKey.trim()?s.sessionKey:t,reply:typeof(s==null?void 0:s.reply)=="string"?s.reply:""}}async function Nb(e){let t="",n=null;const r=new URLSearchParams;typeof e.fromEventIndex=="number"&&r.set("fromEventIndex",String(Math.max(0,Math.trunc(e.fromEventIndex))));const s=`/api/chat/runs/${encodeURIComponent(e.runId)}/stream`+(r.size>0?`?${r.toString()}`:""),o=await Li.openStream({method:"GET",path:s,signal:e.signal,onEvent:a=>{var l;if(a.name==="ready"){const u=a.payload??{};typeof u.sessionKey=="string"&&u.sessionKey.trim()&&(t=u.sessionKey),e.onReady(u);return}if(a.name==="delta"){e.onDelta(a.payload??{delta:""});return}if(a.name==="session_event"){e.onSessionEvent({data:a.payload});return}if(a.name==="final"){const u=a.payload??{};n={sessionKey:typeof u.sessionKey=="string"&&u.sessionKey.trim()?u.sessionKey:t,reply:typeof u.reply=="string"?u.reply:""};return}if(a.name==="error"){const u=a.payload??{};throw new Error(((l=u.message)==null?void 0:l.trim())||"chat stream failed")}}}).finished;return n!==null?n:{sessionKey:typeof(o==null?void 0:o.sessionKey)=="string"&&o.sessionKey.trim()?o.sessionKey:t,reply:typeof(o==null?void 0:o.reply)=="string"?o.reply:""}}async function Pb(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 Dn(r)))return;const s=await jb(e);for(const i of s){if(n.has(i))continue;if(n.add(i),await Dn(i))return}if(r&&await Dn(r))return}catch{}}async function Dn(e){const t=e.trim();if(!t)return!1;try{return(await Zl({runId:t})).stopped===!0}catch{return!1}}async function jb(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 o=await Db(e,t);if(o.length>0)return o;i<n-1&&await _b(r)}return[]}async function Db(e,t){try{const n=await eu({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 _b(e){return new Promise(t=>{window.setTimeout(t,e)})}function Da(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 Ob(e){var m;const t=new Set(["tool","tool_result","toolresult","function"]),n=[];let r=0,s=0,i=null;const o=(b,g)=>(r+=1,`history-${b}-${g||"unknown"}-${r}`),a=b=>{const g=typeof b=="string"?b:JSON.stringify(b??{});try{return{args:g,parsedArgs:JSON.parse(g)}}catch{return{args:g}}},l=(b,g)=>{for(let v=b.length-1;v>=0;v-=1){const w=b[v];if(w.type==="tool-invocation"&&w.toolInvocation.toolCallId===g)return v}return-1},u=b=>i?(i={...i,meta:{...i.meta,timestamp:b}},i):(s+=1,i={id:`history-assistant-${s}-${b||"unknown"}`,role:"assistant",parts:[],meta:{source:"history",status:"final",timestamp:b}},i),c=()=>{i&&(i.parts.length>0&&n.push(i),i=null)},d=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"text",text:g}]},p=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"reasoning",reasoning:g,details:[]}]},f=b=>{const g=u(b.timestamp),v=l(g.parts,b.toolCallId),w={type:"tool-invocation",toolInvocation:{status:ue.CALL,toolCallId:b.toolCallId,toolName:b.toolName,args:b.args,parsedArgs:b.parsedArgs}};if(v>=0){g.parts=[...g.parts.slice(0,v),w,...g.parts.slice(v+1)];return}g.parts=[...g.parts,w]},y=b=>{if(!b.toolCallId)return;const g=u(b.timestamp),v=l(g.parts,b.toolCallId);if(v<0){g.parts=[...g.parts,{type:"tool-invocation",toolInvocation:{status:ue.RESULT,toolCallId:b.toolCallId,toolName:b.toolName,args:"{}",parsedArgs:void 0,result:b.result}}];return}const w=g.parts[v];w.type==="tool-invocation"&&(g.parts=[...g.parts.slice(0,v),{...w,toolInvocation:{...w.toolInvocation,status:ue.RESULT,result:b.result}},...g.parts.slice(v+1)])};for(const b of e){const g=(m=b.role)==null?void 0:m.toLowerCase().trim();if(!g)continue;const v=b.timestamp;if(g==="user"||g==="system"||g==="data"){c();const w=Hr(b.content).trim();if(!w)continue;n.push({id:o(g,v),role:g,parts:[{type:"text",text:w}],meta:{source:"history",status:"final",timestamp:v}});continue}if(g==="assistant"){const w=Hr(b.content).trim();if(w&&d(v,w),typeof b.reasoning_content=="string"&&b.reasoning_content.trim()&&p(v,b.reasoning_content.trim()),Array.isArray(b.tool_calls))for(const N of b.tool_calls){if(!N||typeof N!="object")continue;const j=N,T=j.function,O=typeof T=="object"&&T?T:null,B=typeof j.id=="string"?j.id.trim():"";if(!B)continue;const $=typeof(O==null?void 0:O.name)=="string"?O.name:typeof j.name=="string"?j.name:"tool",C=a((O==null?void 0:O.arguments)??j.arguments??"");f({timestamp:v,toolCallId:B,toolName:$,args:C.args,parsedArgs:C.parsedArgs})}continue}if(t.has(g)){const w=typeof b.tool_call_id=="string"?b.tool_call_id.trim():"",N=typeof b.name=="string"&&b.name.trim()?b.name.trim():"tool";y({timestamp:v,toolCallId:w,toolName:N,result:b.content})}}return c(),n}function Fb(){const e=Date.now().toString(36),t=Math.random().toString(36).slice(2,10);return`run-${e}-${t}`}function zb(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(o=>typeof o=="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,o=typeof n.sessionKey=="string"?n.sessionKey.trim():"",a=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}:{},...o?{sessionKey:o}:{},...a?{agentId:a}:{},...typeof l=="boolean"?{stopSupported:l}:{},...u?{stopReason:u}:{}}}return null}function Bb(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 $b(e){var n;return e.mode!=="send"||((n=e.payload.runId)==null?void 0:n.trim())?e:{...e,payload:{...e.payload,runId:Fb()}}}function Kb(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 Ub(){return{deltaMessageId:ja(),deltaStarted:!1,deltaClosed:!1,hasAssistantSessionEvent:!1,hasAssistantOutput:!1}}function Vb(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 Hb(e,t){return{driver:"nextbot-stream",kind:"final",sessionKey:e.sessionKey,reply:e.reply,hasAssistantSessionEvent:t}}function ui(e,t,n){e({type:X.RUN_METADATA,runId:t,metadata:n})}function ci(e,t){!e.deltaStarted||e.deltaClosed||(t({type:X.TEXT_END,messageId:e.deltaMessageId}),e.deltaClosed=!0)}function qb(e,t,n){const r=Ib({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 Wb(e,t,n){Mb(n.data),Rb(n.data)&&(e.hasAssistantSessionEvent=!0);for(const r of Ab({event:n.data,messageId:e.deltaMessageId}))t(r)}function Gb(e,t,n){const r=n.trim();if(e.hasAssistantOutput||!r)return;const s=ja();t({type:X.TEXT_START,messageId:s}),t({type:X.TEXT_DELTA,messageId:s,delta:r}),t({type:X.TEXT_END,messageId:s})}class Qb{constructor(){this.activeAbortController=null,this.activeRunState=null,this.buildMissingMetadataObservable=t=>new Yt(n=>{n.next({type:X.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:o}=t;return n.mode==="send"?Lb({item:n.payload,requestedSkills:n.requestedSkills,signal:r,onReady:s,onDelta:i,onSessionEvent:o}):Nb({runId:n.runId,fromEventIndex:n.fromEventIndex,signal:r,onReady:s,onDelta:i,onSessionEvent:o})},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 Yt(i=>{const o=Ub();let a=!1;const l=c=>{a||i.next(c)};return l({type:X.RUN_STARTED,runId:n}),this.openRunStream({metadata:t,signal:r.signal,onReady:c=>{this.activeRunState&&Kb(this.activeRunState,c),ui(l,n,Vb(c))},onDelta:c=>{qb(o,l,c)},onSessionEvent:c=>{Wb(o,l,c)}}).then(c=>{ci(o,l),Gb(o,l,c.reply),ui(l,n,Hb(c,o.hasAssistantSessionEvent)),l({type:X.RUN_FINISHED,runId:n}),i.complete()}).catch(c=>{ci(o,l),ar(c)||l({type:X.RUN_ERROR,runId:n,error:c instanceof Error?c.message:String(c)}),i.complete()}).finally(()=>{this.finalizeRunState(r,s)}),()=>{a=!0,r.abort(),this.activeAbortController===r&&(this.activeAbortController=null)}}),this.abortRun=()=>{var n;const t=this.activeRunState;t!=null&&t.backendStopSupported&&Pb(t),(n=this.activeAbortController)==null||n.abort(),this.activeAbortController=null,this.activeRunState=null},this.run=t=>{const n=zb(t),r=typeof t.runId=="string"&&t.runId.trim()?t.runId:`run-${Date.now()}`;if(!n)return this.buildMissingMetadataObservable(r);const s=$b(n);this.abortRun();const i=new AbortController;this.activeAbortController=i;const o=Bb(s);return this.activeRunState=o,this.createRunObservable({metadata:s,clientRunId:r,abortController:i,runState:o})}}}class Xb{constructor(){this.chatUiManager=new Pa,this.runtimeAgent=new Qb,this.chatController=new $x({agent:this.runtimeAgent,getToolDefs:()=>[],getContexts:()=>[],getToolExecutor:()=>{}},{metadataParsers:bb}),this.chatStreamActionsManager=new Na,this.chatInputManager=new xb(this.chatUiManager,this.chatStreamActionsManager),this.chatSessionListManager=new La(this.chatUiManager,this.chatStreamActionsManager),this.chatRunStatusManager=new Ea,this.chatThreadManager=new Cb(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}}function Kt(e){const[t,n]=k.useState(e.getValue());return k.useEffect(()=>{const r=e.subscribe(n);return()=>r.unsubscribe()},[e]),t}function Yb(e,t){const[n,r]=k.useState(t);return k.useEffect(()=>{const s=e.subscribe(r);return()=>s.unsubscribe()},[e]),n}function Jb(e,t){const n=k.useRef(e);k.useEffect(()=>{n.current=e});const r=k.useRef(null);k.useEffect(()=>{t.setCallbacks({onRunSettled:async({sourceSessionId:g,resultSessionId:v})=>{const w=n.current;await w.refetchSessions();const N=w.selectedSessionKeyRef.current;(!N||N===g||v&&N===v)&&await w.refetchHistory()},onRunError:({sourceMessage:g,restoreDraft:v})=>{v&&n.current.setDraft(w=>w.trim().length===0&&g?g:w)},onSessionChanged:g=>{n.current.setSelectedSessionKey(v=>v===g?v:g)}})},[t]);const s=Yb(t.messages$,t.getMessages()),i=Kt(t.isAgentResponding$),o=Kt(t.isAwaitingResponse$),a=Kt(t.activeRun$),l=Kt(t.lastError$),u=(a==null?void 0:a.remoteRunId)??null,c=_x(a),d=!!(a&&(c===null||a.remoteStopCapable&&!u)),p=k.useCallback(async g=>{const v=Da(g.requestedSkills),w=Sb(g,v);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=k.useCallback(async g=>{var j,T;const v=(j=g.runId)==null?void 0:j.trim(),w=(T=g.sessionKey)==null?void 0:T.trim();if(!v||!w)return;const N=kb(g);await t.resume({remoteRunId:v,sessionId:w,agentId:g.agentId,metadata:N,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),y=k.useCallback(async()=>{await t.stop()},[t]),m=k.useCallback(()=>{r.current=null,t.reset()},[t]),b=k.useCallback((g,v)=>{if(!!(t.activeRun$.getValue()||t.isAgentResponding$.getValue()))return;const N=n.current.selectedSessionKeyRef.current;if(N!==r.current&&(r.current=N,t.getMessages().length>0&&t.setMessages([])),!N){t.getMessages().length>0&&t.setMessages([]);return}v!=null&&v.isLoading&&g.length===0||t.setMessages(Ob(g))},[t]);return{uiMessages:s,isSending:i,isAwaitingAssistantOutput:o,canStopCurrentRun:d,stopDisabledReason:c,lastSendError:l,activeBackendRunId:u,sendMessage:p,stopCurrentRun:y,resumeRun:f,resetStreamState:m,applyHistoryMessages:b}}function Zb({view:e}){var Ie,Pe,Xe;const[t]=k.useState(()=>new Xb),n=ie(ce=>ce.snapshot.query),r=ie(ce=>ce.snapshot.selectedSessionKey),s=ie(ce=>ce.snapshot.selectedAgentId),i=V(ce=>ce.snapshot.pendingSessionType),o=V(ce=>ce.snapshot.selectedModel),{confirm:a,ConfirmDialog:l}=fr(),u=en(),c=Ii(),{sessionId:d}=Mi(),p=k.useRef(null),f=k.useRef(r),y=k.useMemo(()=>Ra(d),[d]),{sessionsQuery:m,installedSkillsQuery:b,chatCapabilitiesQuery:g,historyQuery:v,isProviderStateResolved:w,modelOptions:N,sessions:j,skillRecords:T,selectedSession:O,historyMessages:B,sessionTypeOptions:$,defaultSessionType:C,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_}=_u({query:n,selectedSessionKey:r,selectedAgentId:s,currentSelectedModel:o,pendingSessionType:i,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),{uiMessages:A,isSending:K,isAwaitingAssistantOutput:L,canStopCurrentRun:G,stopDisabledReason:ae,lastSendError:x,activeBackendRunId:oe,sendMessage:re,stopCurrentRun:S,resumeRun:he,resetStreamState:ke,applyHistoryMessages:se}=Jb({selectedSessionKeyRef:f,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setDraft:t.chatInputManager.setDraft,setComposerNodes:t.chatInputManager.setComposerNodes,refetchSessions:m.refetch,refetchHistory:v.refetch},t.chatController);k.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:re,stopCurrentRun:S,resumeRun:he,resetStreamState:ke,applyHistoryMessages:se})},[se,t,ke,he,re,S]);const{sessionRunStatusByKey:pe}=Au({view:e,selectedSessionKey:r,activeBackendRunId:oe,isLocallyRunning:K||!!oe,resumeRun:t.chatStreamActionsManager.resumeRun});Ta({view:e,routeSessionKey:y,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:f,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Ma}),k.useEffect(()=>{t.chatStreamActionsManager.applyHistoryMessages(B,{isLoading:v.isLoading})},[B,v.isLoading,t]),k.useEffect(()=>{t.chatUiManager.syncState({pathname:u.pathname}),t.chatUiManager.bindActions({navigate:c,confirm:a})},[a,u.pathname,c,t]);const xe=O?Wi(O):void 0,Te=((Ie=$.find(ce=>ce.value===R))==null?void 0:Ie.label)??lt(R);return k.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:m.refetch})},[t,m.refetch]),k.useEffect(()=>{var ce,W;t.chatInputManager.syncSnapshot({isProviderStateResolved:w,defaultSessionType:C,canStopGeneration:G,stopDisabledReason:ae,stopSupported:((ce=g.data)==null?void 0:ce.stopSupported)??!1,stopReason:(W=g.data)==null?void 0:W.stopReason,sendError:x,isSending:K,modelOptions:N,sessionTypeOptions:$,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,skillRecords:T,isSkillsLoading:b.isLoading}),t.chatSessionListManager.syncSnapshot({sessions:j,query:n,isLoading:m.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:pe,isLocallyRunning:K||!!oe,activeBackendRunId:oe}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:w,modelOptions:N,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_,sessionTypeLabel:Te,selectedSessionKey:r,sessionDisplayName:xe,canDeleteSession:!!O,threadRef:p,isHistoryLoading:v.isLoading,uiMessages:A,isSending:K,isAwaitingAssistantOutput:L})},[oe,E,G,xe,Te,(Pe=g.data)==null?void 0:Pe.stopReason,(Xe=g.data)==null?void 0:Xe.stopSupported,C,v.isLoading,b.isLoading,L,w,K,x,N.length,N,t,n,O,r,R,pe,$,z,_,j,m.isLoading,T,ae,p,A]),h.jsx(Qi,{presenter:t,children:h.jsx(Ia,{view:e,confirmDialog:h.jsx(l,{})})})}function di(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*eS(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{value:i,done:o}=await t.read();if(o)break;r+=n.decode(i,{stream:!0});const{frames:a,rest:l}=hi(r);r=l;for(const u of a)yield u}r+=n.decode();const{frames:s}=hi(r,!0);for(const i of s)yield i}finally{t.releaseLock()}}function hi(e,t=!1){const n=e.split(/\r?\n\r?\n/),r=n.pop()??"",s=[];for(const i of n){const o=di(i);o&&s.push(o)}if(t&&r.trim()){const i=di(r);return i&&s.push(i),{frames:s,rest:""}}return{frames:s,rest:r}}var fi="/ncp/agent",tS="ncp-http-agent-client",_a=class extends Error{constructor(t,n=!1){super(t.message);F(this,"ncpError");F(this,"alreadyPublished");this.name=`NcpHttpAgentClientError(${t.code})`,this.ncpError=t,this.alreadyPublished=n}};function nS(e){const t=e.trim();if(!t)throw new Error("NcpHttpAgentClient requires a non-empty baseUrl.");return new URL(t)}function rS(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 sS(e){const t=(e??fi).trim();if(!t)return fi;const n=t.startsWith("/")?t:`/${t}`;return n.endsWith("/")?n.slice(0,-1):n}async function pi(e){try{return(await e.text()).trim()}catch{return""}}function gi(e){if(Oa(e))return e.ncpError;if(iS(e))return e;const t=e instanceof Error?e.message:String(e??"Unknown error");return{code:Fa(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function _n(e,t={}){return new _a(e,t.alreadyPublished??!1)}function iS(e){return zr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function zr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Oa(e){return e instanceof _a}var oS={"config-error":"config-error","auth-error":"auth-error","runtime-error":"runtime-error","timeout-error":"timeout-error","abort-error":"abort-error"};function Fa(e){if(!e)return"runtime-error";const t=oS[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 aS(e){const t=za(e);return!t||typeof t.type!="string"||!t.type.trim()?null:t}function lS(e){const t=za(e);if(!t)return{code:"runtime-error",message:e||"Unknown stream error."};const n=typeof t.code=="string"?t.code:void 0,r=Fa(n),s=zr(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 za(e){try{const t=JSON.parse(e);return zr(t)?t:null}catch{return null}}var uS=["text","file","source","step-start","reasoning","tool-invocation","card","rich-text","action","extension"],cS=class{constructor(e){F(this,"manifest");F(this,"baseUrl");F(this,"basePath");F(this,"fetchImpl");F(this,"defaultHeaders");F(this,"subscribers",new Set);F(this,"activeControllers",new Set);F(this,"started",!1);var t;this.baseUrl=nS(e.baseUrl),this.basePath=sS(e.basePath),this.fetchImpl=rS(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:"custom",endpointId:((t=e.endpointId)==null?void 0:t.trim())||tS,version:"0.1.0",supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:uS,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 pi(n)}`)}catch(n){if(t.signal.aborted)return;const r=gi(n);throw this.publish({type:ne.EndpointError,payload:r}),_n(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 pi(n)}`);if(!n.body)throw new Error("NCP stream response has no body.");for await(const r of eS(n.body)){if(t.signal.aborted)return;this.handleSseFrame(r)}}catch(n){if(t.signal.aborted)return;if(Oa(n))throw n;const r=gi(n);throw this.publish({type:ne.EndpointError,payload:r}),_n(r)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event==="ncp-event"){const t=aS(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=lS(e.data);throw this.publish({type:ne.EndpointError,payload:t}),_n(t,{alreadyPublished:!0})}}};function dS(){return(e,t)=>fetch(e,{credentials:"include",...t})}const hS=new Set(["off","minimal","low","medium","high","adaptive","xhigh"]);function fS(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return String(e??"")}}function Ee(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 pS(e){const t=cn(e);return t?Ee(t.preferred_model)??Ee(t.preferredModel)??Ee(t.model):null}function gS(e){const t=cn(e);if(!t)return null;const n=Ee(t.preferred_thinking)??Ee(t.thinking)??Ee(t.thinking_level)??Ee(t.thinkingLevel);if(!n)return null;const r=n.toLowerCase();return hS.has(r)?r:null}function mS(e){const t=cn(e);return t?Ee(t.label):null}function yS(e){const t=cn(e);return t?Ee(t.session_type)??Ee(t.sessionType)??"native":"native"}function xS(e){return e.state==="result"?ue.RESULT:e.state==="partial-call"?ue.PARTIAL_CALL:ue.CALL}function bS(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:xS(n),toolCallId:n.toolCallId??`${n.toolName}-${Math.random().toString(36).slice(2,8)}`,toolName:n.toolName,args:fS(n.args),result:n.result}})}return t}function SS(e){return e==="service"?"system":e==="tool"?"assistant":e}function kS(e){return{id:e.id,role:SS(e.role),parts:bS(e.parts),meta:{source:"stream",status:e.status,sessionKey:e.sessionId,timestamp:e.timestamp}}}function vS(e){return e.map(kS)}function wS(e){const t=mS(e),n=pS(e),r=gS(e);return{key:e.sessionId,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{label:t}:{},...n?{preferredModel:n}:{},...r?{preferredThinking:r}:{},sessionType:yS(e),sessionTypeMutable:!1,messageCount:e.messageCount}}function CS(e){return e.map(wS)}function TS(e){const t=new Map;for(const r of e.summaries)r.status==="running"&&t.set(r.sessionId,"running");const n=Ee(e.activeSessionId);return e.isLocallyRunning&&n&&t.set(n,"running"),t}function mi(){return`ncp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function IS(){return Ll({queryKey:["ncp-session-types"],queryFn:tu,staleTime:1e4,retry:!1})}function MS(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>r.key.toLowerCase().includes(n)):e}function RS(e){if(!e.supportedModels||e.supportedModels.length===0)return e.modelOptions;const t=new Set(e.supportedModels),n=e.modelOptions.filter(r=>t.has(r.value));return n.length>0?n:e.modelOptions}function AS(e){var N,j,T,O,B,$,C,R;const t=Ri(),n=Ai(),r=nu({limit:200}),s=IS(),i=Ni("skill"),o=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),a=k.useMemo(()=>{const E=ji({meta:n.data,config:t.data,onlyConfigured:!0}),z=new Set,_=[];for(const A of E)for(const K of A.models){const L=Di(A.prefix,K);!L||z.has(L)||(z.add(L),_.push({value:L,modelLabel:K,providerLabel:A.displayName,thinkingCapability:_i(A.modelThinking,K,A.aliases)}))}return _.sort((A,K)=>{const L=A.providerLabel.localeCompare(K.providerLabel);return L!==0?L:A.modelLabel.localeCompare(K.modelLabel)})},[n.data,t.data]),l=k.useMemo(()=>{var E;return((E=r.data)==null?void 0:E.sessions)??[]},[(N=r.data)==null?void 0:N.sessions]),u=k.useMemo(()=>CS(l),[l]),c=k.useMemo(()=>MS(u,e.query),[u,e.query]),d=k.useMemo(()=>u.find(E=>E.key===e.selectedSessionKey)??null,[u,e.selectedSessionKey]),p=k.useMemo(()=>{var E;return((E=i.data)==null?void 0:E.records)??[]},[(j=i.data)==null?void 0:j.records]),f=zi({selectedSession:d,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:s.data}),y=k.useMemo(()=>{var E;return RS({modelOptions:a,supportedModels:(E=f.selectedSessionTypeOption)==null?void 0:E.supportedModels})},[a,(T=f.selectedSessionTypeOption)==null?void 0:T.supportedModels]),m=k.useMemo(()=>Ki({sessions:u,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[u,e.selectedSessionKey,f.selectedSessionType]),b=k.useMemo(()=>y.find(E=>E.value===e.currentSelectedModel),[y,e.currentSelectedModel]),g=k.useMemo(()=>{var E;return((E=b==null?void 0:b.thinkingCapability)==null?void 0:E.supported)??[]},[(O=b==null?void 0:b.thinkingCapability)==null?void 0:O.supported]),v=k.useMemo(()=>{var E;return((E=b==null?void 0:b.thinkingCapability)==null?void 0:E.default)??null},[(B=b==null?void 0:b.thinkingCapability)==null?void 0:B.default]),w=k.useMemo(()=>Ui({sessions:u,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[u,e.selectedSessionKey,f.selectedSessionType]);return Hi({modelOptions:y,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!d,selectedSessionPreferredModel:d==null?void 0:d.preferredModel,fallbackPreferredModel:(($=f.selectedSessionTypeOption)==null?void 0:$.recommendedModel)??m,defaultModel:((C=f.selectedSessionTypeOption)==null?void 0:C.recommendedModel)??((R=t.data)==null?void 0:R.agents.defaults.model),setSelectedModel:e.setSelectedModel}),qi({supportedThinkingLevels:g,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!d,selectedSessionPreferredThinking:(d==null?void 0:d.preferredThinking)??null,fallbackPreferredThinking:w??null,defaultThinkingLevel:v,setSelectedThinkingLevel:e.setSelectedThinkingLevel}),{configQuery:t,configMetaQuery:n,sessionsQuery:r,sessionTypesQuery:s,installedSkillsQuery:i,isProviderStateResolved:o,modelOptions:y,sessionSummaries:l,sessions:c,skillRecords:p,selectedSession:d,...f}}class ES{constructor(t,n,r){this.uiManager=t,this.streamActionsManager=n,this.getDraftSessionId=r,this.sessionPreferenceSync=new Aa(Ei),this.buildAttachmentSignature=s=>[s.name,s.mimeType,String(s.sizeBytes),s.contentBase64].join(":"),this.hasSnapshotChanges=s=>{const i=V.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.resolveUpdateValue=(s,i)=>typeof i=="function"?i(s):i,this.isSameStringArray=(s,i)=>s.length===i.length&&s.every((o,a)=>o===i[a]),this.syncComposerSnapshot=s=>{const i=V.getState().snapshot.attachments,o=Ly(s,i);V.getState().setSnapshot({composerNodes:s,attachments:o,draft:Zn(s),selectedSkills:er(s)})},this.syncComposerSnapshotWithAttachments=(s,i)=>{V.getState().setSnapshot({composerNodes:s,attachments:i,draft:Zn(s),selectedSkills:er(s)})},this.dedupeAttachments=s=>{const i=new Set,o=[];for(const a of s){const l=this.buildAttachmentSignature(a);i.has(l)||(i.add(l),o.push(a))}return o},this.syncSnapshot=s=>{if(this.hasSnapshotChanges(s)&&(V.getState().setSnapshot(s),Object.prototype.hasOwnProperty.call(s,"modelOptions")||Object.prototype.hasOwnProperty.call(s,"selectedModel")||Object.prototype.hasOwnProperty.call(s,"selectedThinkingLevel"))){const{selectedModel:i}=V.getState().snapshot;this.reconcileThinkingForModel(i)}},this.setDraft=s=>{const i=V.getState().snapshot.draft,o=this.resolveUpdateValue(i,s);o!==i&&this.syncComposerSnapshot(xa(o))},this.setComposerNodes=s=>{const i=V.getState().snapshot.composerNodes,o=this.resolveUpdateValue(i,s);Object.is(o,i)||this.syncComposerSnapshot(o)},this.addAttachments=s=>{if(s.length===0)return[];const i=V.getState().snapshot,o=new Set(i.attachments.map(this.buildAttachmentSignature)),a=this.dedupeAttachments([...i.attachments,...s]),l=a.filter(c=>!o.has(this.buildAttachmentSignature(c)));if(l.length===0)return[];const u=qs(i.composerNodes,a);return this.syncComposerSnapshotWithAttachments(u,a),l},this.restoreComposerState=(s,i)=>{const o=this.dedupeAttachments(i),a=qs(s,o);this.syncComposerSnapshotWithAttachments(a,o)},this.setPendingSessionType=s=>{const i=V.getState().snapshot.pendingSessionType,o=this.resolveUpdateValue(i,s);o!==i&&V.getState().setSnapshot({pendingSessionType:o})},this.send=async()=>{const s=V.getState().snapshot,i=ie.getState().snapshot,o=s.draft.trim(),a=s.attachments,l=Ny(s.composerNodes,a);if(!l.some(f=>f.type!=="text"||f.text.trim().length>0))return;const{selectedSkills:c,composerNodes:d}=s,p=i.selectedSessionKey??this.getDraftSessionId();i.selectedSessionKey||this.uiManager.goToSession(p,{replace:!0}),this.setComposerNodes(Fr()),await this.streamActionsManager.sendMessage({message:o,sessionKey:p,agentId:i.selectedAgentId,sessionType:s.selectedSessionType,model:s.selectedModel||void 0,thinkingLevel:s.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:c,attachments:a,parts:l,restoreDraftOnError:!0,composerNodes:d})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=s=>{const i=V.getState().snapshot.selectedModel,o=this.resolveUpdateValue(i,s);o!==i&&(V.getState().setSnapshot({selectedModel:o}),this.reconcileThinkingForModel(o))},this.setSelectedThinkingLevel=s=>{const i=V.getState().snapshot.selectedThinkingLevel,o=this.resolveUpdateValue(i,s);o!==i&&V.getState().setSnapshot({selectedThinkingLevel:o})},this.selectSessionType=s=>{const i=Oe(s);V.getState().setSnapshot({selectedSessionType:i,pendingSessionType:i})},this.setSelectedSkills=s=>{const i=V.getState().snapshot,{selectedSkills:o}=i,a=this.resolveUpdateValue(o,s);this.isSameStringArray(a,o)||this.syncComposerSnapshot(ba(i.composerNodes,a,i.skillRecords))},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=V.getState().snapshot,r=n.modelOptions.find(o=>o.value===t),{selectedThinkingLevel:s}=n,i=this.resolveThinkingForModel(r,s);i!==s&&V.getState().setSnapshot({selectedThinkingLevel:i})}}const LS=async()=>{};class NS{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:LS},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=He.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&He.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=ie.getState();if(!(!s||!await this.uiManager.confirm({title:I("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:I("delete")}))){He.getState().setSnapshot({isDeletePending:!0});try{await ru(s),this.streamActionsManager.resetStreamState(),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{He.getState().setSnapshot({isDeletePending:!1})}}}}}class PS{constructor(){this.chatUiManager=new Pa,this.chatStreamActionsManager=new Na,this.chatSessionListManager=new La(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new ES(this.chatUiManager,this.chatStreamActionsManager,()=>this.getDraftSessionId()),this.chatRunStatusManager=new Ea,this.chatThreadManager=new NS(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager),this.draftSessionId="",this.setDraftSessionId=t=>{this.draftSessionId=t}}getDraftSessionId(){return this.draftSessionId}}function jS(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=Da(e.requestedSkills);return n.length>0&&(t.requested_skills=n),t}function DS(e){return e instanceof Error?e.message.includes("ncp session not found:"):!1}function _S({view:e}){var Pe,Xe,ce;const[t]=k.useState(()=>new PS),[n,r]=k.useState(()=>mi()),s=ie(W=>W.snapshot.query),i=ie(W=>W.snapshot.selectedSessionKey),o=ie(W=>W.snapshot.selectedAgentId),a=V(W=>W.snapshot.pendingSessionType),l=V(W=>W.snapshot.selectedModel),{confirm:u,ConfirmDialog:c}=fr(),d=en(),p=Ii(),{sessionId:f}=Mi(),y=k.useRef(null),m=k.useRef(i),b=k.useMemo(()=>Ra(f),[f]),{sessionsQuery:g,installedSkillsQuery:v,isProviderStateResolved:w,modelOptions:N,sessionSummaries:j,sessions:T,skillRecords:O,selectedSession:B,sessionTypeOptions:$,defaultSessionType:C,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_}=AS({query:s,selectedSessionKey:i,currentSelectedModel:l,pendingSessionType:a,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),A=g.refetch,K=i??n,L=k.useRef(j);k.useEffect(()=>{L.current=j},[j]);const[G]=k.useState(()=>new cS({baseUrl:su,basePath:"/api/ncp/agent",fetchImpl:dS()})),ae=k.useCallback(async(W,Ye)=>{Ye.throwIfAborted();let je=null;try{je=await iu(W,300)}catch(Be){if(!DS(Be))throw Be}Ye.throwIfAborted();const ze=L.current.find(Be=>Be.sessionId===W)??null;return{messages:(je==null?void 0:je.messages)??[],status:(ze==null?void 0:ze.status)==="running"?"running":"idle"}},[]),x=ex({sessionId:K,client:G,loadSeed:ae});k.useEffect(()=>{t.setDraftSessionId(n)},[n,t]),k.useEffect(()=>{if(i===null){const W=mi();r(W),t.setDraftSessionId(W)}},[t,i]);const oe=k.useMemo(()=>vS(x.visibleMessages),[x.visibleMessages]),re=x.isSending||x.isRunning,S=x.isRunning,he=x.isRunning,ke=x.isRunning?null:"__preparing__",se=((Pe=x.hydrateError)==null?void 0:Pe.message)??((Xe=x.snapshot.error)==null?void 0:Xe.message)??null,pe=x.activeRunId,xe=k.useMemo(()=>TS({summaries:j,activeSessionId:K,isLocallyRunning:re||!!pe}),[pe,K,re,j]);k.useEffect(()=>{!re&&!pe||A()},[pe,re,A]),k.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:async W=>{var ze,Be;if(W.sessionKey!==K)return;const Ye=jS({model:W.model,thinkingLevel:W.thinkingLevel,sessionType:W.sessionType,requestedSkills:W.requestedSkills}),je=ox({sessionId:W.sessionKey,text:W.message,attachments:W.attachments,parts:W.parts,metadata:Ye});if(je)try{g.refetch(),await x.send(je),await g.refetch()}catch(Dt){throw W.restoreDraftOnError&&(W.composerNodes&&W.composerNodes.length>0?(Be=(ze=t.chatInputManager).restoreComposerState)==null||Be.call(ze,W.composerNodes,W.attachments??[]):t.chatInputManager.setDraft(ft=>ft.trim().length===0?W.message:ft)),Dt}},stopCurrentRun:async()=>{await x.abort(),await g.refetch()},resumeRun:async W=>{W.sessionKey===K&&await x.streamRun()},resetStreamState:()=>{m.current=null},applyHistoryMessages:()=>{}})},[K,x,t,g]),Ta({view:e,routeSessionKey:b,selectedSessionKey:i,selectedAgentId:o,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:m,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Ma}),k.useEffect(()=>{t.chatUiManager.syncState({pathname:d.pathname}),t.chatUiManager.bindActions({navigate:p,confirm:u})},[u,d.pathname,p,t]);const Te=B?Wi(B):void 0,Ie=((ce=$.find(W=>W.value===R))==null?void 0:ce.label)??lt(R);return k.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:g.refetch})},[t,g.refetch]),k.useEffect(()=>{t.chatInputManager.syncSnapshot({isProviderStateResolved:w,defaultSessionType:C,canStopGeneration:he,stopDisabledReason:ke,stopSupported:!0,stopReason:void 0,sendError:se,isSending:re,modelOptions:N,sessionTypeOptions:$,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,skillRecords:O,isSkillsLoading:v.isLoading}),t.chatSessionListManager.syncSnapshot({sessions:T,query:s,isLoading:g.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:xe,isLocallyRunning:re||!!pe,activeBackendRunId:pe}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:w,modelOptions:N,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_,sessionTypeLabel:Ie,selectedSessionKey:i,sessionDisplayName:Te,canDeleteSession:!!B,threadRef:y,isHistoryLoading:x.isHydrating,uiMessages:oe,isSending:re,isAwaitingAssistantOutput:S})},[pe,x.isHydrating,E,he,Te,Ie,C,v.isLoading,S,w,re,se,N.length,N,t,s,B,i,R,xe,$,z,_,T,g.isLoading,O,ke,y,oe]),h.jsx(Qi,{presenter:t,children:h.jsx(Ia,{view:e,confirmDialog:h.jsx(c,{})})})}function QS({view:e}){const t=en();return Fi(t.search)==="ncp"?h.jsx(_S,{view:e}):h.jsx(Zb,{view:e})}export{QS as ChatPage};
|
|
37
|
+
`):"",this.name="UnsubscriptionError",this.errors=n}});function sr(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 o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=On(o),l=a.next();!l.done;l=a.next()){var u=l.value;u.remove(this)}}catch(m){t={error:m}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var c=this.initialTeardown;if(qe(c))try{c()}catch(m){i=m instanceof Nn?m.errors:[m]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var p=On(d),f=p.next();!f.done;f=p.next()){var y=f.value;try{Js(y)}catch(m){i=i??[],m instanceof Nn?i=Fn(Fn([],zn(i)),zn(m.errors)):i.push(m)}}}catch(m){r={error:m}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}}if(i)throw new Nn(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Js(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)&&sr(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&sr(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),Ca=un.EMPTY;function Ta(e){return e instanceof un||e&&"closed"in e&&qe(e.remove)&&qe(e.add)&&qe(e.unsubscribe)}function Js(e){qe(e)?e():e.unsubscribe()}var Sx={Promise:void 0},kx={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Fn([e,t],zn(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function vx(e){kx.setTimeout(function(){throw e})}function Zs(){}function qt(e){e()}var Ia=(function(e){At(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Ta(n)&&n.add(r)):r.destination=Tx,r}return t.create=function(n,r,s){return new ir(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),wx=(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){$t(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){$t(r)}else $t(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){$t(n)}},e})(),ir=(function(e){At(t,e);function t(n,r,s){var i=e.call(this)||this,o;return qe(n)||!n?o={next:n??void 0,error:r??void 0,complete:s??void 0}:o=n,i.destination=new wx(o),i}return t})(Ia);function $t(e){vx(e)}function Cx(e){throw e}var Tx={closed:!0,next:Zs,error:Cx,complete:Zs},Ix=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Mx(e){return e}function Rx(e){return e.length===0?Mx:e.length===1?e[0]:function(n){return e.reduce(function(r,s){return s(r)},n)}}var Yt=(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=Ex(t)?t:new ir(t,n,r);return qt(function(){var o=s,a=o.operator,l=o.source;i.add(a?a.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=ei(n),new n(function(s,i){var o=new ir({next:function(a){try{t(a)}catch(l){i(l),o.unsubscribe()}},error:i,complete:s});r.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Ix]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Rx(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=ei(t),new t(function(r,s){var i;n.subscribe(function(o){return i=o},function(o){return s(o)},function(){return r(i)})})},e.create=function(t){return new e(t)},e})();function ei(e){var t;return(t=e??Sx.Promise)!==null&&t!==void 0?t:Promise}function Ax(e){return e&&qe(e.next)&&qe(e.error)&&qe(e.complete)}function Ex(e){return e&&e instanceof Ia||Ax(e)&&Ta(e)}var Lx=wa(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ue=(function(e){At(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 ti(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new Lx},t.prototype.next=function(n){var r=this;qt(function(){var s,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=On(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(n)}}catch(u){s={error:u}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}}})},t.prototype.error=function(n){var r=this;qt(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;qt(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,o=s.isStopped,a=s.observers;return i||o?Ca:(this.currentObservers=null,a.push(n),new un(function(){r.currentObservers=null,sr(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,s=r.hasError,i=r.thrownError,o=r.isStopped;s?n.error(i):o&&n.complete()},t.prototype.asObservable=function(){var n=new Yt;return n.source=this,n},t.create=function(n,r){return new ti(n,r)},t})(Yt),ti=(function(e){At(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:Ca},t})(Ue),it=(function(e){At(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})(Ue);const fe=[];for(let e=0;e<256;++e)fe.push((e+256).toString(16).slice(1));function Nx(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 Pn;const Px=new Uint8Array(16);function jx(){if(!Pn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pn=crypto.getRandomValues.bind(crypto)}return Pn(Px)}const Dx=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ni={randomUUID:Dx};function or(e,t,n){var s;if(ni.randomUUID&&!e)return ni.randomUUID();e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??jx();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,Nx(r)}var ue=(e=>(e.CALL="call",e.RESULT="result",e.PARTIAL_CALL="partial-call",e.ERROR="error",e.CANCELLED="cancelled",e))(ue||{}),X=(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))(X||{});function _x(e){return!e||e.remoteStopCapable&&e.remoteRunId?null:e.remoteStopCapable?"__preparing__":e.remoteStopReason??""}const Ox=e=>{try{return JSON.parse(e)}catch{return}},ri=e=>({toolCallId:e.id,toolName:e.function.name,args:e.function.arguments,parsedArgs:Ox(e.function.arguments),status:ue.CALL});function Fx(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"||![ue.CALL,ue.PARTIAL_CALL].includes(i.toolInvocation.status))return i;let o;if(typeof i.toolInvocation.args=="string")try{o=JSON.parse(i.toolInvocation.args)}catch{return{...i,toolInvocation:{...i.toolInvocation,args:JSON.stringify({}),parsedArgs:o,status:ue.RESULT,result:{error:"invalid_args",raw:i.toolInvocation.args}}}}return{...i,toolInvocation:{...i.toolInvocation,args:i.toolInvocation.args,parsedArgs:o,status:ue.RESULT,result:n}}})}:r})}function ar(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 si(e){if(e instanceof Error){const n=e.message.trim();if(n)return n}return String(e??"").trim()||"Failed to send message"}function ii(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 zx{constructor(t){F(this,"currentMessageId");F(this,"currentReasoningMessageId");F(this,"currentReasoningContent","");F(this,"currentToolCallId");F(this,"currentToolCallMessageId");F(this,"currentToolCallName");F(this,"currentToolCallArgs","");F(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(a=>a.type==="tool-invocation"&&a.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===ue.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 X.RUN_STARTED:break;case X.TEXT_START:this.handleTextStart(t);break;case X.TEXT_DELTA:this.handleTextContent(t);break;case X.TEXT_END:this.handleTextEnd();break;case X.REASONING_START:this.handleReasoningStart(t);break;case X.REASONING_DELTA:this.handleReasoningContent(t);break;case X.REASONING_END:this.handleReasoningEnd();break;case X.TOOL_CALL_START:this.handleToolCallStart(t);break;case X.TOOL_CALL_ARGS_DELTA:this.handleToolCallArgsDelta(t);break;case X.TOOL_CALL_ARGS:this.handleToolCallArgs(t);break;case X.TOOL_CALL_END:this.handleToolCallEnd(),this.emitToolCallEvents();break;case X.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 o=r.length-1;o>=0;o-=1)if(((i=r[o])==null?void 0:i.type)==="reasoning"){s=o;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(o=>o.role==="assistant"&&o.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:ue.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 o=this.findAssistantMessageByToolCallId(this.currentToolCallId);if(o){this.currentToolCallMessageId=o.id;const u=o.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 a=r[r.length-1];if(a&&a.role==="assistant")this.currentToolCallMessageId=a.id,this.sessionManager.updateMessage({...a,parts:[...a.parts||[],n]});else{const u=or();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 o=r[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===t.toolCallId){let a;try{a=JSON.parse(this.currentToolCallArgs)}catch{}r[i]={...o,toolInvocation:{...o.toolInvocation,status:ue.PARTIAL_CALL,args:this.currentToolCallArgs,parsedArgs:a}};break}}this.sessionManager.updateMessage({...n,parts:r})}handleToolCallArgs(t){this.currentToolCallId===t.toolCallId&&(this.currentToolCallArgs=t.args,this.handleToolCallArgsDelta({type:X.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 o=s[i];if(o.type==="tool-invocation"&&o.toolInvocation.toolCallId===this.currentToolCallId){s[i]={...o,toolInvocation:{...ri(n),status:ue.CALL}};break}}this.sessionManager.updateMessage({...r,parts:s})}else{const s=((t=this.currentToolCallMessageId)==null?void 0:t.trim())||or();this.sessionManager.addMessages([{id:s,role:"assistant",parts:[{type:"tool-invocation",toolInvocation:{...ri(n),status:ue.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:ue.RESULT})}}class Bx{constructor(){F(this,"disposables",[]);F(this,"addDisposable",t=>{this.disposables.push(t)});F(this,"dispose",()=>{this.disposables.forEach(t=>t()),this.disposables=[]})}}class $x extends Bx{constructor(n=null,r){super();F(this,"_messages$",new it([]));F(this,"messages$");F(this,"threadId$",new it(null));F(this,"isAgentResponding$",new it(!1));F(this,"activeRun$",new it(null));F(this,"lastError$",new it(null));F(this,"isAwaitingResponse$",new it(!1));F(this,"runCompleted$",new Ue);F(this,"runError$",new Ue);F(this,"runMetadata$",new Ue);F(this,"activeSubscription",null);F(this,"addMessagesEvent$",new Ue);F(this,"updateMessageEvent$",new Ue);F(this,"setMessagesEvent$",new Ue);F(this,"toolCall$",new Ue);F(this,"eventHandler",new zx(this));F(this,"runIdCounter",0);F(this,"metadataParsers");F(this,"callbacks");F(this,"getMessages",()=>this._messages$.getValue());F(this,"setMessages",n=>{this._messages$.next(n),this.setMessagesEvent$.next({messages:n})});F(this,"handleEvent",n=>{this.eventHandler.handleEvent(n)});F(this,"setCallbacks",n=>{this.callbacks=n});F(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});F(this,"addMessages",n=>{const s=[...this.getMessages()];for(const i of n){const o=s.findIndex(a=>a.id===i.id);o>=0?s[o]=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)});F(this,"removeMessages",n=>{n.length!==0&&this._messages$.next(this.getMessages().filter(r=>!n.includes(r.id)))});F(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)});F(this,"addToolResult",(n,r)=>{const s=this.getMessages().find(o=>o.parts.find(a=>a.type==="tool-invocation"&&a.toolInvocation.toolCallId===n.toolCallId));if(!s)return;const i={...s,parts:s.parts.map(o=>o.type==="tool-invocation"&&o.toolInvocation.toolCallId===n.toolCallId?{...o,toolInvocation:{...o.toolInvocation,result:n.result??void 0,status:n.status,error:n.error??void 0,cancelled:n.cancelled??void 0}}:o)};this.updateMessage(i)});F(this,"send",async n=>{(this.activeRun$.getValue()||this.activeSubscription)&&this.abortAgentRun(),this.lastError$.next(null);const r=n.message.trim();r&&(this.addMessages([{id:or(),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}))});F(this,"resume",async n=>{var o,a;const r=(o=n.remoteRunId)==null?void 0:o.trim(),s=(a=n.sessionId)==null?void 0:a.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})))});F(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}))});F(this,"handleAgentResponse",n=>{this.activeSubscription&&this.activeSubscription.unsubscribe(),this.activeSubscription=n.subscribe(r=>{var s,i,o,a,l,u,c,d,p;if(r.type===X.RUN_METADATA){const f=r,y=this.activeRun$.getValue(),m=((s=f.runId)==null?void 0:s.trim())||(y?`ui-${y.localRunId}`:"");this.metadataParsers&&y&&this.isMatchingRun(y,m)&&this.processRunMetadata(y,f.metadata),this.runMetadata$.next({runId:m,metadata:f.metadata});return}if(this.handleEvent(r),r.type===X.RUN_FINISHED){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),y=((i=r.runId)==null?void 0:i.trim())||(f?`ui-${f.localRunId}`:"");if(!f||!this.isMatchingRun(f,y))return;const m=f.sessionId;this.activeRun$.next(null),m&&((a=(o=this.callbacks).onRunSettled)==null||a.call(o,{sourceSessionId:m}))}else if(r.type===X.RUN_ERROR){this.isAgentResponding$.next(!1),this.isAwaitingResponse$.next(!1),this.activeSubscription=null;const f=this.activeRun$.getValue(),y=((l=r.runId)==null?void 0:l.trim())||(f?`ui-${f.localRunId}`:""),m=ar(r.error);if(this.runError$.next({runId:y,error:r.error,isAbort:m}),!f||!this.isMatchingRun(f,y)){this.activeRun$.next(null);return}const b=f.sessionId;if(m){this.activeRun$.next(null),b&&((c=(u=this.callbacks).onRunSettled)==null||c.call(u,{sourceSessionId:b}));return}const g=si(r.error);this.lastError$.next(g),this.activeRun$.next(null),b&&this.addMessages([ii(g,{sessionKey:b,status:"error"})]),(p=(d=this.callbacks).onRunError)==null||p.call(d,{error:g,sourceMessage:f.sourceMessage,restoreDraft:f.restoreDraftOnError})}})});F(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)});F(this,"runAgent",async n=>{var o,a,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=Fx(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=ar(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=si(c);this.lastError$.next(f),p.sessionId&&this.addMessages([ii(f,{sessionKey:p.sessionId,status:"error"})]),(a=(o=this.callbacks).onRunError)==null||a.call(o,{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}))}});F(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)});F(this,"applyReadyMetadata",(n,r)=>{var i,o,a,l,u;const s={...n};(i=r.remoteRunId)!=null&&i.trim()&&(s.remoteRunId=r.remoteRunId.trim()),typeof r.stopCapable=="boolean"&&(s.remoteStopCapable=r.stopCapable),(o=r.stopReason)!=null&&o.trim()&&(s.remoteStopReason=r.stopReason.trim()),(a=r.sessionId)!=null&&a.trim()&&(s.sessionId=r.sessionId.trim(),(u=(l=this.callbacks).onSessionChanged)==null||u.call(l,s.sessionId)),this.activeRun$.next(s)});F(this,"applyFinalMetadata",(n,r)=>{var o,a,l,u;const s=n.sessionId,i=r.sessionId;i&&i!==s&&((a=(o=this.callbacks).onSessionChanged)==null||a.call(o,i)),this.activeRun$.next(null),s&&((u=(l=this.callbacks).onRunSettled)==null||u.call(l,{sourceSessionId:s,resultSessionId:i}))});F(this,"isMatchingRun",(n,r)=>r.trim()?r===`ui-${n.localRunId}`:!1);F(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 o=JSON.parse(r.function.arguments),a=await s(o);this.addToolResult({toolCallId:r.id,result:a,status:ue.RESULT}),this.runAgent()}catch(o){console.error("[AgentChatController] handleAddToolResult error",o),this.addToolResult({toolCallId:r.id,error:o instanceof Error?o.message:String(o),status:ue.ERROR}),this.runAgent()}});return()=>n.unsubscribe()});this.agentProvider=n;const{initialMessages:s=[],metadataParsers:i,callbacks:o={}}=r||{};this.metadataParsers=i??null,this.callbacks=o,this._messages$.next(s),this.messages$=this._messages$.asObservable(),this.agentProvider&&this.addDisposable(this.connectToolExecutor())}}const Kx=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Ux(e){return typeof e=="object"&&e!==null}function Vx(e){return e.type==="text"&&typeof e.text=="string"}function Hx(e){return e.type==="reasoning"&&typeof e.reasoning=="string"}function qx(e){return e.type==="file"&&typeof e.mimeType=="string"&&typeof e.data=="string"}function Wx(e){return e.type!=="tool-invocation"||!Ux(e.toolInvocation)?!1:typeof e.toolInvocation.toolName=="string"}function Qx(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 Gx(e,t){return e==="user"?t.user:e==="assistant"?t.assistant:e==="tool"?t.tool:e==="system"?t.system:t.fallback}function Xx(e){return e==="user"||e==="assistant"||e==="tool"||e==="system"?e:"message"}function Yx(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 oi(e){const t=e.trim();return t&&t.replace(Kx,"").trim()?t:null}function Jx(e){return e.uiMessages.map(t=>{var n;return{id:t.id,role:Xx(t.role),roleLabel:Gx(t.role,e.texts.roleLabels),timestampLabel:e.formatTimestamp(Qx(t)),status:(n=t.meta)==null?void 0:n.status,parts:t.parts.map(r=>{if(Vx(r)){const s=oi(r.text);return s?{type:"markdown",text:s}:null}if(Hx(r)){const s=oi(r.reasoning);return s?{type:"reasoning",text:s,label:e.texts.reasoningLabel}:null}if(qx(r)){const s=r.mimeType.startsWith("image/");return{type:"file",file:{label:typeof r.name=="string"&&r.name.trim()?r.name.trim():s?e.texts.imageAttachmentLabel:e.texts.fileAttachmentLabel,mimeType:r.mimeType,dataUrl:typeof r.url=="string"&&r.url.trim().length>0?r.url.trim():`data:${r.mimeType};base64,${r.data}`,isImage:s}}}if(Wx(r)){const s=r.toolInvocation,i=cu(s.parsedArgs??s.args),o=typeof s.error=="string"&&s.error.trim()?s.error.trim():s.result!=null?Vr(s.result).trim():"",a=s.status==="result"||s.status==="error"||s.status==="cancelled",l={kind:a?"result":"call",name:s.toolName,detail:i,text:o||void 0,callId:s.toolCallId||void 0,hasResult:a};return{type:"tool-card",card:Yx(l,e.texts)}}return{type:"unknown",label:e.texts.unknownPartLabel,rawType:typeof r.type=="string"?r.type:"unknown",text:Vr(r)}}).filter(r=>r!==null)}})}function Zx(e){const{language:t}=gr(),n=k.useMemo(()=>e.uiMessages.map(s=>{var i,o;return{id:s.id,role:s.role,meta:{timestamp:(i=s.meta)==null?void 0:i.timestamp,status:(o=s.meta)==null?void 0:o.status},parts:s.parts}}),[e.uiMessages]),r=k.useMemo(()=>Jx({uiMessages:n,formatTimestamp:s=>tn(s,t),texts:{roleLabels:{user:I("chatRoleUser"),assistant:I("chatRoleAssistant"),tool:I("chatRoleTool"),system:I("chatRoleSystem"),fallback:I("chatRoleMessage")},reasoningLabel:I("chatReasoning"),toolCallLabel:I("chatToolCall"),toolResultLabel:I("chatToolResult"),toolNoOutputLabel:I("chatToolNoOutput"),toolOutputLabel:I("chatToolOutput"),imageAttachmentLabel:I("chatImageAttachment"),fileAttachmentLabel:I("chatFileAttachment"),unknownPartLabel:I("chatUnknownPart")}}),[t,n]);return h.jsx(Ry,{messages:r,isSending:e.isSending,hasAssistantDraft:e.uiMessages.some(s=>{var i,o;return s.role==="assistant"&&(((i=s.meta)==null?void 0:i.status)==="streaming"||((o=s.meta)==null?void 0:o.status)==="pending")}),className:e.className,texts:{copyCodeLabel:I("chatCodeCopy"),copiedCodeLabel:I("chatCodeCopied"),typingLabel:I("chatTyping")}})}const eb=[{icon:Al,titleKey:"chatWelcomeCapability1Title",descKey:"chatWelcomeCapability1Desc"},{icon:cr,titleKey:"chatWelcomeCapability2Title",descKey:"chatWelcomeCapability2Desc"},{icon:hr,titleKey:"chatWelcomeCapability3Title",descKey:"chatWelcomeCapability3Desc"}];function tb({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(wi,{className:"h-8 w-8 text-primary"})}),h.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:I("chatWelcomeTitle")}),h.jsx("p",{className:"text-sm text-gray-500 mb-8",children:I("chatWelcomeSubtitle")}),h.jsx("div",{className:"grid grid-cols-3 gap-3",children:eb.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:I(t.titleKey)}),h.jsx("div",{className:"text-[11px] text-gray-500 leading-relaxed",children:I(t.descKey)})]},t.titleKey)})})]})})}const nb={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},He=Zt(e=>({snapshot:nb,setSnapshot:t=>e(n=>({snapshot:{...n.snapshot,...t}}))}));function rb(){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 sb(){var d;const e=mr(),t=He(p=>p.snapshot),n=k.useRef(null),r=t.threadRef??n,s=!!(t.selectedSessionKey||t.sessionTypeLabel),i=t.sessionDisplayName||t.selectedSessionKey||I("chatSidebarNewTask"),o=!t.selectedSessionKey&&t.uiMessages.length===0&&!t.isSending,a=t.modelOptions.length>0,l=t.isProviderStateResolved&&!a,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:Le("px-5 border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200",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(Ve,{variant:"ghost",size:"icon",className:"rounded-lg shrink-0 text-gray-400 hover:text-destructive",onClick:e.chatThreadManager.deleteSession,disabled:!t.canDeleteSession||t.isDeletePending,children:h.jsx(Ti,{className:"h-4 w-4"})}):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:I("chatModelNoOptions")}),h.jsx("button",{type:"button",onClick:e.chatThreadManager.goToProviders,className:"text-xs font-semibold text-amber-900 underline-offset-2 hover:underline",children:I("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:o?h.jsx(tb,{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:I("chatNoMessages")}):h.jsx("div",{className:"mx-auto w-full max-w-[min(1120px,100%)] px-6 py-5",children:h.jsx(Zx,{uiMessages:t.uiMessages,isSending:t.isSending&&t.isAwaitingAssistantOutput})})}),h.jsx(bx,{})]}):h.jsx(rb,{})}function ai(e){return tn(e??void 0)}function ib(e){return typeof e!="number"||!Number.isFinite(e)?"-":tn(new Date(e))}function ob(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 ab(e){const t=e.schedule;return t.kind==="cron"?t.expr?`cron ${t.expr}`:"cron":t.kind==="every"?`every ${ob(t.everyMs)}`:t.kind==="at"?`at ${ib(t.atMs)}`:"-"}function lb(e){if(!e.payload.deliver)return"-";const t=e.payload.channel??"-",n=e.payload.to??"-";return`${t}:${n}`}function ub(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 cb(e,t){return t==="all"?!0:t==="enabled"?e.enabled:!e.enabled}function db(){var y;const[e,t]=k.useState(""),[n,r]=k.useState("all"),s=Vl({all:!0}),i=Hl(),o=ql(),a=Wl(),{confirm:l,ConfirmDialog:u}=fr(),c=k.useMemo(()=>{var b;return(((b=s.data)==null?void 0:b.jobs)??[]).filter(g=>ub(g,e)).filter(g=>cb(g,n))},[s.data,e,n]),d=async m=>{await l({title:`${I("cronDeleteConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,variant:"destructive",confirmLabel:I("delete")})&&i.mutate({id:m.id})},p=async m=>{const b=!m.enabled;await l({title:b?`${I("cronEnableConfirm")}?`:`${I("cronDisableConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,variant:b?"default":"destructive",confirmLabel:b?I("cronEnable"):I("cronDisable")})&&o.mutate({id:m.id,enabled:b})},f=async m=>{const b=!m.enabled;await l({title:b?`${I("cronRunForceConfirm")}?`:`${I("cronRunConfirm")}?`,description:m.name?`${m.name} (${m.id})`:m.id,confirmLabel:I("cronRunNow")})&&a.mutate({id:m.id,force:b})};return h.jsxs(Mu,{fullHeight:!0,children:[h.jsx(Ru,{title:I("cronPageTitle"),description:I("cronPageDescription"),actions:h.jsx(Ve,{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(El,{className:Le("h-4 w-4",s.isFetching&&"animate-spin")})})}),h.jsx("div",{className:"mb-6",children:h.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[h.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[h.jsx(pr,{value:e,onChange:m=>t(m.target.value),placeholder:I("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(Ql,{value:n,onValueChange:m=>r(m),children:[h.jsx(Gl,{className:"w-full",children:h.jsx(Xl,{placeholder:I("cronStatusLabel")})}),h.jsxs(Yl,{children:[h.jsx(vt,{value:"all",children:I("cronStatusAll")}),h.jsx(vt,{value:"enabled",children:I("cronStatusEnabled")}),h.jsx(vt,{value:"disabled",children:I("cronStatusDisabled")})]})]})}),h.jsxs("div",{className:"text-xs text-gray-500 ml-auto",children:[I("cronTotalLabel"),": ",((y=s.data)==null?void 0:y.total)??0," / ",c.length]})]})}),h.jsx("div",{className:"flex-1 overflow-auto custom-scrollbar",children:s.isLoading?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronLoading")}):c.length===0?h.jsx("div",{className:"text-sm text-gray-400 p-4 text-center",children:I("cronEmpty")}):h.jsx("div",{className:"space-y-4",children:c.map(m=>h.jsx(Jl,{className:"border border-gray-200",children:h.jsx(Zl,{className:"pt-5 pb-5",children:h.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[h.jsxs("div",{className:"min-w-[220px] flex-1",children:[h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h.jsx("span",{className:"text-sm font-semibold text-gray-900",children:m.name||m.id}),h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-gray-100 text-gray-500",children:m.id}),h.jsx("span",{className:Le("text-[10px] font-semibold px-2 py-0.5 rounded-full",m.enabled?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"),children:m.enabled?I("enabled"):I("disabled")}),m.deleteAfterRun&&h.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:I("cronOneShot")})]}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronScheduleLabel"),": ",ab(m)]}),h.jsx("div",{className:"mt-2 text-sm text-gray-700 whitespace-pre-wrap break-words",children:m.payload.message}),h.jsxs("div",{className:"mt-2 text-xs text-gray-500",children:[I("cronDeliverTo"),": ",lb(m)]})]}),h.jsxs("div",{className:"min-w-[220px] text-xs text-gray-500 space-y-2",children:[h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronNextRun"),":"]})," ",ai(m.state.nextRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastRun"),":"]})," ",ai(m.state.lastRunAt)]}),h.jsxs("div",{children:[h.jsxs("span",{className:"font-medium text-gray-700",children:[I("cronLastStatus"),":"]})," ",m.state.lastStatus??"-"]}),m.state.lastError&&h.jsx("div",{className:"text-[11px] text-red-500 break-words",children:m.state.lastError})]}),h.jsxs("div",{className:"flex items-start gap-2 flex-wrap justify-end",children:[h.jsxs(Ve,{variant:"subtle",size:"sm",onClick:()=>f(m),className:"gap-1",children:[h.jsx(Ll,{className:"h-3.5 w-3.5"}),I("cronRunNow")]}),h.jsxs(Ve,{variant:m.enabled?"outline":"primary",size:"sm",onClick:()=>p(m),className:"gap-1",children:[h.jsx(Nl,{className:"h-3.5 w-3.5"}),m.enabled?I("cronDisable"):I("cronEnable")]}),h.jsxs(Ve,{variant:"destructive",size:"sm",onClick:()=>d(m),className:"gap-1",children:[h.jsx(Ti,{className:"h-3.5 w-3.5"}),I("delete")]})]})]})})},m.id))})}),h.jsx(u,{})]})}function Ma(e){const{view:t,routeSessionKey:n,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:i,setSelectedAgentId:o,selectedSessionKeyRef:a,resetStreamState:l,resolveAgentIdFromSessionKey:u}=e;k.useEffect(()=>{if(t==="chat"){if(n){r!==n&&i(n);return}r!==null&&(i(null),l())}},[l,n,r,i,t]),k.useEffect(()=>{const c=r?u(r):null;c&&s!==c&&o(c)},[u,s,r,o]),k.useEffect(()=>{a.current=r},[r,a])}function Ra({view:e,confirmDialog:t}){return h.jsxs("div",{className:"h-full flex",children:[h.jsx(Ky,{}),e==="chat"?h.jsx(sb,{}):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(db,{})})}):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(bu,{forcedType:"skills"})})})}),t]})}const lr="sid_";function Aa(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 hb(e){const t=Math.random().toString(36).slice(2,8);return`agent:${e}:ui:direct:web-${Date.now().toString(36)}${t}`}function fb(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`${lr}${r}`}function pb(e){if(!e.startsWith(lr))return null;const t=e.slice(lr.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 Ea(e){if(!e)return null;const t=pb(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function gb(e){return`/chat/${fb(e)}`}function mb(e){const t=e.trim();return t.length>0?t:null}function yb(e){return e??null}class La{constructor(t){this.updateSession=t,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{const n=V.getState().snapshot,s=ie.getState().snapshot.selectedSessionKey;s&&this.enqueue({sessionKey:s,patch:{preferredModel:mb(n.selectedModel),preferredThinking:yb(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 xb{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.sessionPreferenceSync=new La(Bn),this.hasSnapshotChanges=r=>{const s=V.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.isSameStringArray=(r,s)=>r.length===s.length&&r.every((i,o)=>i===s[o]),this.syncComposerSnapshot=r=>{V.getState().setSnapshot({composerNodes:r,draft:Zn(r),selectedSkills:er(r)})},this.syncSnapshot=r=>{if(this.hasSnapshotChanges(r)&&(V.getState().setSnapshot(r),Object.prototype.hasOwnProperty.call(r,"modelOptions")||Object.prototype.hasOwnProperty.call(r,"selectedModel")||Object.prototype.hasOwnProperty.call(r,"selectedThinkingLevel"))){const{selectedModel:s}=V.getState().snapshot;this.reconcileThinkingForModel(s)}},this.setDraft=r=>{const s=V.getState().snapshot.draft,i=this.resolveUpdateValue(s,r);i!==s&&this.syncComposerSnapshot(ba(i))},this.setComposerNodes=r=>{const s=V.getState().snapshot.composerNodes,i=this.resolveUpdateValue(s,r);Object.is(i,s)||this.syncComposerSnapshot(i)},this.setPendingSessionType=r=>{const s=V.getState().snapshot.pendingSessionType,i=this.resolveUpdateValue(s,r);i!==s&&V.getState().setSnapshot({pendingSessionType:i})},this.send=async()=>{const r=V.getState().snapshot,s=ie.getState().snapshot,i=r.draft.trim();if(!i)return;const{selectedSkills:o,composerNodes:a}=r,l=!!s.selectedSessionKey,u=s.selectedSessionKey??hb(s.selectedAgentId);l||this.uiManager.goToSession(u,{replace:!0}),this.setComposerNodes(Fr()),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:o,restoreDraftOnError:!0,composerNodes:a})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=r=>{const s=V.getState().snapshot.selectedModel,i=this.resolveUpdateValue(s,r);i!==s&&(V.getState().setSnapshot({selectedModel:i}),this.reconcileThinkingForModel(i))},this.setSelectedThinkingLevel=r=>{const s=V.getState().snapshot.selectedThinkingLevel,i=this.resolveUpdateValue(s,r);i!==s&&V.getState().setSnapshot({selectedThinkingLevel:i})},this.selectSessionType=r=>{const s=Oe(r);V.getState().setSnapshot({selectedSessionType:s,pendingSessionType:s}),this.syncRemoteSessionType(s)},this.setSelectedSkills=r=>{const s=V.getState().snapshot,{selectedSkills:i}=s,o=this.resolveUpdateValue(i,r);this.isSameStringArray(o,i)||this.syncComposerSnapshot(Sa(s.composerNodes,o,s.skillRecords))},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=ie.getState().snapshot,{selectedSessionKey:i}=s;if(!i)return;const o=s.sessions.find(a=>a.key===i);o!=null&&o.sessionTypeMutable&&Oe(o.sessionType)!==r&&await Bn(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=V.getState().snapshot,r=n.modelOptions.find(o=>o.value===t),{selectedThinkingLevel:s}=n,i=this.resolveThinkingForModel(r,s);i!==s&&V.getState().setSnapshot({selectedThinkingLevel:i})}}const bb={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 Sb(e,t){return{driver:"nextbot-stream",mode:"send",payload:e,requestedSkills:t}}function kb(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 vb(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 Na{constructor(){this.syncSnapshot=t=>{const n=tr.getState().snapshot,r=t.sessionRunStatusByKey;(!r||vb(n.sessionRunStatusByKey,r))&&(t.isLocallyRunning===void 0||Object.is(n.isLocallyRunning,t.isLocallyRunning))&&(t.activeBackendRunId===void 0||Object.is(n.activeBackendRunId,t.activeBackendRunId))||tr.getState().setSnapshot(t)}}}class Pa{constructor(t,n){this.uiManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=r=>{const s=ie.getState().snapshot;for(const[i,o]of Object.entries(r))if(!Object.is(s[i],o))return!0;return!1},this.resolveUpdateValue=(r,s)=>typeof s=="function"?s(r):s,this.syncSnapshot=r=>{this.hasSnapshotChanges(r)&&ie.getState().setSnapshot(r)},this.setSelectedAgentId=r=>{const s=ie.getState().snapshot.selectedAgentId,i=this.resolveUpdateValue(s,r);i!==s&&ie.getState().setSnapshot({selectedAgentId:i})},this.setSelectedSessionKey=r=>{const s=ie.getState().snapshot.selectedSessionKey,i=this.resolveUpdateValue(s,r);i!==s&&ie.getState().setSnapshot({selectedSessionKey:i})},this.createSession=r=>{const{snapshot:s}=V.getState(),{defaultSessionType:i}=s,o=i||"native",a=typeof r=="string"&&r.trim().length>0?r.trim():o;this.streamActionsManager.resetStreamState(),V.getState().setSnapshot({pendingSessionType:a}),this.uiManager.goToChatRoot()},this.selectSession=r=>{this.uiManager.goToSession(r)},this.setQuery=r=>{const s=ie.getState().snapshot.query,i=this.resolveUpdateValue(s,r);i!==s&&ie.getState().setSnapshot({query:i})}}}const jn=async()=>{},li=()=>{};class ja{constructor(){this.actions={sendMessage:jn,stopCurrentRun:jn,resumeRun:jn,resetStreamState:li,applyHistoryMessages:li},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 wb=async()=>{};class Cb{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:wb},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=He.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&He.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=ie.getState();if(!(!s||!await this.uiManager.confirm({title:I("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:I("delete")}))){He.getState().setSnapshot({isDeletePending:!0});try{await eu(s),this.streamActionsManager.resetStreamState(),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{He.getState().setSnapshot({isDeletePending:!1})}}}}}const Tb=async e=>!1;class Da{constructor(){this.state={pathname:""},this.actions={navigate:null,confirm:Tb},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(gb(t),n)}}}function Ib(e){return e.delta?e.started?[{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[{type:X.TEXT_START,messageId:e.messageId},{type:X.TEXT_DELTA,messageId:e.messageId,delta:e.delta}]:[]}function Mb(e){return!1}function Rb(e){var n,r;return((r=(n=e.message)==null?void 0:n.role)==null?void 0:r.toLowerCase().trim())==="assistant"}function Ab(e){var o;const{event:t,messageId:n}=e,r=t.message;if(!r)return[];const s=(o=r.role)==null?void 0:o.toLowerCase().trim();if(!s)return[];const i=[];if(typeof r.reasoning_content=="string"&&r.reasoning_content.trim()&&(i.push({type:X.REASONING_START,messageId:n}),i.push({type:X.REASONING_DELTA,messageId:n,delta:r.reasoning_content.trim()}),i.push({type:X.REASONING_END,messageId:n})),Array.isArray(r.tool_calls))for(let a=0;a<r.tool_calls.length;a+=1){const l=r.tool_calls[a];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}-${a}`,y=typeof(d==null?void 0:d.name)=="string"?d.name:typeof u.name=="string"?u.name:"tool",m=(d==null?void 0:d.arguments)??u.arguments??"",b=typeof m=="string"?m:JSON.stringify(m??{});i.push({type:X.TOOL_CALL_START,messageId:n,toolCallId:f,toolName:y}),i.push({type:X.TOOL_CALL_ARGS,toolCallId:f,args:b}),i.push({type:X.TOOL_CALL_END,toolCallId:f})}if(s==="tool"||s==="tool_result"||s==="toolresult"||s==="function"){const a=typeof r.tool_call_id=="string"?r.tool_call_id.trim():"";a&&i.push({type:X.TOOL_CALL_RESULT,toolCallId:a,content:r.content})}return i}function _a(){return`stream-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Eb(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 Lb(e){let t="",n=null;const s=await Ni.openStream({method:"POST",path:"/api/chat/turn/stream",body:Eb(e.item,e.requestedSkills),signal:e.signal,onEvent:i=>{var o;if(i.name==="ready"){const a=i.payload??{};typeof a.sessionKey=="string"&&a.sessionKey.trim()&&(t=a.sessionKey),e.onReady(a);return}if(i.name==="delta"){e.onDelta(i.payload??{delta:""});return}if(i.name==="session_event"){e.onSessionEvent({data:i.payload});return}if(i.name==="final"){const a=i.payload??{};n={sessionKey:typeof a.sessionKey=="string"&&a.sessionKey.trim()?a.sessionKey:t,reply:typeof a.reply=="string"?a.reply:""};return}if(i.name==="error"){const a=i.payload??{};throw new Error(((o=a.message)==null?void 0:o.trim())||"chat stream failed")}}}).finished;return n!==null?n:{sessionKey:typeof(s==null?void 0:s.sessionKey)=="string"&&s.sessionKey.trim()?s.sessionKey:t,reply:typeof(s==null?void 0:s.reply)=="string"?s.reply:""}}async function Nb(e){let t="",n=null;const r=new URLSearchParams;typeof e.fromEventIndex=="number"&&r.set("fromEventIndex",String(Math.max(0,Math.trunc(e.fromEventIndex))));const s=`/api/chat/runs/${encodeURIComponent(e.runId)}/stream`+(r.size>0?`?${r.toString()}`:""),o=await Ni.openStream({method:"GET",path:s,signal:e.signal,onEvent:a=>{var l;if(a.name==="ready"){const u=a.payload??{};typeof u.sessionKey=="string"&&u.sessionKey.trim()&&(t=u.sessionKey),e.onReady(u);return}if(a.name==="delta"){e.onDelta(a.payload??{delta:""});return}if(a.name==="session_event"){e.onSessionEvent({data:a.payload});return}if(a.name==="final"){const u=a.payload??{};n={sessionKey:typeof u.sessionKey=="string"&&u.sessionKey.trim()?u.sessionKey:t,reply:typeof u.reply=="string"?u.reply:""};return}if(a.name==="error"){const u=a.payload??{};throw new Error(((l=u.message)==null?void 0:l.trim())||"chat stream failed")}}}).finished;return n!==null?n:{sessionKey:typeof(o==null?void 0:o.sessionKey)=="string"&&o.sessionKey.trim()?o.sessionKey:t,reply:typeof(o==null?void 0:o.reply)=="string"?o.reply:""}}async function Pb(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 Dn(r)))return;const s=await jb(e);for(const i of s){if(n.has(i))continue;if(n.add(i),await Dn(i))return}if(r&&await Dn(r))return}catch{}}async function Dn(e){const t=e.trim();if(!t)return!1;try{return(await tu({runId:t})).stopped===!0}catch{return!1}}async function jb(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 o=await Db(e,t);if(o.length>0)return o;i<n-1&&await _b(r)}return[]}async function Db(e,t){try{const n=await nu({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 _b(e){return new Promise(t=>{window.setTimeout(t,e)})}function Oa(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 Ob(e){var m;const t=new Set(["tool","tool_result","toolresult","function"]),n=[];let r=0,s=0,i=null;const o=(b,g)=>(r+=1,`history-${b}-${g||"unknown"}-${r}`),a=b=>{const g=typeof b=="string"?b:JSON.stringify(b??{});try{return{args:g,parsedArgs:JSON.parse(g)}}catch{return{args:g}}},l=(b,g)=>{for(let v=b.length-1;v>=0;v-=1){const w=b[v];if(w.type==="tool-invocation"&&w.toolInvocation.toolCallId===g)return v}return-1},u=b=>i?(i={...i,meta:{...i.meta,timestamp:b}},i):(s+=1,i={id:`history-assistant-${s}-${b||"unknown"}`,role:"assistant",parts:[],meta:{source:"history",status:"final",timestamp:b}},i),c=()=>{i&&(i.parts.length>0&&n.push(i),i=null)},d=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"text",text:g}]},p=(b,g)=>{if(!g)return;const v=u(b);v.parts=[...v.parts,{type:"reasoning",reasoning:g,details:[]}]},f=b=>{const g=u(b.timestamp),v=l(g.parts,b.toolCallId),w={type:"tool-invocation",toolInvocation:{status:ue.CALL,toolCallId:b.toolCallId,toolName:b.toolName,args:b.args,parsedArgs:b.parsedArgs}};if(v>=0){g.parts=[...g.parts.slice(0,v),w,...g.parts.slice(v+1)];return}g.parts=[...g.parts,w]},y=b=>{if(!b.toolCallId)return;const g=u(b.timestamp),v=l(g.parts,b.toolCallId);if(v<0){g.parts=[...g.parts,{type:"tool-invocation",toolInvocation:{status:ue.RESULT,toolCallId:b.toolCallId,toolName:b.toolName,args:"{}",parsedArgs:void 0,result:b.result}}];return}const w=g.parts[v];w.type==="tool-invocation"&&(g.parts=[...g.parts.slice(0,v),{...w,toolInvocation:{...w.toolInvocation,status:ue.RESULT,result:b.result}},...g.parts.slice(v+1)])};for(const b of e){const g=(m=b.role)==null?void 0:m.toLowerCase().trim();if(!g)continue;const v=b.timestamp;if(g==="user"||g==="system"||g==="data"){c();const w=Hr(b.content).trim();if(!w)continue;n.push({id:o(g,v),role:g,parts:[{type:"text",text:w}],meta:{source:"history",status:"final",timestamp:v}});continue}if(g==="assistant"){const w=Hr(b.content).trim();if(w&&d(v,w),typeof b.reasoning_content=="string"&&b.reasoning_content.trim()&&p(v,b.reasoning_content.trim()),Array.isArray(b.tool_calls))for(const N of b.tool_calls){if(!N||typeof N!="object")continue;const j=N,T=j.function,O=typeof T=="object"&&T?T:null,B=typeof j.id=="string"?j.id.trim():"";if(!B)continue;const $=typeof(O==null?void 0:O.name)=="string"?O.name:typeof j.name=="string"?j.name:"tool",C=a((O==null?void 0:O.arguments)??j.arguments??"");f({timestamp:v,toolCallId:B,toolName:$,args:C.args,parsedArgs:C.parsedArgs})}continue}if(t.has(g)){const w=typeof b.tool_call_id=="string"?b.tool_call_id.trim():"",N=typeof b.name=="string"&&b.name.trim()?b.name.trim():"tool";y({timestamp:v,toolCallId:w,toolName:N,result:b.content})}}return c(),n}function Fb(){const e=Date.now().toString(36),t=Math.random().toString(36).slice(2,10);return`run-${e}-${t}`}function zb(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(o=>typeof o=="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,o=typeof n.sessionKey=="string"?n.sessionKey.trim():"",a=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}:{},...o?{sessionKey:o}:{},...a?{agentId:a}:{},...typeof l=="boolean"?{stopSupported:l}:{},...u?{stopReason:u}:{}}}return null}function Bb(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 $b(e){var n;return e.mode!=="send"||((n=e.payload.runId)==null?void 0:n.trim())?e:{...e,payload:{...e.payload,runId:Fb()}}}function Kb(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 Ub(){return{deltaMessageId:_a(),deltaStarted:!1,deltaClosed:!1,hasAssistantSessionEvent:!1,hasAssistantOutput:!1}}function Vb(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 Hb(e,t){return{driver:"nextbot-stream",kind:"final",sessionKey:e.sessionKey,reply:e.reply,hasAssistantSessionEvent:t}}function ui(e,t,n){e({type:X.RUN_METADATA,runId:t,metadata:n})}function ci(e,t){!e.deltaStarted||e.deltaClosed||(t({type:X.TEXT_END,messageId:e.deltaMessageId}),e.deltaClosed=!0)}function qb(e,t,n){const r=Ib({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 Wb(e,t,n){Mb(n.data),Rb(n.data)&&(e.hasAssistantSessionEvent=!0);for(const r of Ab({event:n.data,messageId:e.deltaMessageId}))t(r)}function Qb(e,t,n){const r=n.trim();if(e.hasAssistantOutput||!r)return;const s=_a();t({type:X.TEXT_START,messageId:s}),t({type:X.TEXT_DELTA,messageId:s,delta:r}),t({type:X.TEXT_END,messageId:s})}class Gb{constructor(){this.activeAbortController=null,this.activeRunState=null,this.buildMissingMetadataObservable=t=>new Yt(n=>{n.next({type:X.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:o}=t;return n.mode==="send"?Lb({item:n.payload,requestedSkills:n.requestedSkills,signal:r,onReady:s,onDelta:i,onSessionEvent:o}):Nb({runId:n.runId,fromEventIndex:n.fromEventIndex,signal:r,onReady:s,onDelta:i,onSessionEvent:o})},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 Yt(i=>{const o=Ub();let a=!1;const l=c=>{a||i.next(c)};return l({type:X.RUN_STARTED,runId:n}),this.openRunStream({metadata:t,signal:r.signal,onReady:c=>{this.activeRunState&&Kb(this.activeRunState,c),ui(l,n,Vb(c))},onDelta:c=>{qb(o,l,c)},onSessionEvent:c=>{Wb(o,l,c)}}).then(c=>{ci(o,l),Qb(o,l,c.reply),ui(l,n,Hb(c,o.hasAssistantSessionEvent)),l({type:X.RUN_FINISHED,runId:n}),i.complete()}).catch(c=>{ci(o,l),ar(c)||l({type:X.RUN_ERROR,runId:n,error:c instanceof Error?c.message:String(c)}),i.complete()}).finally(()=>{this.finalizeRunState(r,s)}),()=>{a=!0,r.abort(),this.activeAbortController===r&&(this.activeAbortController=null)}}),this.abortRun=()=>{var n;const t=this.activeRunState;t!=null&&t.backendStopSupported&&Pb(t),(n=this.activeAbortController)==null||n.abort(),this.activeAbortController=null,this.activeRunState=null},this.run=t=>{const n=zb(t),r=typeof t.runId=="string"&&t.runId.trim()?t.runId:`run-${Date.now()}`;if(!n)return this.buildMissingMetadataObservable(r);const s=$b(n);this.abortRun();const i=new AbortController;this.activeAbortController=i;const o=Bb(s);return this.activeRunState=o,this.createRunObservable({metadata:s,clientRunId:r,abortController:i,runState:o})}}}class Xb{constructor(){this.chatUiManager=new Da,this.runtimeAgent=new Gb,this.chatController=new $x({agent:this.runtimeAgent,getToolDefs:()=>[],getContexts:()=>[],getToolExecutor:()=>{}},{metadataParsers:bb}),this.chatStreamActionsManager=new ja,this.chatInputManager=new xb(this.chatUiManager,this.chatStreamActionsManager),this.chatSessionListManager=new Pa(this.chatUiManager,this.chatStreamActionsManager),this.chatRunStatusManager=new Na,this.chatThreadManager=new Cb(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}}function Kt(e){const[t,n]=k.useState(e.getValue());return k.useEffect(()=>{const r=e.subscribe(n);return()=>r.unsubscribe()},[e]),t}function Yb(e,t){const[n,r]=k.useState(t);return k.useEffect(()=>{const s=e.subscribe(r);return()=>s.unsubscribe()},[e]),n}function Jb(e,t){const n=k.useRef(e);k.useEffect(()=>{n.current=e});const r=k.useRef(null);k.useEffect(()=>{t.setCallbacks({onRunSettled:async({sourceSessionId:g,resultSessionId:v})=>{const w=n.current;await w.refetchSessions();const N=w.selectedSessionKeyRef.current;(!N||N===g||v&&N===v)&&await w.refetchHistory()},onRunError:({sourceMessage:g,restoreDraft:v})=>{v&&n.current.setDraft(w=>w.trim().length===0&&g?g:w)},onSessionChanged:g=>{n.current.setSelectedSessionKey(v=>v===g?v:g)}})},[t]);const s=Yb(t.messages$,t.getMessages()),i=Kt(t.isAgentResponding$),o=Kt(t.isAwaitingResponse$),a=Kt(t.activeRun$),l=Kt(t.lastError$),u=(a==null?void 0:a.remoteRunId)??null,c=_x(a),d=!!(a&&(c===null||a.remoteStopCapable&&!u)),p=k.useCallback(async g=>{const v=Oa(g.requestedSkills),w=Sb(g,v);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=k.useCallback(async g=>{var j,T;const v=(j=g.runId)==null?void 0:j.trim(),w=(T=g.sessionKey)==null?void 0:T.trim();if(!v||!w)return;const N=kb(g);await t.resume({remoteRunId:v,sessionId:w,agentId:g.agentId,metadata:N,stopCapable:g.stopSupported,stopReason:g.stopReason})},[t]),y=k.useCallback(async()=>{await t.stop()},[t]),m=k.useCallback(()=>{r.current=null,t.reset()},[t]),b=k.useCallback((g,v)=>{if(!!(t.activeRun$.getValue()||t.isAgentResponding$.getValue()))return;const N=n.current.selectedSessionKeyRef.current;if(N!==r.current&&(r.current=N,t.getMessages().length>0&&t.setMessages([])),!N){t.getMessages().length>0&&t.setMessages([]);return}v!=null&&v.isLoading&&g.length===0||t.setMessages(Ob(g))},[t]);return{uiMessages:s,isSending:i,isAwaitingAssistantOutput:o,canStopCurrentRun:d,stopDisabledReason:c,lastSendError:l,activeBackendRunId:u,sendMessage:p,stopCurrentRun:y,resumeRun:f,resetStreamState:m,applyHistoryMessages:b}}function Zb({view:e}){var Ie,Pe,Xe;const[t]=k.useState(()=>new Xb),n=ie(ce=>ce.snapshot.query),r=ie(ce=>ce.snapshot.selectedSessionKey),s=ie(ce=>ce.snapshot.selectedAgentId),i=V(ce=>ce.snapshot.pendingSessionType),o=V(ce=>ce.snapshot.selectedModel),{confirm:a,ConfirmDialog:l}=fr(),u=en(),c=Ii(),{sessionId:d}=Mi(),p=k.useRef(null),f=k.useRef(r),y=k.useMemo(()=>Ea(d),[d]),{sessionsQuery:m,installedSkillsQuery:b,chatCapabilitiesQuery:g,historyQuery:v,isProviderStateResolved:w,modelOptions:N,sessions:j,skillRecords:T,selectedSession:O,historyMessages:B,sessionTypeOptions:$,defaultSessionType:C,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_}=Ou({query:n,selectedSessionKey:r,selectedAgentId:s,currentSelectedModel:o,pendingSessionType:i,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),{uiMessages:A,isSending:K,isAwaitingAssistantOutput:L,canStopCurrentRun:Q,stopDisabledReason:ae,lastSendError:x,activeBackendRunId:oe,sendMessage:re,stopCurrentRun:S,resumeRun:he,resetStreamState:ke,applyHistoryMessages:se}=Jb({selectedSessionKeyRef:f,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setDraft:t.chatInputManager.setDraft,setComposerNodes:t.chatInputManager.setComposerNodes,refetchSessions:m.refetch,refetchHistory:v.refetch},t.chatController);k.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:re,stopCurrentRun:S,resumeRun:he,resetStreamState:ke,applyHistoryMessages:se})},[se,t,ke,he,re,S]);const{sessionRunStatusByKey:pe}=Eu({view:e,selectedSessionKey:r,activeBackendRunId:oe,isLocallyRunning:K||!!oe,resumeRun:t.chatStreamActionsManager.resumeRun});Ma({view:e,routeSessionKey:y,selectedSessionKey:r,selectedAgentId:s,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:f,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Aa}),k.useEffect(()=>{t.chatStreamActionsManager.applyHistoryMessages(B,{isLoading:v.isLoading})},[B,v.isLoading,t]),k.useEffect(()=>{t.chatUiManager.syncState({pathname:u.pathname}),t.chatUiManager.bindActions({navigate:c,confirm:a})},[a,u.pathname,c,t]);const xe=O?Qi(O):void 0,Te=((Ie=$.find(ce=>ce.value===R))==null?void 0:Ie.label)??lt(R);return k.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:m.refetch})},[t,m.refetch]),k.useEffect(()=>{var ce,W;t.chatInputManager.syncSnapshot({isProviderStateResolved:w,defaultSessionType:C,canStopGeneration:Q,stopDisabledReason:ae,stopSupported:((ce=g.data)==null?void 0:ce.stopSupported)??!1,stopReason:(W=g.data)==null?void 0:W.stopReason,sendError:x,isSending:K,modelOptions:N,sessionTypeOptions:$,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,skillRecords:T,isSkillsLoading:b.isLoading}),t.chatSessionListManager.syncSnapshot({sessions:j,query:n,isLoading:m.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:pe,isLocallyRunning:K||!!oe,activeBackendRunId:oe}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:w,modelOptions:N,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_,sessionTypeLabel:Te,selectedSessionKey:r,sessionDisplayName:xe,canDeleteSession:!!O,threadRef:p,isHistoryLoading:v.isLoading,uiMessages:A,isSending:K,isAwaitingAssistantOutput:L})},[oe,E,Q,xe,Te,(Pe=g.data)==null?void 0:Pe.stopReason,(Xe=g.data)==null?void 0:Xe.stopSupported,C,v.isLoading,b.isLoading,L,w,K,x,N.length,N,t,n,O,r,R,pe,$,z,_,j,m.isLoading,T,ae,p,A]),h.jsx(Xi,{presenter:t,children:h.jsx(Ra,{view:e,confirmDialog:h.jsx(l,{})})})}function di(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*eS(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{value:i,done:o}=await t.read();if(o)break;r+=n.decode(i,{stream:!0});const{frames:a,rest:l}=hi(r);r=l;for(const u of a)yield u}r+=n.decode();const{frames:s}=hi(r,!0);for(const i of s)yield i}finally{t.releaseLock()}}function hi(e,t=!1){const n=e.split(/\r?\n\r?\n/),r=n.pop()??"",s=[];for(const i of n){const o=di(i);o&&s.push(o)}if(t&&r.trim()){const i=di(r);return i&&s.push(i),{frames:s,rest:""}}return{frames:s,rest:r}}var fi="/ncp/agent",tS="ncp-http-agent-client",Fa=class extends Error{constructor(t,n=!1){super(t.message);F(this,"ncpError");F(this,"alreadyPublished");this.name=`NcpHttpAgentClientError(${t.code})`,this.ncpError=t,this.alreadyPublished=n}};function nS(e){const t=e.trim();if(!t)throw new Error("NcpHttpAgentClient requires a non-empty baseUrl.");return new URL(t)}function rS(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 sS(e){const t=(e??fi).trim();if(!t)return fi;const n=t.startsWith("/")?t:`/${t}`;return n.endsWith("/")?n.slice(0,-1):n}async function pi(e){try{return(await e.text()).trim()}catch{return""}}function gi(e){if(za(e))return e.ncpError;if(iS(e))return e;const t=e instanceof Error?e.message:String(e??"Unknown error");return{code:Ba(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function _n(e,t={}){return new Fa(e,t.alreadyPublished??!1)}function iS(e){return zr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function zr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function za(e){return e instanceof Fa}var oS={"config-error":"config-error","auth-error":"auth-error","runtime-error":"runtime-error","timeout-error":"timeout-error","abort-error":"abort-error"};function Ba(e){if(!e)return"runtime-error";const t=oS[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 aS(e){const t=$a(e);return!t||typeof t.type!="string"||!t.type.trim()?null:t}function lS(e){const t=$a(e);if(!t)return{code:"runtime-error",message:e||"Unknown stream error."};const n=typeof t.code=="string"?t.code:void 0,r=Ba(n),s=zr(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 $a(e){try{const t=JSON.parse(e);return zr(t)?t:null}catch{return null}}var uS=["text","file","source","step-start","reasoning","tool-invocation","card","rich-text","action","extension"],cS=class{constructor(e){F(this,"manifest");F(this,"baseUrl");F(this,"basePath");F(this,"fetchImpl");F(this,"defaultHeaders");F(this,"subscribers",new Set);F(this,"activeControllers",new Set);F(this,"started",!1);var t;this.baseUrl=nS(e.baseUrl),this.basePath=sS(e.basePath),this.fetchImpl=rS(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:"custom",endpointId:((t=e.endpointId)==null?void 0:t.trim())||tS,version:"0.1.0",supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:uS,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 pi(n)}`)}catch(n){if(t.signal.aborted)return;const r=gi(n);throw this.publish({type:ne.EndpointError,payload:r}),_n(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 pi(n)}`);if(!n.body)throw new Error("NCP stream response has no body.");for await(const r of eS(n.body)){if(t.signal.aborted)return;this.handleSseFrame(r)}}catch(n){if(t.signal.aborted)return;if(za(n))throw n;const r=gi(n);throw this.publish({type:ne.EndpointError,payload:r}),_n(r)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event==="ncp-event"){const t=aS(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=lS(e.data);throw this.publish({type:ne.EndpointError,payload:t}),_n(t,{alreadyPublished:!0})}}};function dS(){return(e,t)=>fetch(e,{credentials:"include",...t})}const hS=new Set(["off","minimal","low","medium","high","adaptive","xhigh"]);function fS(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return String(e??"")}}function Ee(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 pS(e){const t=cn(e);return t?Ee(t.preferred_model)??Ee(t.preferredModel)??Ee(t.model):null}function gS(e){const t=cn(e);if(!t)return null;const n=Ee(t.preferred_thinking)??Ee(t.thinking)??Ee(t.thinking_level)??Ee(t.thinkingLevel);if(!n)return null;const r=n.toLowerCase();return hS.has(r)?r:null}function mS(e){const t=cn(e);return t?Ee(t.label):null}function yS(e){const t=cn(e);return t?Ee(t.session_type)??Ee(t.sessionType)??"native":"native"}function xS(e){return e.state==="result"?ue.RESULT:e.state==="partial-call"?ue.PARTIAL_CALL:ue.CALL}function bS(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",...n.name?{name:n.name}:{},mimeType:n.mimeType??"application/octet-stream",data:n.contentBase64,...n.url?{url:n.url}:{},...typeof n.sizeBytes=="number"?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type==="file"&&n.url){t.push({type:"file",...n.name?{name:n.name}:{},mimeType:n.mimeType??"application/octet-stream",data:"",url:n.url,...typeof n.sizeBytes=="number"?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type==="step-start"){t.push({type:"step-start"});continue}n.type==="tool-invocation"&&t.push({type:"tool-invocation",toolInvocation:{status:xS(n),toolCallId:n.toolCallId??`${n.toolName}-${Math.random().toString(36).slice(2,8)}`,toolName:n.toolName,args:fS(n.args),result:n.result}})}return t}function SS(e){return e==="service"?"system":e==="tool"?"assistant":e}function kS(e){return{id:e.id,role:SS(e.role),parts:bS(e.parts),meta:{source:"stream",status:e.status,sessionKey:e.sessionId,timestamp:e.timestamp}}}function vS(e){return e.map(kS)}function wS(e){const t=mS(e),n=pS(e),r=gS(e);return{key:e.sessionId,createdAt:e.updatedAt,updatedAt:e.updatedAt,...t?{label:t}:{},...n?{preferredModel:n}:{},...r?{preferredThinking:r}:{},sessionType:yS(e),sessionTypeMutable:!1,messageCount:e.messageCount}}function CS(e){return e.map(wS)}function TS(e){const t=new Map;for(const r of e.summaries)r.status==="running"&&t.set(r.sessionId,"running");const n=Ee(e.activeSessionId);return e.isLocallyRunning&&n&&t.set(n,"running"),t}function mi(){return`ncp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function IS(){return Pl({queryKey:["ncp-session-types"],queryFn:ru,staleTime:1e4,retry:!1})}function MS(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>r.key.toLowerCase().includes(n)):e}function RS(e){if(!e.supportedModels||e.supportedModels.length===0)return e.modelOptions;const t=new Set(e.supportedModels),n=e.modelOptions.filter(r=>t.has(r.value));return n.length>0?n:e.modelOptions}function AS(e){var N,j,T,O,B,$,C,R;const t=Ri(),n=Ai(),r=su({limit:200}),s=IS(),i=Pi("skill"),o=(t.isFetched||t.isSuccess)&&(n.isFetched||n.isSuccess),a=k.useMemo(()=>{const E=Di({meta:n.data,config:t.data,onlyConfigured:!0}),z=new Set,_=[];for(const A of E)for(const K of A.models){const L=_i(A.prefix,K);!L||z.has(L)||(z.add(L),_.push({value:L,modelLabel:K,providerLabel:A.displayName,thinkingCapability:Oi(A.modelThinking,K,A.aliases)}))}return _.sort((A,K)=>{const L=A.providerLabel.localeCompare(K.providerLabel);return L!==0?L:A.modelLabel.localeCompare(K.modelLabel)})},[n.data,t.data]),l=k.useMemo(()=>{var E;return((E=r.data)==null?void 0:E.sessions)??[]},[(N=r.data)==null?void 0:N.sessions]),u=k.useMemo(()=>CS(l),[l]),c=k.useMemo(()=>MS(u,e.query),[u,e.query]),d=k.useMemo(()=>u.find(E=>E.key===e.selectedSessionKey)??null,[u,e.selectedSessionKey]),p=k.useMemo(()=>{var E;return((E=i.data)==null?void 0:E.records)??[]},[(j=i.data)==null?void 0:j.records]),f=Bi({selectedSession:d,selectedSessionKey:e.selectedSessionKey,pendingSessionType:e.pendingSessionType,setPendingSessionType:e.setPendingSessionType,sessionTypesData:s.data}),y=k.useMemo(()=>{var E;return RS({modelOptions:a,supportedModels:(E=f.selectedSessionTypeOption)==null?void 0:E.supportedModels})},[a,(T=f.selectedSessionTypeOption)==null?void 0:T.supportedModels]),m=k.useMemo(()=>Ui({sessions:u,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[u,e.selectedSessionKey,f.selectedSessionType]),b=k.useMemo(()=>y.find(E=>E.value===e.currentSelectedModel),[y,e.currentSelectedModel]),g=k.useMemo(()=>{var E;return((E=b==null?void 0:b.thinkingCapability)==null?void 0:E.supported)??[]},[(O=b==null?void 0:b.thinkingCapability)==null?void 0:O.supported]),v=k.useMemo(()=>{var E;return((E=b==null?void 0:b.thinkingCapability)==null?void 0:E.default)??null},[(B=b==null?void 0:b.thinkingCapability)==null?void 0:B.default]),w=k.useMemo(()=>Vi({sessions:u,selectedSessionKey:e.selectedSessionKey,sessionType:f.selectedSessionType}),[u,e.selectedSessionKey,f.selectedSessionType]);return qi({modelOptions:y,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!d,selectedSessionPreferredModel:d==null?void 0:d.preferredModel,fallbackPreferredModel:(($=f.selectedSessionTypeOption)==null?void 0:$.recommendedModel)??m,defaultModel:((C=f.selectedSessionTypeOption)==null?void 0:C.recommendedModel)??((R=t.data)==null?void 0:R.agents.defaults.model),setSelectedModel:e.setSelectedModel}),Wi({supportedThinkingLevels:g,selectedSessionKey:e.selectedSessionKey,selectedSessionExists:!!d,selectedSessionPreferredThinking:(d==null?void 0:d.preferredThinking)??null,fallbackPreferredThinking:w??null,defaultThinkingLevel:v,setSelectedThinkingLevel:e.setSelectedThinkingLevel}),{configQuery:t,configMetaQuery:n,sessionsQuery:r,sessionTypesQuery:s,installedSkillsQuery:i,isProviderStateResolved:o,modelOptions:y,sessionSummaries:l,sessions:c,skillRecords:p,selectedSession:d,...f}}class ES{constructor(t,n,r){this.uiManager=t,this.streamActionsManager=n,this.getDraftSessionId=r,this.sessionPreferenceSync=new La(Ei),this.buildAttachmentSignature=s=>[s.attachmentUri??"",s.url??"",s.name,s.mimeType,String(s.sizeBytes),s.contentBase64??""].join(":"),this.hasSnapshotChanges=s=>{const i=V.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.resolveUpdateValue=(s,i)=>typeof i=="function"?i(s):i,this.isSameStringArray=(s,i)=>s.length===i.length&&s.every((o,a)=>o===i[a]),this.syncComposerSnapshot=s=>{const i=V.getState().snapshot.attachments,o=Ny(s,i);V.getState().setSnapshot({composerNodes:s,attachments:o,draft:Zn(s),selectedSkills:er(s)})},this.syncComposerSnapshotWithAttachments=(s,i)=>{V.getState().setSnapshot({composerNodes:s,attachments:i,draft:Zn(s),selectedSkills:er(s)})},this.dedupeAttachments=s=>{const i=new Set,o=[];for(const a of s){const l=this.buildAttachmentSignature(a);i.has(l)||(i.add(l),o.push(a))}return o},this.syncSnapshot=s=>{if(this.hasSnapshotChanges(s)&&(V.getState().setSnapshot(s),Object.prototype.hasOwnProperty.call(s,"modelOptions")||Object.prototype.hasOwnProperty.call(s,"selectedModel")||Object.prototype.hasOwnProperty.call(s,"selectedThinkingLevel"))){const{selectedModel:i}=V.getState().snapshot;this.reconcileThinkingForModel(i)}},this.setDraft=s=>{const i=V.getState().snapshot.draft,o=this.resolveUpdateValue(i,s);o!==i&&this.syncComposerSnapshot(ba(o))},this.setComposerNodes=s=>{const i=V.getState().snapshot.composerNodes,o=this.resolveUpdateValue(i,s);Object.is(o,i)||this.syncComposerSnapshot(o)},this.addAttachments=s=>{if(s.length===0)return[];const i=V.getState().snapshot,o=new Set(i.attachments.map(this.buildAttachmentSignature)),a=this.dedupeAttachments([...i.attachments,...s]),l=a.filter(c=>!o.has(this.buildAttachmentSignature(c)));if(l.length===0)return[];const u=qs(i.composerNodes,a);return this.syncComposerSnapshotWithAttachments(u,a),l},this.restoreComposerState=(s,i)=>{const o=this.dedupeAttachments(i),a=qs(s,o);this.syncComposerSnapshotWithAttachments(a,o)},this.setPendingSessionType=s=>{const i=V.getState().snapshot.pendingSessionType,o=this.resolveUpdateValue(i,s);o!==i&&V.getState().setSnapshot({pendingSessionType:o})},this.send=async()=>{const s=V.getState().snapshot,i=ie.getState().snapshot,o=s.draft.trim(),a=s.attachments,l=Py(s.composerNodes,a);if(!l.some(f=>f.type!=="text"||f.text.trim().length>0))return;const{selectedSkills:c,composerNodes:d}=s,p=i.selectedSessionKey??this.getDraftSessionId();i.selectedSessionKey||this.uiManager.goToSession(p,{replace:!0}),this.setComposerNodes(Fr()),await this.streamActionsManager.sendMessage({message:o,sessionKey:p,agentId:i.selectedAgentId,sessionType:s.selectedSessionType,model:s.selectedModel||void 0,thinkingLevel:s.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:c,attachments:a,parts:l,restoreDraftOnError:!0,composerNodes:d})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=s=>{const i=V.getState().snapshot.selectedModel,o=this.resolveUpdateValue(i,s);o!==i&&(V.getState().setSnapshot({selectedModel:o}),this.reconcileThinkingForModel(o))},this.setSelectedThinkingLevel=s=>{const i=V.getState().snapshot.selectedThinkingLevel,o=this.resolveUpdateValue(i,s);o!==i&&V.getState().setSnapshot({selectedThinkingLevel:o})},this.selectSessionType=s=>{const i=Oe(s);V.getState().setSnapshot({selectedSessionType:i,pendingSessionType:i})},this.setSelectedSkills=s=>{const i=V.getState().snapshot,{selectedSkills:o}=i,a=this.resolveUpdateValue(o,s);this.isSameStringArray(a,o)||this.syncComposerSnapshot(Sa(i.composerNodes,a,i.skillRecords))},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=V.getState().snapshot,r=n.modelOptions.find(o=>o.value===t),{selectedThinkingLevel:s}=n,i=this.resolveThinkingForModel(r,s);i!==s&&V.getState().setSnapshot({selectedThinkingLevel:i})}}const LS=async()=>{};class NS{constructor(t,n,r){this.uiManager=t,this.sessionListManager=n,this.streamActionsManager=r,this.actions={refetchSessions:LS},this.bindActions=s=>{this.actions={...this.actions,...s}},this.hasSnapshotChanges=s=>{const i=He.getState().snapshot;for(const[o,a]of Object.entries(s))if(!Object.is(i[o],a))return!0;return!1},this.syncSnapshot=s=>{this.hasSnapshotChanges(s)&&He.getState().setSnapshot(s)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.deleteCurrentSession=async()=>{const{snapshot:{selectedSessionKey:s}}=ie.getState();if(!(!s||!await this.uiManager.confirm({title:I("chatDeleteSessionConfirm"),variant:"destructive",confirmLabel:I("delete")}))){He.getState().setSnapshot({isDeletePending:!0});try{await iu(s),this.streamActionsManager.resetStreamState(),this.uiManager.goToChatRoot({replace:!0}),await this.actions.refetchSessions()}finally{He.getState().setSnapshot({isDeletePending:!1})}}}}}class PS{constructor(){this.chatUiManager=new Da,this.chatStreamActionsManager=new ja,this.chatSessionListManager=new Pa(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new ES(this.chatUiManager,this.chatStreamActionsManager,()=>this.getDraftSessionId()),this.chatRunStatusManager=new Na,this.chatThreadManager=new NS(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager),this.draftSessionId="",this.setDraftSessionId=t=>{this.draftSessionId=t}}getDraftSessionId(){return this.draftSessionId}}function jS(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=Oa(e.requestedSkills);return n.length>0&&(t.requested_skills=n),t}function DS(e){return e instanceof Error?e.message.includes("ncp session not found:"):!1}function _S({view:e}){var Pe,Xe,ce;const[t]=k.useState(()=>new PS),[n,r]=k.useState(()=>mi()),s=ie(W=>W.snapshot.query),i=ie(W=>W.snapshot.selectedSessionKey),o=ie(W=>W.snapshot.selectedAgentId),a=V(W=>W.snapshot.pendingSessionType),l=V(W=>W.snapshot.selectedModel),{confirm:u,ConfirmDialog:c}=fr(),d=en(),p=Ii(),{sessionId:f}=Mi(),y=k.useRef(null),m=k.useRef(i),b=k.useMemo(()=>Ea(f),[f]),{sessionsQuery:g,installedSkillsQuery:v,isProviderStateResolved:w,modelOptions:N,sessionSummaries:j,sessions:T,skillRecords:O,selectedSession:B,sessionTypeOptions:$,defaultSessionType:C,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_}=AS({query:s,selectedSessionKey:i,currentSelectedModel:l,pendingSessionType:a,setPendingSessionType:t.chatInputManager.setPendingSessionType,setSelectedModel:t.chatInputManager.setSelectedModel,setSelectedThinkingLevel:t.chatInputManager.setSelectedThinkingLevel}),A=g.refetch,K=i??n,L=k.useRef(j);k.useEffect(()=>{L.current=j},[j]);const[Q]=k.useState(()=>new cS({baseUrl:Li,basePath:"/api/ncp/agent",fetchImpl:dS()})),ae=k.useCallback(async(W,Ye)=>{Ye.throwIfAborted();let je=null;try{je=await ou(W,300)}catch(Be){if(!DS(Be))throw Be}Ye.throwIfAborted();const ze=L.current.find(Be=>Be.sessionId===W)??null;return{messages:(je==null?void 0:je.messages)??[],status:(ze==null?void 0:ze.status)==="running"?"running":"idle"}},[]),x=tx({sessionId:K,client:Q,loadSeed:ae});k.useEffect(()=>{t.setDraftSessionId(n)},[n,t]),k.useEffect(()=>{if(i===null){const W=mi();r(W),t.setDraftSessionId(W)}},[t,i]);const oe=k.useMemo(()=>vS(x.visibleMessages),[x.visibleMessages]),re=x.isSending||x.isRunning,S=x.isRunning,he=x.isRunning,ke=x.isRunning?null:"__preparing__",se=((Pe=x.hydrateError)==null?void 0:Pe.message)??((Xe=x.snapshot.error)==null?void 0:Xe.message)??null,pe=x.activeRunId,xe=k.useMemo(()=>TS({summaries:j,activeSessionId:K,isLocallyRunning:re||!!pe}),[pe,K,re,j]);k.useEffect(()=>{!re&&!pe||A()},[pe,re,A]),k.useEffect(()=>{t.chatStreamActionsManager.bind({sendMessage:async W=>{var ze,Be;if(W.sessionKey!==K)return;const Ye=jS({model:W.model,thinkingLevel:W.thinkingLevel,sessionType:W.sessionType,requestedSkills:W.requestedSkills}),je=sx({sessionId:W.sessionKey,text:W.message,attachments:W.attachments,parts:W.parts,metadata:Ye});if(je)try{g.refetch(),await x.send(je),await g.refetch()}catch(Dt){throw W.restoreDraftOnError&&(W.composerNodes&&W.composerNodes.length>0?(Be=(ze=t.chatInputManager).restoreComposerState)==null||Be.call(ze,W.composerNodes,W.attachments??[]):t.chatInputManager.setDraft(ft=>ft.trim().length===0?W.message:ft)),Dt}},stopCurrentRun:async()=>{await x.abort(),await g.refetch()},resumeRun:async W=>{W.sessionKey===K&&await x.streamRun()},resetStreamState:()=>{m.current=null},applyHistoryMessages:()=>{}})},[K,x,t,g]),Ma({view:e,routeSessionKey:b,selectedSessionKey:i,selectedAgentId:o,setSelectedSessionKey:t.chatSessionListManager.setSelectedSessionKey,setSelectedAgentId:t.chatSessionListManager.setSelectedAgentId,selectedSessionKeyRef:m,resetStreamState:t.chatStreamActionsManager.resetStreamState,resolveAgentIdFromSessionKey:Aa}),k.useEffect(()=>{t.chatUiManager.syncState({pathname:d.pathname}),t.chatUiManager.bindActions({navigate:p,confirm:u})},[u,d.pathname,p,t]);const Te=B?Qi(B):void 0,Ie=((ce=$.find(W=>W.value===R))==null?void 0:ce.label)??lt(R);return k.useEffect(()=>{t.chatThreadManager.bindActions({refetchSessions:g.refetch})},[t,g.refetch]),k.useEffect(()=>{t.chatInputManager.syncSnapshot({isProviderStateResolved:w,defaultSessionType:C,canStopGeneration:he,stopDisabledReason:ke,stopSupported:!0,stopReason:void 0,sendError:se,isSending:re,modelOptions:N,sessionTypeOptions:$,selectedSessionType:R,canEditSessionType:E,sessionTypeUnavailable:z,skillRecords:O,isSkillsLoading:v.isLoading}),t.chatSessionListManager.syncSnapshot({sessions:T,query:s,isLoading:g.isLoading}),t.chatRunStatusManager.syncSnapshot({sessionRunStatusByKey:xe,isLocallyRunning:re||!!pe,activeBackendRunId:pe}),t.chatThreadManager.syncSnapshot({isProviderStateResolved:w,modelOptions:N,sessionTypeUnavailable:z,sessionTypeUnavailableMessage:_,sessionTypeLabel:Ie,selectedSessionKey:i,sessionDisplayName:Te,canDeleteSession:!!B,threadRef:y,isHistoryLoading:x.isHydrating,uiMessages:oe,isSending:re,isAwaitingAssistantOutput:S})},[pe,x.isHydrating,E,he,Te,Ie,C,v.isLoading,S,w,re,se,N.length,N,t,s,B,i,R,xe,$,z,_,T,g.isLoading,O,ke,y,oe]),h.jsx(Xi,{presenter:t,children:h.jsx(Ra,{view:e,confirmDialog:h.jsx(c,{})})})}function GS({view:e}){const t=en();return zi(t.search)==="ncp"?h.jsx(_S,{view:e}):h.jsx(Zb,{view:e})}export{GS as ChatPage};
|