@cjhyy/code-shell-web 0.9.19 → 0.9.21

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.
@@ -17,7 +17,7 @@ description: 描述这个 Skill 适合处理什么任务
17
17
  `}function _c(n){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(n)&&!n.includes("..")}function qv(n,i,r){const s=i.trim().toLocaleLowerCase();return n.filter(f=>(r==="all"||f.source===r)&&(!s||`${f.name} ${f.description}`.toLocaleLowerCase().includes(s)))}const Em={project:"工作区",user:"用户级",plugin:"插件","panel-app":"Panel App"};function Hv({onAuthLost:n,onChanged:i,onDirtyChange:r,configurationVersion:s=0}){const[f,d]=w.useState(null),[o,m]=w.useState(null),[g,p]=w.useState(""),[b,y]=w.useState("all"),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(""),[M,H]=w.useState(0),[oe,ce]=w.useState(!1),[R,W]=w.useState(!1),ie=w.useRef(null),F=w.useRef(null),A=w.useRef(!1),G=w.useRef({onAuthLost:n,onChanged:i});G.current={onAuthLost:n,onChanged:i};const V=w.useRef(null),se=w.useRef(null),ae=w.useCallback(k=>{k instanceof We&&k.status===401?G.current.onAuthLost():D(k instanceof Error?k.message:"操作失败,请重试。")},[]);w.useEffect(()=>()=>{ie.current?.abort(),F.current?.abort()},[]),w.useEffect(()=>{if(ie.current){A.current=!0;return}const k=new AbortController;return F.current=k,Cm(k.signal).then(T=>{k.signal.aborted||d(T)}).catch(T=>{k.signal.aborted||ae(T)}),()=>k.abort()},[M,s,ae]),w.useEffect(()=>{o&&V.current?.focus()},[o?.kind]);const P=k=>{se.current=document.activeElement,D(""),_(""),ce(!1),W(!1),m(k)},E=()=>{m(null),ce(!1),W(!1),D(""),se.current?.focus()},U=()=>{if(!ie.current){if(oe){W(!0);return}E()}},te=async(k,T,K=!1)=>{if(ie.current)return;F.current?.abort();const C=new AbortController;ie.current=C,S(k),D(""),_("");try{const re=await T(C.signal);if(C.signal.aborted)return;if(K){try{const ve=await Cm(C.signal);C.signal.aborted||d(ve)}catch(ve){if(ve instanceof We&&ve.status===401)throw ve;C.signal.aborted||D("操作已完成,但列表刷新失败。请点击刷新查看最新状态。")}if(C.signal.aborted)return;_(re.message||"设置已保存,下次任务生效。"),G.current.onChanged?.()}return re}catch(re){C.signal.aborted||ae(re);return}finally{ie.current===C&&(ie.current=null),C.signal.aborted||(S(""),A.current&&(A.current=!1,H(re=>re+1)))}};w.useEffect(()=>(r?.(oe||!!v),()=>r?.(!1)),[oe,v,r]);const he=qv(f?.skills??[],g,b);return u.jsxs("section",{className:"hub-skills","aria-labelledby":"skills-title",onKeyDown:k=>{k.key==="Escape"&&o&&!v&&(k.preventDefault(),U())},children:[u.jsxs("header",{className:"skills-heading",children:[u.jsxs("div",{children:[u.jsx("span",{className:"skills-eyebrow",children:"工作区能力"}),u.jsx("h1",{id:"skills-title",children:"Skills"}),u.jsx("p",{children:"创建工作说明,导入社区技能,把常用流程留在工作区。"})]}),u.jsxs("div",{className:"skills-actions",children:[u.jsx("button",{className:"config-button",disabled:!!v||!!o,onClick:()=>P({kind:"import"}),children:"从 GitHub 导入"}),u.jsx("button",{className:"config-button config-button-primary",disabled:!!v||!!o,onClick:()=>P({kind:"create"}),children:"+ 创建 Skill"})]})]}),N&&u.jsx("div",{className:"config-message config-error",role:"alert",children:N}),z&&u.jsx("div",{className:"config-message config-success",role:"status",children:z}),v&&u.jsxs("p",{className:"skills-progress",role:"status",children:[v,"…"]}),o&&u.jsxs("section",{className:"skills-workspace-panel","aria-labelledby":"skills-panel-title",children:[u.jsxs("header",{children:[u.jsx("h2",{id:"skills-panel-title",ref:V,tabIndex:-1,children:o.kind==="create"?"创建 Skill":o.kind==="detail"?o.detail.editable?`编辑 ${o.detail.name}`:o.detail.name:o.kind==="import"?"从 GitHub 导入":o.kind==="update"?`更新 ${o.preview.name}`:`移除 ${o.skill.name}`}),u.jsx("button",{className:"config-button config-button-quiet",disabled:!!v,onClick:U,children:"关闭"})]}),R&&u.jsxs("div",{className:"skills-discard-confirm",role:"alert",children:[u.jsx("p",{children:"还有未保存的修改。关闭会丢弃这些修改。"}),u.jsxs("div",{className:"skills-actions",children:[u.jsx("button",{className:"config-button",onClick:()=>W(!1),children:"继续编辑"}),u.jsx("button",{className:"config-button skills-danger",onClick:E,children:"放弃修改并关闭"})]})]}),(o.kind==="create"||o.kind==="detail")&&u.jsx(Iv,{detail:o.kind==="detail"?o.detail:void 0,busy:!!v,run:te,onSaved:E,onDirtyChange:ce},o.kind==="detail"?o.detail.name+o.detail.revision:"create"),o.kind==="import"&&u.jsx(Yv,{preview:o.preview,busy:!!v,run:te,onPreview:k=>m({kind:"import",preview:k}),onInstalled:E},o.preview?.reviewToken??"url"),o.kind==="update"&&u.jsx(Gv,{preview:o.preview,busy:!!v,run:te,onUpdated:E}),o.kind==="remove"&&u.jsxs("div",{className:"skills-remove-confirm",children:[u.jsxs("p",{children:["确认从当前工作区移除 ",u.jsx("strong",{children:o.skill.name}),"?它的 SKILL.md、脚本和资源文件都会移除。"]}),u.jsx("p",{className:"config-help",children:"已保存的对话会保留。其他设备下一次运行任务时将不再使用这个工作区 Skill。"}),u.jsxs("div",{className:"skills-actions",children:[u.jsx("button",{className:"config-button",disabled:!!v,onClick:U,children:"取消"}),u.jsx("button",{className:"config-button skills-danger",disabled:!!v,onClick:()=>{te("正在移除 Skill",k=>Ov(o.skill.name,o.skill.revision,k),!0).then(k=>{k&&E()})},children:"确认移除"})]})]})]}),u.jsxs("div",{className:"skills-filter",children:[u.jsxs("label",{children:[u.jsx("span",{className:"config-sr-only",children:"搜索 Skills"}),u.jsx("input",{type:"search","aria-label":"搜索 Skills",value:g,onChange:k=>p(k.target.value),placeholder:"搜索名称或用途…"})]}),u.jsxs("select",{"aria-label":"Skill 来源",value:b,onChange:k=>y(k.target.value),children:[u.jsx("option",{value:"all",children:"全部来源"}),Object.entries(Em).map(([k,T])=>u.jsx("option",{value:k,children:T},k))]}),u.jsx("button",{className:"config-button config-button-quiet",disabled:!!v,onClick:()=>{D(""),H(k=>k+1)},children:"刷新"})]}),!f&&!N?u.jsx("p",{className:"config-help",children:"正在读取 Skills…"}):f?u.jsxs("p",{className:"skills-count",children:[he.length===f.skills.length?`${he.length} 个 Skill`:`显示 ${he.length} / ${f.skills.length} 个 Skill`," · ",f.skills.filter(k=>k.enabled).length," 个已启用"]}):null,f&&!he.length&&u.jsxs("div",{className:"skills-empty",children:[u.jsx("h2",{children:g||b!=="all"?"没有匹配的 Skills":"从一个常用流程开始"}),u.jsx("p",{children:g||b!=="all"?"调整搜索词或来源筛选。":"创建自己的 Skill,或粘贴 GitHub 地址导入完整的社区技能。"})]}),u.jsx("div",{className:"skills-list",children:he.map(k=>u.jsxs("article",{className:"skills-card",children:[u.jsxs("div",{className:"skills-card-heading",children:[u.jsxs("div",{children:[u.jsx("h2",{children:k.name}),u.jsx("span",{className:"config-badge",children:Em[k.source]}),k.origin&&u.jsx("span",{className:"config-badge",children:"GitHub"})]}),u.jsx("button",{className:"config-switch",role:"switch","aria-checked":k.enabled,"aria-label":`${k.enabled?"停用":"启用"} ${k.name}`,disabled:!!v||!!k.disabledReason,title:k.disabledReason,onClick:()=>{te("正在更新 Skill",async T=>(await Tv(k.name,!k.enabled,T),{ok:!0,name:k.name,message:k.enabled?"Skill 已停用,下次任务生效。":"Skill 已启用,下次任务生效。"}),!0)},children:u.jsx("span",{})})]}),u.jsx("p",{children:k.description||"暂未填写用途描述。"}),k.origin&&u.jsxs("p",{className:"skills-source",children:[k.origin.url.replace("https://github.com/","")," · ",k.origin.ref," ·"," ",k.origin.commit.slice(0,8)]}),k.readOnlyReason&&u.jsx("p",{className:"config-help",children:k.readOnlyReason}),k.disabledReason&&u.jsx("p",{className:"config-help",children:k.disabledReason}),u.jsxs("footer",{className:"skills-actions",children:[u.jsx("button",{className:"config-button config-button-quiet",disabled:!!v||!!o,onClick:()=>{se.current=document.activeElement,te("正在读取 Skill",T=>Rv(k.name,T)).then(T=>{T&&P({kind:"detail",detail:T})})},children:k.editable?"查看与编辑":"查看说明"}),k.editable&&k.origin&&u.jsx("button",{className:"config-button config-button-quiet",disabled:!!v||!!o,onClick:()=>{te("正在检查来源更新",T=>Uv(k.name,k.revision,T)).then(T=>{T?.changed?P({kind:"update",preview:T}):T&&_(`${k.name} 已是最新版本。`)})},children:"检查更新"}),k.removable&&u.jsx("button",{className:"config-button config-button-quiet skills-remove",disabled:!!v||!!o,onClick:()=>P({kind:"remove",skill:k}),children:"移除"})]})]},k.name))}),f&&u.jsxs("details",{className:"skills-directories",children:[u.jsx("summary",{children:"Skills 存在哪里"}),u.jsx("p",{children:"这里管理当前工作区。用户级、插件和 Panel App 的 Skills 可以查看和启停,安装内容由各自来源管理。"}),u.jsx("ul",{children:f.directories.map(k=>u.jsx("li",{children:u.jsx("code",{children:k})},k))})]})]})}function Iv({detail:n,busy:i,run:r,onSaved:s,onDirtyChange:f}){const[d,o]=w.useState(n?.name??"my-skill"),[m,g]=w.useState(n?.content??Ss("my-skill")),p=m!==n?.content,b=!n||n.editable;return w.useEffect(()=>{f(b&&(n?m!==n.content:d!=="my-skill"||m!==Ss("my-skill")))},[m,d,n,b,f]),u.jsx("form",{className:"skills-editor",onSubmit:y=>{y.preventDefault(),r(n?"正在保存 Skill":"正在创建 Skill",v=>n?Dv(n.name,m,n.revision,v):_v(d.trim(),m,v),!0).then(v=>{v&&s()})},children:u.jsxs("fieldset",{disabled:i,children:[!n&&u.jsxs("label",{children:[u.jsx("span",{children:"名称"}),u.jsx("input",{required:!0,value:d,maxLength:128,onChange:y=>{const v=y.target.value;m===Ss(d)&&g(Ss(v)),o(v)},"aria-describedby":"skill-name-help","aria-label":"Skill 名称"}),u.jsx("small",{id:"skill-name-help",children:"字母、数字、短横线、下划线或点;创建后名称保持不变。"}),!_c(d)&&u.jsx("span",{className:"skills-field-error",children:"请输入有效名称。"})]}),u.jsxs("label",{children:[u.jsxs("span",{children:[b?"SKILL.md":"说明",n&&b&&p&&u.jsx("small",{className:"skills-unsaved",children:"未保存"})]}),u.jsx("textarea",{value:m,readOnly:!b,onChange:y=>g(y.target.value),rows:18,spellCheck:!1,"aria-label":"SKILL.md 内容"})]}),n?.origin&&b&&u.jsx("p",{className:"config-help",children:"手动编辑会保留 GitHub 来源;以后更新来源时,会预览将替换的完整内容。"}),b&&u.jsxs("div",{className:"skills-actions",children:[u.jsx("span",{className:"config-help",children:"支持 Markdown 和 YAML Frontmatter。变更在下一次任务中生效。"}),u.jsx("button",{className:"config-button config-button-primary",type:"submit",disabled:!m.trim()||!n&&!_c(d)||!!n&&!p,children:n?"保存修改":"创建 Skill"})]})]})})}function Yv({preview:n,busy:i,run:r,onPreview:s,onInstalled:f}){const[d,o]=w.useState(""),[m,g]=w.useState(n?.skills[0]?.pathInRepo??""),[p,b]=w.useState(n?.skills[0]?.name??"");return n?u.jsxs("form",{className:"skills-import-preview",onSubmit:y=>{y.preventDefault(),r("正在导入 Skill 与资源",v=>Lv(n.reviewToken,m,p,v),!0).then(v=>{v&&f()})},children:[u.jsxs("p",{children:[u.jsx("a",{href:n.repoUrl,target:"_blank",rel:"noreferrer",children:n.repoUrl.replace("https://github.com/","")})," ",u.jsx("span",{className:"config-badge",children:n.commit.slice(0,8)})]}),n.warning&&u.jsx("p",{className:"config-help",children:n.warning}),u.jsxs("fieldset",{disabled:i,children:[u.jsx("legend",{children:"选择一个 Skill"}),u.jsx("div",{className:"skills-source-choices",children:n.skills.map(y=>u.jsxs("label",{children:[u.jsx("input",{type:"radio",name:"github-skill",checked:m===y.pathInRepo,onChange:()=>{g(y.pathInRepo),b(y.name)}}),u.jsxs("span",{children:[u.jsx("strong",{children:y.name}),u.jsx("small",{children:y.description||y.pathInRepo}),y.alreadyInstalled&&u.jsx("small",{children:"已有同名 Skill,可修改安装名称。"})]})]},y.pathInRepo))}),!!n.skills.length&&u.jsxs(u.Fragment,{children:[u.jsxs("label",{children:[u.jsx("span",{children:"安装到工作区时使用的名称"}),u.jsx("input",{required:!0,maxLength:128,value:p,onChange:y=>b(y.target.value)})]}),u.jsx("p",{className:"config-help",children:"将导入预览时的确定版本。不会执行其中的脚本。"}),u.jsx("button",{className:"config-button config-button-primary",disabled:!m||!_c(p),type:"submit",children:"确认导入到工作区"})]})]})]}):u.jsxs("form",{className:"skills-import-url",onSubmit:y=>{y.preventDefault(),r("正在检查 GitHub 来源",v=>Mv(d,v)).then(v=>{v&&s(v)})},children:[u.jsxs("label",{children:[u.jsx("span",{children:"GitHub 仓库或 Skill 目录地址"}),u.jsx("input",{type:"url",required:!0,value:d,onChange:y=>o(y.target.value),placeholder:"https://github.com/owner/repository/tree/main/skills/example",disabled:i})]}),u.jsx("p",{className:"config-help",children:"先查看可导入的技能,再确认安装。脚本和资源文件会一起保留。"}),u.jsx("button",{className:"config-button config-button-primary",disabled:i||!d.trim(),children:"预览来源"})]})}function Gv({preview:n,busy:i,run:r,onUpdated:s}){return u.jsxs("div",{className:"skills-update-preview",children:[u.jsxs("p",{children:["来源版本 ",u.jsx("code",{children:n.currentCommit.slice(0,8)})," →"," ",u.jsx("code",{children:n.latestCommit.slice(0,8)})]}),u.jsx("p",{children:"确认后会用下方版本替换此 Skill 的说明、脚本和资源,包括你在其中做过的本地修改。"}),u.jsxs("details",{children:[u.jsxs("summary",{children:["查看将导入的 ",n.files?.length??0," 个文件"]}),u.jsx("ul",{children:n.files?.map(f=>u.jsxs("li",{children:[u.jsx("code",{children:f.path}),u.jsxs("span",{children:[Math.ceil(f.size/1024)," KB",f.executable?" · 可执行脚本":""]})]},f.path))})]}),u.jsxs("label",{children:[u.jsx("span",{children:"新的 SKILL.md"}),u.jsx("textarea",{value:n.content??"",readOnly:!0,rows:16,"aria-label":"更新后的 SKILL.md"})]}),u.jsx("button",{className:"config-button config-button-primary",disabled:i||!n.reviewToken,onClick:()=>{r("正在更新 Skill",f=>Bv(n.reviewToken,f),!0).then(f=>{f&&s()})},children:"确认更新到预览版本"})]})}function Vv(n){const i=r=>r.map((s,f)=>({id:`stored-${f}`,name:s,value:"",stored:!0,removed:!1}));return{name:n?.name??"",transport:n?.transport??"stdio",command:n?.command??"",args:"",clearArgs:!1,url:n?.url??"",env:i(n?.envKeys??[]),headers:i(n?.headerKeys??[]),envHeaders:Object.entries(n?.envHeaders??{}).map(([r,s],f)=>({id:`stored-${f}`,name:r,value:s,initialValue:s,stored:!0,removed:!1})),envVars:(n?.envVars??[]).join(`
18
18
  `),bearerTokenEnvVar:n?.bearerTokenEnvVar??"",credentialRef:n?.credentialRef??"",enabled:n?.enabled??!0,restrictTools:n?.allowedTools!==void 0,allowedTools:(n?.allowedTools??[]).join(`
19
19
  `),disabledTools:(n?.disabledTools??[]).join(`
20
- `),reuseStoredSecrets:!1}}function fc(n){return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean)}function Qv(n,i){const r={},s=new Set;for(const f of n){if(!f.stored&&f.removed)continue;const d=f.name.trim();if(["__proto__","prototype","constructor"].includes(d))throw new Error(`${i}名称无效。`);if(!d&&!f.value&&!f.stored)continue;if(!d||!f.stored&&!f.value)throw new Error(`请完整填写${i}的名称和值,或移除空行。`);const o=i==="环境变量"?d:d.toLowerCase();if(s.has(o))throw new Error(`${i}名称不能重复。`);s.add(o),f.removed?r[d]=null:f.value&&f.value!==f.initialValue&&(r[d]=f.value)}return r}function Nm(n){try{return new URL(n).origin}catch{return""}}function Xv(n,i){if(!i)return!1;const r=i.envKeys.length||i.headerKeys.length||i.envVars.length||Object.keys(i.envHeaders).length||i.credentialRef||i.bearerTokenEnvVar||i.argsCount,s=n.transport!==i.transport||(n.transport==="stdio"?n.command.trim()!==i.command||!!n.args.trim()||n.clearArgs:Nm(n.url)!==Nm(i.url??""));return!!r&&s}function Zv(n,i){const r={name:n.name.trim()};(!i||n.transport!==i.transport)&&(r.transport=n.transport),(!i||n.enabled!==i.enabled)&&(r.enabled=n.enabled),n.transport==="stdio"?((!i||n.command.trim()!==i.command)&&(r.command=n.command.trim()),n.clearArgs?r.args=[]:n.args.trim()&&(r.args=n.args.split(/\r?\n/).filter(o=>o.length>0))):(!i||n.url.trim()!==i.url)&&(r.url=n.url.trim());for(const[o,m]of[["env","环境变量"],["headers","请求头"],["envHeaders","环境变量请求头"]]){const g=Qv(n[o],m);Object.keys(g).length&&(r[o]=g)}const s=fc(n.envVars);(!i||JSON.stringify(s)!==JSON.stringify(i.envVars))&&(r.envVars=s);for(const o of["bearerTokenEnvVar","credentialRef"])(!i||n[o].trim()!==(i[o]??""))&&(r[o]=n[o].trim()||null);const f=n.restrictTools?fc(n.allowedTools):void 0;(!i||JSON.stringify(f)!==JSON.stringify(i.allowedTools))&&(r.allowedTools=f??null);const d=fc(n.disabledTools);return(!i||JSON.stringify(d)!==JSON.stringify(i.disabledTools))&&(r.disabledTools=d),n.reuseStoredSecrets&&(r.reuseStoredSecrets=!0),r}function Yg(n){if(!n||typeof n.workspacePath!="string"||!Array.isArray(n.servers)||!Array.isArray(n.removed))throw new Error("服务端返回了无效的 MCP 配置,请刷新重试。");return n}const $i=(n,i="")=>`/api/v1/mcp/servers/${encodeURIComponent(n)}${i}`;async function Kv(n){return Yg(await Ve("/api/v1/mcp",{signal:n}))}async function Bs(n,i,r,s){return Yg(await Ve(n,{method:i,headers:{"Content-Type":"application/json"},...r===void 0?{}:{body:JSON.stringify(r)},signal:s}))}function Fv(n,i,r){return Bs(i?$i(i.name):"/api/v1/mcp/servers",i?"PUT":"POST",Zv(n,i),r)}function $v(n,i,r){return Bs($i(n,"/enabled"),"PUT",{enabled:i},r)}function Jv(n,i){return Bs($i(n),"DELETE",void 0,i)}function Tm(n,i){return Bs($i(n,"/inherit"),"POST",{},i)}async function Pv(n,i){const r=await Ve($i(n,"/probe"),{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:i});if(r.name!==n||!["ok","error","cancelled"].includes(r.status))throw new Error("服务端返回了无效的连接测试结果。");return r}function Am(n,i,r){return Ve(Rt($i(n,"/cancel-probe"),i,r),{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",keepalive:!0})}const Wv={local:"工作区本地",project:"工作区配置",user:"用户级",managed:"启动配置",plugin:"插件提供"};function e0({onAuthLost:n,onConfigurationChange:i,configurationVersion:r=0,onDirtyChange:s}){const[f,d]=w.useState(null),[o,m]=w.useState(!0),[g,p]=w.useState(!1),[b,y]=w.useState(!1),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(null),[M,H]=w.useState(null),[oe,ce]=w.useState(""),[R,W]=w.useState({}),[ie,F]=w.useState(null),[A,G]=w.useState(0),V=w.useRef({onAuthLost:n,onConfigurationChange:i,onDirtyChange:s});V.current={onAuthLost:n,onConfigurationChange:i,onDirtyChange:s};const se=w.useRef(!1),ae=w.useRef(null),P=w.useRef(null),E=w.useRef(null),U=w.useRef(0),te=w.useRef(!1),he=w.useRef(r);w.useEffect(()=>{V.current.onDirtyChange?.(b||g)},[b,g]);const k=w.useCallback(Y=>{Y instanceof We&&Y.status===401?V.current.onAuthLost():S(Y instanceof Error?Y.message:"MCP 操作失败,请重试。")},[]);w.useEffect(()=>(se.current=!0,()=>{se.current=!1,V.current.onDirtyChange?.(!1),P.current?.abort();const Y=E.current;Y&&(Y.controller.abort(),Am(Y.name,Y.workspace,Y.projectId).catch(()=>{}))}),[]),w.useEffect(()=>{he.current!==r&&(he.current=r,P.current?te.current=!0:G(Y=>Y+1))},[r]),w.useEffect(()=>{const Y=new AbortController;ae.current=Y;const xe=Date.now(),J=++U.current;return m(!0),S(""),Kv(Y.signal).then(ye=>{!Y.signal.aborted&&J===U.current&&(d(ye),W(Ae=>Object.fromEntries(Object.entries(Ae).filter(([,we])=>Date.parse(we.checkedAt)>=xe))))}).catch(ye=>{!Y.signal.aborted&&J===U.current&&k(ye)}).finally(()=>{!Y.signal.aborted&&J===U.current&&m(!1)}),()=>Y.abort()},[A,k]);const T=async(Y,xe="MCP 设置已保存,任务进程会加载新的配置。")=>{if(P.current||E.current)return!1;ae.current?.abort();const J=++U.current,ye=new AbortController;P.current=ye,p(!0),m(!1),S(""),D("");try{const Ae=await Y(ye.signal);return!se.current||ye.signal.aborted||J!==U.current?!1:(d(Ae),W({}),D(xe),V.current.onConfigurationChange?.(),!0)}catch(Ae){return se.current&&!ye.signal.aborted&&k(Ae),!1}finally{P.current===ye&&(P.current=null),se.current&&!ye.signal.aborted&&(p(!1),te.current&&(te.current=!1,G(Ae=>Ae+1)))}},K=async Y=>{if(E.current||P.current)return;const xe=new AbortController;E.current={name:Y,controller:xe,workspace:Jc()??"",projectId:Us()},F(Y),S(""),D(""),W(J=>{const ye={...J};return delete ye[Y],ye});try{const J=await Pv(Y,xe.signal);se.current&&!xe.signal.aborted&&W(ye=>({...ye,[Y]:J}))}catch(J){se.current&&!xe.signal.aborted&&k(J)}finally{E.current?.controller===xe&&(E.current=null),se.current&&F(null)}},C=async()=>{const Y=E.current;if(Y)try{await Am(Y.name,Y.workspace,Y.projectId)}catch(xe){se.current&&k(xe)}finally{Y.controller.abort(),E.current===Y&&(E.current=null),se.current&&(F(null),W(xe=>({...xe,[Y.name]:{name:Y.name,status:"cancelled",checkedAt:new Date().toISOString(),durationMs:0,error:{code:"cancelled",message:"测试已取消。"}}})))}},re=g||o||ie!==null,ve=oe.trim().toLocaleLowerCase(),Q=[...f?.servers??[]];z?.kind==="edit"&&!Q.some(Y=>Y.name===z.name)&&Q.push(z.original);const pe=Q.filter(Y=>!ve||Y.name.toLocaleLowerCase().includes(ve)||z?.kind==="edit"&&z.name===Y.name),je=z?.kind==="edit"?Q.find(Y=>Y.name===z.name):void 0;return u.jsxs("div",{className:"hub-mcp",children:[u.jsxs("div",{className:"config-section-heading hub-mcp-toolbar",children:[u.jsxs("label",{className:"config-search",children:[u.jsx("span",{"aria-hidden":"true",children:"⌕"}),u.jsx("input",{type:"search",value:oe,onChange:Y=>ce(Y.target.value),placeholder:"搜索 MCP 服务…","aria-label":"搜索 MCP 服务"})]}),u.jsxs("div",{className:"hub-mcp-toolbar-actions",children:[u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>G(Y=>Y+1),children:"刷新 MCP"}),u.jsx("button",{className:"config-button",disabled:re||z!==null,onClick:()=>_({kind:"new"}),children:"+ 添加服务"})]})]}),v&&u.jsx("p",{className:"config-message config-error",role:"alert",children:v}),N&&u.jsx("p",{className:"config-message config-success",role:"status",children:N}),g&&u.jsx("p",{className:"config-help",role:"status",children:"正在保存 MCP 配置…"}),o&&!f&&u.jsx("p",{className:"config-help",role:"status",children:"正在读取 MCP 配置…"}),z?.kind==="new"&&u.jsxs("div",{className:"config-card hub-mcp-editor-card",children:[u.jsx("h2",{children:"添加 MCP 服务"}),u.jsx(zm,{disabled:re,save:T,onDone:()=>_(null),onProbe:Y=>{K(Y)},onDirtyChange:y})]}),!pe.length&&f&&z?.kind!=="new"&&u.jsxs("div",{className:"config-empty",children:[u.jsx("span",{"aria-hidden":"true",children:"⌘"}),u.jsx("h3",{children:ve?"没有匹配的服务":"连接你的工具与数据"}),u.jsx("p",{children:ve?"试试其他服务名称。":"添加运行 CodeShell 的设备上的命令,或连接提供 MCP 接口的 HTTP 服务。"})]}),u.jsx("div",{className:"hub-mcp-list",children:pe.map(Y=>u.jsxs("article",{className:"config-card hub-mcp-card",children:[u.jsxs("div",{className:"hub-mcp-card-head",children:[u.jsx("span",{className:"config-row-icon","aria-hidden":"true",children:"⌘"}),u.jsxs("div",{className:"config-row-copy",children:[u.jsx("strong",{children:Y.name}),u.jsxs("span",{children:[Y.transport==="stdio"?"本地命令":Y.transport==="inprocess"?"内置工具":"HTTP 服务"," ","· ",Wv[Y.scope]]})]}),u.jsx("button",{className:"config-switch",type:"button",role:"switch","aria-checked":Y.enabled,"aria-label":`${Y.enabled?"停用":"启用"} MCP ${Y.name}`,disabled:re||Y.pluginDisabled,onClick:()=>{T(xe=>$v(Y.name,!Y.enabled,xe))},children:u.jsx("span",{})})]}),z?.kind==="edit"&&z.name===Y.name&&je?u.jsx(zm,{server:je,disabled:re,save:T,onDone:()=>_(null),onProbe:xe=>{K(xe)},onDirtyChange:y},Y.name):u.jsxs(u.Fragment,{children:[u.jsxs("p",{className:"hub-mcp-endpoint",children:[u.jsx("code",{children:Y.transport==="stdio"?Y.command:Y.url||"由任务进程提供"}),Y.argsCount>0&&u.jsxs("span",{children:[Y.argsCount," 个已保存参数"]})]}),u.jsxs("div",{className:"hub-mcp-metadata",children:[u.jsx("span",{className:`config-badge${Y.enabled?" config-badge-accent":""}`,children:Y.enabled?"配置启用":"配置停用"}),Y.envKeys.length>0&&u.jsxs("span",{children:[Y.envKeys.length," 个环境变量"]}),(Y.headerKeys.length>0||Y.credentialRef||Y.bearerTokenEnvVar||Object.keys(Y.envHeaders).length>0)&&u.jsx("span",{children:"已配置认证"}),Y.hasLocalOverride&&u.jsx("span",{children:"本地覆盖"})]}),Y.source==="plugin"&&u.jsx("p",{className:"config-help",children:Y.pluginDisabled?"所属插件已停用。启用插件后,才能启用或测试这个服务。":"连接命令与地址由插件提供,可在此启停或测试。"}),u.jsxs("div",{className:"hub-mcp-card-actions",children:[ie===Y.name?u.jsx("button",{className:"config-button",onClick:()=>{C()},children:"取消测试"}):u.jsx("button",{className:"config-button",disabled:re||Y.pluginDisabled||Y.transport==="inprocess",onClick:()=>{K(Y.name)},children:"测试连接"}),Y.editable&&u.jsx("button",{className:"config-button config-button-quiet",disabled:re||z!==null,onClick:()=>{H(null),_({kind:"edit",name:Y.name,original:Y})},children:"编辑"}),Y.hasLocalOverride&&u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>{T(xe=>Tm(Y.name,xe),"已移除本地覆盖,恢复继承配置。")},children:"恢复继承"}),Y.deletable&&u.jsx("button",{className:"config-button config-button-quiet hub-mcp-remove",disabled:re||z!==null,onClick:()=>H(Y.name),children:"移除"})]}),M===Y.name&&u.jsxs("div",{className:"hub-mcp-delete",role:"alert",children:[u.jsxs("span",{children:["从当前工作区移除 ",Y.name,"?其他工作区的配置不受影响。"]}),u.jsxs("div",{children:[u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>H(null),children:"取消"}),u.jsx("button",{className:"config-button hub-mcp-remove",disabled:re,onClick:async()=>{await T(xe=>Jv(Y.name,xe),"已从当前工作区移除服务。")&&H(null)},children:"确认移除"})]})]}),ie===Y.name&&u.jsx("p",{className:"hub-mcp-probing",role:"status",children:"正在建立测试连接并读取工具列表…"}),R[Y.name]&&u.jsx(t0,{result:R[Y.name]})]})]},Y.name))}),!!f?.removed.length&&u.jsxs("details",{className:"hub-mcp-removed",children:[u.jsxs("summary",{children:["已在当前工作区移除(",f.removed.length,")"]}),f.removed.map(Y=>u.jsxs("div",{className:"hub-mcp-removed-row",children:[u.jsx("span",{children:Y.name}),u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>{T(xe=>Tm(Y.name,xe),"已恢复继承的 MCP 配置。")},children:"恢复继承"})]},Y.name))]}),u.jsx("p",{className:"config-help hub-mcp-explanation",children:"连接使用运行 CodeShell 的设备上的网络、环境和凭据。测试只建立一次短连接并读取工具列表,完成后关闭;不会调用工具或改变启用状态。"})]})}function zm({server:n,disabled:i,save:r,onDone:s,onProbe:f,onDirtyChange:d}){const o=w.useRef(n).current,[m,g]=w.useState(()=>Vv(o)),p=w.useRef(JSON.stringify(m)).current,b=JSON.stringify(m)!==p;w.useEffect(()=>{d(b)},[b,d]),w.useEffect(()=>()=>d(!1),[d]);const[y,v]=w.useState(""),S=(z,_)=>g(M=>({...M,[z]:_})),N=Xv(m,o),D=m.transport==="stdio";return u.jsx("form",{className:"hub-mcp-editor",onSubmit:async z=>{z.preventDefault(),v("");const _=z.nativeEvent.submitter?.getAttribute("data-probe")==="true";try{await r(M=>Fv(m,o,M))&&(s(),_&&f(m.name.trim()))}catch(M){v(M instanceof Error?M.message:"请检查填写内容。")}},children:u.jsxs("fieldset",{disabled:i,children:[u.jsx("legend",{className:"config-sr-only",children:o?`编辑 MCP ${o.name}`:"新 MCP 服务"}),u.jsxs("div",{className:"config-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"服务名称"}),u.jsx("input",{required:!0,readOnly:!!o,maxLength:128,pattern:"[A-Za-z0-9][A-Za-z0-9._:\\-]*",value:m.name,onChange:z=>S("name",z.target.value),placeholder:"例如 workspace-tools"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"连接方式"}),u.jsxs("select",{"aria-label":"连接方式",value:m.transport,onChange:z=>S("transport",z.target.value),children:[u.jsx("option",{value:"stdio",children:"本地命令(stdio)"}),u.jsx("option",{value:"streamable-http",children:"HTTP(Streamable HTTP)"}),o?.transport==="sse"&&u.jsx("option",{value:"sse",children:"HTTP(已有 SSE 配置)"})]})]}),D?u.jsxs(u.Fragment,{children:[u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"启动命令"}),u.jsx("input",{required:!0,"aria-label":"启动命令",value:m.command,onChange:z=>S("command",z.target.value),placeholder:"例如 node、uvx 或可执行文件路径"}),u.jsx("small",{children:"在当前工作区执行。命令与参数分别填写。"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"命令参数"}),u.jsx("textarea",{"aria-label":"命令参数",rows:3,disabled:m.clearArgs,value:m.args,onChange:z=>S("args",z.target.value),placeholder:o?.argsCount?`已有 ${o.argsCount} 个参数,留空保留。填写后将完整替换。`:"每行一个参数,不需要额外添加引号",autoComplete:"off",spellCheck:!1}),u.jsx("small",{children:"参数可能含密钥,因此不会读回已有值。每一行会作为一个完整参数。"})]}),!!o?.argsCount&&u.jsxs("label",{className:"hub-mcp-check config-full-width",children:[u.jsx("input",{type:"checkbox",checked:m.clearArgs,onChange:z=>S("clearArgs",z.target.checked)}),u.jsx("span",{children:"清空已保存的所有参数"})]})]}):u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"MCP 接口地址"}),u.jsx("input",{type:"url","aria-label":"MCP 接口地址",required:!0,value:m.url,onChange:z=>S("url",z.target.value),placeholder:"https://example.com/mcp"}),o?.urlHasHiddenParts&&u.jsx("small",{children:"已有地址的查询参数已隐藏;不修改地址时会保留。"})]})]}),D?u.jsx(dc,{title:"环境变量",rows:m.env,onChange:z=>S("env",z)}):u.jsx(dc,{title:"请求头",rows:m.headers,onChange:z=>S("headers",z)}),u.jsxs("details",{className:"hub-mcp-advanced",children:[u.jsx("summary",{children:"高级配置"}),u.jsx("div",{className:"config-form-grid",children:D?u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"转发运行环境变量"}),u.jsx("textarea",{"aria-label":"转发运行环境变量",rows:2,value:m.envVars,onChange:z=>S("envVars",z.target.value),placeholder:"每行一个环境变量名称,例如 GITHUB_TOKEN"}),u.jsx("small",{children:"只填写名称,实际值在连接时从CodeShell 的启动环境读取。"})]}):u.jsxs(u.Fragment,{children:[u.jsxs("label",{children:[u.jsx("span",{children:"Bearer Token 环境变量"}),u.jsx("input",{"aria-label":"Bearer Token 环境变量",value:m.bearerTokenEnvVar,onChange:z=>S("bearerTokenEnvVar",z.target.value),placeholder:"例如 MCP_ACCESS_TOKEN",autoComplete:"off"}),u.jsx("small",{children:"填写运行环境中的变量名称。"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"已存储的凭据 ID"}),u.jsx("input",{"aria-label":"已存储的凭据 ID",value:m.credentialRef,onChange:z=>S("credentialRef",z.target.value),placeholder:"可选",autoComplete:"off"}),u.jsx("small",{children:"引用已有凭据;优先于 Bearer 环境变量。"})]})]})}),!D&&u.jsx(dc,{title:"环境变量请求头",rows:m.envHeaders,onChange:z=>S("envHeaders",z),visibleValues:!0}),u.jsxs("label",{className:"hub-mcp-check",children:[u.jsx("input",{type:"checkbox",checked:m.restrictTools,onChange:z=>S("restrictTools",z.target.checked)}),u.jsx("span",{children:"只允许指定工具"})]}),u.jsxs("div",{className:"config-form-grid",children:[m.restrictTools&&u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"允许的工具名称"}),u.jsx("textarea",{rows:2,value:m.allowedTools,onChange:z=>S("allowedTools",z.target.value),placeholder:"每行一个精确工具名称;留空则不开放任何工具"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"停用的工具名称"}),u.jsx("textarea",{rows:2,value:m.disabledTools,onChange:z=>S("disabledTools",z.target.value),placeholder:"每行一个精确工具名称,可留空"})]})]})]}),u.jsxs("label",{className:"hub-mcp-check",children:[u.jsx("input",{type:"checkbox",checked:m.enabled,onChange:z=>S("enabled",z.target.checked)}),u.jsx("span",{children:"启用服务,让任务可以使用这些工具"})]}),N&&u.jsxs("label",{className:"hub-mcp-check hub-mcp-reuse",children:[u.jsx("input",{type:"checkbox",required:!0,checked:m.reuseStoredSecrets,onChange:z=>S("reuseStoredSecrets",z.target.checked)}),u.jsx("span",{children:"允许新的启动方式或服务地址使用已保存的参数、环境变量和认证配置。"})]}),y&&u.jsx("p",{className:"config-error config-message",role:"alert",children:y}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{type:"button",className:"config-button config-button-quiet",onClick:s,children:"取消"}),u.jsx("button",{type:"submit","data-probe":"true",className:"config-button",children:"保存并测试"}),u.jsx("button",{type:"submit",className:"config-button config-button-primary",children:"保存配置"})]})]})})}function dc({title:n,rows:i,onChange:r,visibleValues:s=!1}){const f=(d,o)=>r(i.map(m=>m.id===d?{...m,...o}:m));return u.jsxs("div",{className:"hub-mcp-keys",children:[u.jsxs("div",{className:"hub-mcp-key-heading",children:[u.jsx("h3",{children:n}),u.jsxs("button",{className:"config-text-button",type:"button",onClick:()=>r([...i,{id:la(),name:"",value:"",stored:!1,removed:!1}]),children:["+ 添加",n]})]}),!i.length&&u.jsx("p",{className:"config-help",children:s?"可按请求头名称引用运行环境变量。":"无需此项时可以留空。"}),i.map(d=>u.jsxs("div",{className:`hub-mcp-key-row${d.removed?" hub-mcp-key-removed":""}`,children:[u.jsxs("label",{children:[u.jsxs("span",{className:"config-sr-only",children:[n,"名称"]}),u.jsx("input",{"aria-label":`${n}名称`,value:d.name,readOnly:d.stored,disabled:d.removed,onChange:o=>f(d.id,{name:o.target.value}),placeholder:n==="环境变量"?"例如 API_KEY":"例如 Authorization",autoComplete:"off"})]}),u.jsxs("label",{children:[u.jsxs("span",{className:"config-sr-only",children:[n,"值"]}),u.jsx("input",{"aria-label":`${n} ${d.name||"新条目"} 的值`,type:s?"text":"password",value:d.value,disabled:d.removed,onChange:o=>f(d.id,{value:o.target.value}),placeholder:d.removed?"保存时移除":s?"运行环境变量名称":d.stored?"已配置 · 留空保留":"输入值",autoComplete:s?"off":"new-password",spellCheck:!1})]}),u.jsx("button",{className:"config-button config-button-quiet",type:"button",onClick:()=>d.stored?f(d.id,{removed:!d.removed}):r(i.filter(o=>o.id!==d.id)),children:d.removed?"撤销移除":"移除"})]},d.id)),!!i.length&&!s&&u.jsx("p",{className:"config-help",children:"已有值保留在运行 CodeShell 的设备上;留空保留,填写新值替换,点击“移除”后保存才能删除。"})]})}function t0({result:n}){return u.jsxs("div",{className:`hub-mcp-probe-result hub-mcp-probe-${n.status}`,role:"status",children:[u.jsxs("div",{className:"hub-mcp-probe-summary",children:[u.jsx("strong",{children:n.status==="ok"?"测试连接成功":n.status==="cancelled"?"测试已取消":"连接测试失败"}),u.jsxs("span",{children:[new Date(n.checkedAt).toLocaleTimeString()," ·"," ",n.durationMs<1e3?`${n.durationMs} ms`:`${(n.durationMs/1e3).toFixed(1)} 秒`]})]}),n.error&&u.jsx("p",{children:n.error.message}),n.status==="ok"&&u.jsxs(u.Fragment,{children:[u.jsxs("p",{children:["发现 ",n.toolCount??0," 个工具",n.truncated?"(列表已截取)":"","。测试连接现已关闭。"]}),!!n.tools?.length&&u.jsxs("details",{children:[u.jsx("summary",{children:"查看工具列表"}),u.jsx("ul",{children:n.tools.map((i,r)=>u.jsxs("li",{children:[u.jsxs("div",{children:[u.jsx("code",{children:i.name}),!i.allowed&&u.jsx("span",{className:"config-badge",children:"被工具策略停用"})]}),i.description&&u.jsx("p",{children:i.description})]},`${i.name}-${r}`))})]})]})]})}const n0={overview:{title:"设置",description:"管理当前工作区的模型、Skills 和工具连接。"},models:{title:"模型与连接",description:"选择默认模型,管理工作区使用的服务商连接与凭据。"},skills:{title:"Skills",description:"让 CodeShell 按照你熟悉的工作方式完成任务。"},mcp:{title:"MCP 工具",description:"管理工具连接,测试连接并查看可用工具。"}};function l0(n){return n.section==="skills"?u.jsx(Hv,{onAuthLost:n.onAuthLost,onDirtyChange:n.onDirtyChange,onChanged:n.onConfigurationChange,configurationVersion:n.configurationVersion}):u.jsx(i0,{...n})}function i0({host:n="hub",section:i,onSectionChange:r,onAuthLost:s,onDirtyChange:f,onConfigurationChange:d,configurationVersion:o=0}){const[m,g]=w.useState(null),[p,b]=w.useState(!0),[y,v]=w.useState(""),[S,N]=w.useState(""),[D,z]=w.useState(null),[_,M]=w.useState(0),H=w.useRef({onAuthLost:s,onConfigurationChange:d});H.current={onAuthLost:s,onConfigurationChange:d};const oe=w.useRef(!1),ce=w.useRef(0),R=w.useRef(null),W=w.useRef(null),ie=w.useRef(!1),F=w.useRef(o),A=w.useCallback(se=>{se instanceof We&&se.status===401?H.current.onAuthLost():v(Ig(se))},[]);w.useEffect(()=>{o!==F.current&&(F.current=o,W.current?ie.current=!0:M(se=>se+1))},[o]),w.useEffect(()=>(oe.current=!0,()=>{oe.current=!1,W.current?.abort()}),[]),w.useEffect(()=>{const se=new AbortController;R.current=se;const ae=++ce.current;return b(!0),v(""),Hg(se.signal).then(P=>{!se.signal.aborted&&ae===ce.current&&g(P)}).catch(P=>{!se.signal.aborted&&ae===ce.current&&A(P)}).finally(()=>{!se.signal.aborted&&ae===ce.current&&b(!1)}),()=>se.abort()},[_,A]);const G=async(se,ae)=>{if(W.current)return!1;R.current?.abort();const P=++ce.current,E=new AbortController;W.current=E,b(!1),z(se),v(""),N("");try{const U=await ae(E.signal);return!oe.current||E.signal.aborted||P!==ce.current?!1:(g(U),N(U.restartRequired?"设置已保存,重启服务后生效。":"设置已保存,下次运行任务时生效。"),H.current.onConfigurationChange?.(),!0)}catch(U){return U instanceof We&&U.status===409&&(ie.current=!0),oe.current&&!E.signal.aborted&&A(U),!1}finally{W.current===E&&(W.current=null),oe.current&&!E.signal.aborted&&(z(null),ie.current&&(ie.current=!1,M(U=>U+1)))}},V=n0[i];return u.jsxs("section",{className:"hub-settings","aria-labelledby":"hub-settings-title",children:[u.jsxs("div",{className:"hub-settings-heading",children:[u.jsxs("div",{children:[u.jsx("span",{className:"hub-settings-eyebrow",children:n==="desktop"?"桌面工作区":"服务端工作区"}),u.jsx("h1",{id:"hub-settings-title",children:V.title}),u.jsx("p",{children:V.description})]}),u.jsx("button",{className:"config-button config-button-quiet",disabled:p||D!==null,onClick:()=>{N(""),M(se=>se+1)},children:p?"读取中…":"刷新"})]}),y&&u.jsx("div",{className:"config-message config-error",role:"alert",children:y}),S&&u.jsx("div",{className:"config-message config-success",role:"status",children:S}),D&&u.jsxs("p",{className:"config-loading",role:"status",children:["正在保存",D,"…"]}),!m&&p?u.jsx("p",{className:"config-loading",role:"status",children:"正在读取工作区设置…"}):null,m&&u.jsxs(u.Fragment,{children:[i==="overview"&&u.jsx(r0,{host:n,configuration:m,onSectionChange:r}),i==="models"&&u.jsx(a0,{configuration:m,disabled:D!==null||p,saving:D!==null,save:G,onDirtyChange:f,onAuthLost:s}),i==="mcp"&&u.jsx(e0,{onAuthLost:s,onDirtyChange:f,onConfigurationChange:d,configurationVersion:o}),u.jsx("p",{className:"config-scope-note",children:"配置作用于当前工作区,所有连接到这里的设备共用。"})]})]})}function r0({host:n,configuration:i,onSectionChange:r}){const s=i.connections.find(o=>o.id===i.defaults.text),f=i.skills.filter(o=>o.enabled).length,d=[{section:"models",title:"模型与连接",summary:s?`${s.id} · ${s.model}`:"尚未设置默认模型",icon:"◈"},{section:"skills",title:"Skills",summary:`${i.skills.length} 个可用 · ${f} 个已启用`,icon:"✧"},{section:"mcp",title:"MCP 工具",summary:`${i.mcpServers.length} 个已配置的工具服务`,icon:"⌘"}];return u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"config-workspace-card",children:[u.jsx("span",{className:"config-workspace-icon","aria-hidden":"true",children:"▱"}),u.jsxs("div",{children:[u.jsx("strong",{children:"当前工作区"}),u.jsx("code",{children:i.workspace.path}),u.jsx("p",{children:n==="desktop"?"对话、文件操作和工具都由已连接的桌面端执行。":"对话、文件操作和工具都在服务端运行。"})]}),u.jsx("span",{className:"config-badge",children:n==="desktop"?"桌面工作区":"服务端工作区"})]}),u.jsx("h2",{className:"config-section-title",children:"工作区配置"}),u.jsx("div",{className:"config-card config-overview-list",children:d.map(o=>{const m=u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"config-row-icon","aria-hidden":"true",children:o.icon}),u.jsxs("span",{className:"config-row-copy",children:[u.jsx("strong",{children:o.title}),u.jsx("span",{children:o.summary})]}),r&&u.jsx("span",{className:"config-chevron","aria-hidden":"true",children:"›"})]});return r?u.jsx("button",{className:"config-overview-row",onClick:()=>r(o.section),children:m},o.section):u.jsx("div",{className:"config-overview-row",children:m},o.section)})}),u.jsxs("div",{className:"config-explanation",children:[u.jsx("h2",{children:"工作区与执行位置"}),u.jsx("p",{children:n==="desktop"?"这里直接使用桌面端的任务、模型、Skills 和工具连接。修改配置后,桌面窗口和已配对的网页共同使用。":"这里使用服务端的任务、模型、Skills 和工具连接。修改配置后,连接到这个服务端的网页共同使用。"}),u.jsx("p",{children:n==="desktop"?"切换项目会切换对应的文件、历史和工作区设置;无需复制桌面配置。":"独立部署使用自己的运行环境。部署到另一台机器时,需要迁移配置和数据,或在这里重新设置。"})]})]})}function a0({configuration:n,disabled:i,saving:r,save:s,onDirtyChange:f,onAuthLost:d}){const[o,m]=w.useState(null),[g,p]=w.useState(null),[b,y]=w.useState(""),[v,S]=w.useState(!1),[N,D]=w.useState(!1),[z,_]=w.useState(null),[M,H]=w.useState({}),oe=w.useRef(null),ce=n.connections.filter(A=>A.tag==="text"),R=n.connections.length-ce.length,W=i||!!z;w.useEffect(()=>{g&&!n.connections.some(A=>A.id===g.id)&&p(null)},[n.connections,g]),w.useEffect(()=>()=>oe.current?.abort(),[]);const ie=w.useRef(new Map);w.useEffect(()=>{const A=new Map(n.connections.map(V=>[V.id,V.revision??JSON.stringify(V)])),G=new Set([...ie.current].filter(([V,se])=>A.get(V)!==se).map(([V])=>V));ie.current=A,z&&G.has(z)&&oe.current?.abort(),G.size&&H(V=>Object.fromEntries(Object.entries(V).filter(([se])=>!G.has(se))))},[n,z]),w.useEffect(()=>(f?.(v||N||r||!!z),()=>f?.(!1)),[v,N,r,z,f]);const F=async A=>{if(oe.current)return;const G=new AbortController;oe.current=G,_(A.id),H(V=>({...V,[A.id]:"正在发送一条简短测试请求…"}));try{const V=await zv(A.id,G.signal);G.signal.aborted||H(se=>({...se,[A.id]:V}))}catch(V){G.signal.aborted||(V instanceof We&&V.status===401?d():H(se=>({...se,[A.id]:Ig(V)})))}finally{oe.current===G&&(oe.current=null,_(null))}};return u.jsxs(u.Fragment,{children:[u.jsx(s0,{configuration:n,disabled:W,save:s,onDirtyChange:D}),u.jsxs("div",{className:"config-section-heading",children:[u.jsxs("h2",{children:["文字模型连接 ",u.jsx("span",{className:"config-count",children:ce.length})]}),u.jsxs("button",{className:"config-button",disabled:W||o!==null||g!==null||!n.catalog.length,onClick:()=>m("__new__"),children:[u.jsx("span",{"aria-hidden":"true",children:"+"})," 添加连接"]})]}),o!==null&&u.jsxs("div",{className:"config-card config-editor-card",children:[u.jsx("h3",{children:o==="__new__"?"添加模型连接":`编辑 ${o.id}`}),u.jsx(u0,{connection:o==="__new__"?void 0:o,configuration:n,disabled:W,save:s,onDone:()=>m(null),onDirtyChange:S},o==="__new__"?"new":o.id)]}),!ce.length&&o!=="__new__"&&u.jsx(o0,{title:"还没有文字模型连接",description:"添加服务商地址、模型名称和 API Key,再选择一个默认模型。"}),u.jsx("div",{className:"config-connection-list",children:ce.map(A=>{const G=n.catalog.find(E=>E.id===A.catalogId),V=g?.id===A.id,se=V&&g?.revision!==A.revision,ae=n.defaults.text===A.id&&ce.length>1,P=M[A.id];return u.jsxs("article",{className:"config-card config-connection-card",children:[u.jsxs("div",{className:"config-connection-head",children:[u.jsx("span",{className:"config-model-icon","aria-hidden":"true",children:"◈"}),u.jsxs("div",{className:"config-row-copy",children:[u.jsx("strong",{children:A.id}),u.jsx("span",{children:G?.displayName??A.catalogId})]}),n.defaults.text===A.id&&u.jsx("span",{className:"config-badge config-badge-accent",children:"默认"}),u.jsx("button",{className:"config-button config-button-quiet",disabled:W||o!==null||g!==null,onClick:()=>m(A),children:"编辑"})]}),u.jsxs("dl",{className:"config-connection-facts",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"模型"}),u.jsx("dd",{children:A.model||"未填写"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"服务地址"}),u.jsx("dd",{children:A.baseUrl||G?.defaultBaseUrl||"服务商默认地址"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"API Key"}),u.jsx("dd",{children:A.hasApiKey?"•••••••• · 已配置":A.needsKey?"未配置":"无需 API Key"})]})]}),u.jsxs("div",{className:"config-model-actions",children:[z===A.id?u.jsx("button",{className:"config-button",onClick:()=>{oe.current?.abort(),H(E=>({...E,[A.id]:"已取消连接测试。"}))},children:"取消测试"}):u.jsx("button",{className:"config-button",disabled:W||o!==null||g!==null,onClick:()=>{F(A)},children:"测试连接"}),u.jsx("span",{className:"config-help",children:"发送一条简短请求,服务商可能计费。"}),u.jsx("button",{className:"config-button config-button-quiet config-remove-connection",disabled:W||o!==null||g!==null,onClick:()=>{p(A),y("")},children:"删除"})]}),P&&u.jsxs("div",{className:`config-probe-result ${typeof P!="string"&&P.ok?"is-success":""}`,role:"status",children:[u.jsx("span",{children:typeof P=="string"?P:P.message}),typeof P!="string"&&u.jsxs("small",{children:[Math.max(.01,P.latencyMs/1e3).toFixed(2)," 秒 ·"," ",new Date(P.checkedAt).toLocaleTimeString()]})]}),V&&u.jsxs("div",{className:"config-remove-confirm",children:[u.jsxs("h3",{children:["删除连接 ",A.id,"?"]}),u.jsx("p",{children:"连接会从当前工作区移除,已有对话记录会保留。"}),se&&u.jsx("p",{role:"alert",children:"连接已被其他设备更新,请取消后重新检查再删除。"}),ce.length===1&&u.jsx("p",{children:"这是最后一个文字模型连接。删除后需重新添加连接才能继续对话。"}),ae&&u.jsxs("label",{children:[u.jsx("span",{children:"替代默认模型"}),u.jsxs("select",{"aria-label":"替代默认模型",value:b,onChange:E=>y(E.target.value),disabled:W,children:[u.jsx("option",{value:"",children:"请选择其他连接"}),ce.filter(E=>E.id!==A.id).map(E=>u.jsxs("option",{value:E.id,children:[E.id," · ",E.model]},E.id))]})]}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{className:"config-button",disabled:W,onClick:()=>p(null),children:"取消删除"}),u.jsx("button",{className:"config-button config-button-danger",disabled:W||se||ae&&!b,onClick:()=>{s("删除连接",E=>Av(A.id,b||void 0,E,g?.revision)).then(E=>{E&&p(null)})},children:"确认删除连接"})]})]})]},A.id)})}),R>0&&u.jsxs("p",{className:"config-help",children:["另有 ",R," 个其他类型的模型连接,保留在工作区配置中。目前此处提供文字模型编辑。"]})]})}function s0({configuration:n,disabled:i,save:r,onDirtyChange:s}){const[f,d]=w.useState(n.defaults.text??""),[o,m]=w.useState(n.defaults.auxText??""),g=w.useRef(n.defaults);w.useEffect(()=>{const y=g.current;g.current=n.defaults,d(v=>v===(y.text??"")?n.defaults.text??"":v),m(v=>v===(y.auxText??"")?n.defaults.auxText??"":v)},[n.defaults]);const p=n.connections.filter(y=>y.tag==="text"),b=f!==(n.defaults.text??"")||o!==(n.defaults.auxText??"");return w.useEffect(()=>(s(b),()=>s(!1)),[b,s]),u.jsx("form",{className:"config-card config-defaults",onSubmit:y=>{y.preventDefault(),r("默认模型",v=>Nv({text:f,auxText:o||null},v))},children:u.jsxs("fieldset",{disabled:i||!p.length,children:[u.jsx("legend",{children:"默认模型"}),u.jsxs("div",{className:"config-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"对话模型"}),u.jsxs("select",{required:!0,value:f,onChange:y=>d(y.target.value),"aria-label":"默认对话模型",children:[u.jsx("option",{value:"",disabled:!0,children:"选择模型连接"}),f&&!p.some(y=>y.id===f)&&u.jsxs("option",{value:f,disabled:!0,children:[f,"(连接不可用)"]}),p.map(y=>u.jsxs("option",{value:y.id,children:[y.id," · ",y.model]},y.id))]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"辅助模型"}),u.jsxs("select",{value:o,onChange:y=>m(y.target.value),"aria-label":"默认辅助模型",children:[u.jsx("option",{value:"",children:"跟随对话模型"}),o&&!p.some(y=>y.id===o)&&u.jsxs("option",{value:o,disabled:!0,children:[o,"(连接不可用)"]}),p.map(y=>u.jsxs("option",{value:y.id,children:[y.id," · ",y.model]},y.id))]})]})]}),u.jsxs("div",{className:"config-form-footer",children:[u.jsx("p",{className:"config-help",children:"辅助模型用于标题生成等轻量任务。"}),u.jsx("button",{className:"config-button",disabled:!b||!f,type:"submit",children:"保存默认模型"})]})]})})}function u0({connection:n,configuration:i,disabled:r,save:s,onDone:f,onDirtyChange:d}){const[o,m]=w.useState(()=>{const M=cc(n);return n||(M.catalogId=i.catalog[0]?.id??""),M}),g=w.useRef(o),p=JSON.stringify(o)!==JSON.stringify(g.current),[b,y]=w.useState(!1),v=n?i.connections.find(M=>M.id===n.id):void 0,S=!!n&&(!v||o.expectedRevision!==v.revision);w.useEffect(()=>{if(!p&&v&&o.expectedRevision!==v.revision){const M=cc(v);g.current=M,m(M)}},[p,v,o.expectedRevision]);const N=()=>{if(!v)return;const M=cc(v);g.current=M,m(M),y(!1)};w.useEffect(()=>(d(p),()=>d(!1)),[p,d]);const D=i.catalog.find(M=>M.id===o.catalogId),z=!n&&i.connections.some(M=>M.id===o.id.trim()),_=(M,H)=>m(oe=>({...oe,[M]:H}));return u.jsx("form",{className:"config-connection-editor",onSubmit:async M=>{M.preventDefault(),!S&&await s("模型连接",H=>Ev(o,H))&&f()},children:u.jsxs("fieldset",{disabled:r,children:[u.jsx("legend",{className:"config-sr-only",children:n?`编辑 ${n.id}`:"新模型连接"}),S&&u.jsxs("div",{className:"config-remove-confirm",role:"alert",children:[u.jsx("p",{children:v?"其他设备已更新这个连接。你的草稿已保留,请检查最新设置后再保存。":"这个连接已被其他设备删除。草稿仍保留,你可以复制内容后关闭编辑。"}),v&&u.jsx("button",{className:"config-button",type:"button",onClick:N,children:"放弃草稿并载入最新设置"})]}),u.jsxs("div",{className:"config-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"连接名称"}),u.jsx("input",{required:!0,maxLength:120,value:o.id,readOnly:!!n,onChange:M=>_("id",M.target.value),placeholder:"例如 work-model",autoComplete:"off"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"服务商"}),u.jsxs("select",{required:!0,disabled:!!n,"aria-label":"服务商",value:o.catalogId,onChange:M=>_("catalogId",M.target.value),children:[n&&!D&&u.jsx("option",{value:o.catalogId,children:o.catalogId}),i.catalog.map(M=>u.jsx("option",{value:M.id,children:M.displayName},M.id))]})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"模型名称"}),u.jsx("input",{required:!0,maxLength:240,value:o.model,onChange:M=>_("model",M.target.value),placeholder:"服务商提供的模型 ID",autoComplete:"off"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"服务地址"}),u.jsx("input",{type:"url","aria-label":"服务地址",value:o.baseUrl,onChange:M=>_("baseUrl",M.target.value),placeholder:D?.defaultBaseUrl||"使用服务商默认地址",autoComplete:"off"}),u.jsx("small",{children:"留空使用服务商默认地址,支持兼容接口。"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsxs("span",{children:["API Key ",n?.hasApiKey&&u.jsx("span",{className:"config-field-meta",children:"已配置"})]}),u.jsx("input",{type:"password","aria-label":"API Key",required:D?.needsKey&&!n?.hasApiKey,value:o.apiKey,onChange:M=>_("apiKey",M.target.value),placeholder:n?.hasApiKey?"留空保留现有 API Key":D?.needsKey?"输入 API Key":"可选",autoComplete:"new-password",spellCheck:!1}),u.jsx("small",{children:n?.hasApiKey?"现有密钥保留在运行 CodeShell 的设备上,输入新值可替换。":"密钥保存在当前工作区配置中。"})]})]}),z&&u.jsx("p",{className:"config-error config-message",role:"alert",children:"连接名称已存在,请使用其他名称或编辑现有连接。"}),u.jsx("p",{className:"config-help",children:"保存后可在连接卡片中测试实际连接。"}),b&&u.jsxs("div",{className:"config-remove-confirm",role:"alert",children:[u.jsx("p",{children:"还有未保存的修改,确定放弃?"}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{type:"button",className:"config-button",onClick:()=>y(!1),children:"继续编辑"}),u.jsx("button",{type:"button",className:"config-button config-button-danger",onClick:f,children:"放弃修改"})]})]}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{type:"button",className:"config-button config-button-quiet",onClick:()=>p?y(!0):f(),children:"取消"}),u.jsx("button",{type:"submit",className:"config-button config-button-primary",disabled:z||S,children:"保存连接"})]})]})})}function o0({title:n,description:i}){return u.jsxs("div",{className:"config-empty",children:[u.jsx("span",{"aria-hidden":"true",children:"◇"}),u.jsx("h3",{children:n}),u.jsx("p",{children:i})]})}function hc(n,i=!1){return Rt(`/api/v1/files/content?path=${encodeURIComponent(n)}${i?"&inline=true":""}`)}function Rm(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function c0({initialPath:n,openVersion:i=0,onAuthLost:r}){const[s,f]=w.useState(""),[d,o]=w.useState(null),[m,g]=w.useState(null),[p,b]=w.useState(!1),[y,v]=w.useState(!1),[S,N]=w.useState(""),[D,z]=w.useState(0),[_,M]=w.useState(""),H=w.useRef(null),oe=w.useRef(r);oe.current=r;const ce=w.useCallback(F=>{F instanceof We&&F.status===401?oe.current():N(F instanceof Error?F.message:"文件读取失败,请重试。")},[]);w.useEffect(()=>{const F=new AbortController;return b(!0),N(""),Ve(`/api/v1/files?path=${encodeURIComponent(s)}`,{signal:F.signal}).then(A=>{F.signal.aborted||o(A)}).catch(A=>{F.signal.aborted||ce(A)}).finally(()=>{F.signal.aborted||b(!1)}),()=>F.abort()},[s,D,ce]);const R=w.useCallback((F,A=!1)=>{H.current?.abort();const G=new AbortController;H.current=G,g(null),v(!0),N(""),Ve(`${hc(F)}&preview=true`,{signal:G.signal}).then(V=>{G.signal.aborted||(A&&f(V.path.split("/").slice(0,-1).join("/")),g(V))}).catch(V=>{G.signal.aborted||ce(V)}).finally(()=>{G.signal.aborted||v(!1)})},[ce]);w.useEffect(()=>{n&&R(n,!0)},[n,i,R]),w.useEffect(()=>()=>H.current?.abort(),[]);const W=F=>{H.current?.abort(),v(!1),g(null),f(F),M("")},ie=d?.files.filter(F=>F.name.toLocaleLowerCase().includes(_.toLocaleLowerCase()))??[];return u.jsxs("section",{className:"hub-library hub-files","aria-labelledby":"hub-files-heading",children:[u.jsxs("header",{className:"library-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{id:"hub-files-heading",children:"工作区文件"}),u.jsx("p",{children:"查看任务生成的内容,下载到当前设备。"})]}),u.jsx("button",{className:"library-button",onClick:()=>{z(F=>F+1),m&&R(m.path)},children:"刷新"})]}),S?u.jsx("div",{className:"library-error",role:"alert",children:S}):null,u.jsxs("nav",{className:"file-breadcrumbs","aria-label":"文件位置",children:[u.jsx("button",{onClick:()=>W(""),children:"工作区"}),(d?.path??s).split("/").filter(Boolean).map((F,A,G)=>u.jsxs(w.Fragment,{children:[u.jsx("span",{"aria-hidden":"true",children:"/"}),u.jsx("button",{onClick:()=>W(G.slice(0,A+1).join("/")),children:F})]},A))]}),u.jsxs("div",{className:`file-columns${m||y?" has-preview":""}`,children:[u.jsxs("div",{className:"file-directory",children:[u.jsxs("label",{className:"library-search",children:[u.jsx("span",{className:"sr-only",children:"筛选当前文件夹"}),u.jsx("input",{type:"search",placeholder:"筛选当前文件夹…",value:_,onChange:F=>M(F.target.value)})]}),u.jsx("div",{className:"file-entries","aria-busy":p,children:p?u.jsx("p",{className:"library-empty",role:"status",children:"正在读取文件…"}):ie.length===0?u.jsx("p",{className:"library-empty",children:_?"没有匹配的文件。":"这个文件夹还没有文件。"}):ie.map(F=>u.jsxs("button",{className:`file-entry${m?.path===F.path?" selected":""}`,onClick:()=>F.kind==="directory"?W(F.path):R(F.path),children:[u.jsx("span",{className:"file-glyph","aria-hidden":"true",children:F.kind==="directory"?"▱":"▤"}),u.jsx("span",{className:"file-entry-name",children:F.name}),u.jsx("span",{className:"file-entry-size",children:F.kind==="directory"?"文件夹":Rm(F.size)})]},F.path))}),d?.truncated?u.jsx("p",{className:"library-hint",children:"这里只显示前 500 项。可以进入子文件夹继续查看。"}):null]}),y||m?u.jsxs("article",{className:"file-preview","aria-label":"文件预览",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("strong",{children:m?.name??"正在打开…"}),m?u.jsx("span",{children:Rm(m.size)}):null]}),u.jsxs("div",{className:"library-actions",children:[m?u.jsx("a",{className:"library-button",href:hc(m.path),download:!0,children:"下载"}):null,u.jsx("button",{className:"library-button",onClick:()=>{H.current?.abort(),v(!1),g(null)},children:"关闭预览"})]})]}),y?u.jsx("p",{className:"library-empty",role:"status",children:"正在读取内容…"}):m?.kind==="text"?u.jsxs(u.Fragment,{children:[u.jsx("pre",{tabIndex:0,children:m.content}),m.truncated?u.jsx("p",{className:"library-hint",children:"预览显示前 512 KB,下载可获取完整内容。"}):null]}):m?.kind==="image"?u.jsx("img",{src:hc(m.path,!0),alt:m.name,onError:()=>N("图片无法预览,可以下载后打开。")}):u.jsx("div",{className:"library-empty",children:"这个文件暂不支持直接预览,可以下载后打开。"})]}):null]})]})}async function Dc(n={}){const i=new URLSearchParams({archived:n.archived??"false",limit:"50"});return n.query&&i.set("query",n.query),n.cursor&&i.set("cursor",n.cursor),Ve(`/api/v1/sessions?${i}`,{signal:n.signal})}function _m(n,i="markdown"){return Rt(`/api/v1/sessions/${encodeURIComponent(n)}/export?format=${i}`)}function f0({onAuthLost:n,onOpen:i,onChanged:r,version:s=0,onDirtyChange:f}){const[d,o]=w.useState(""),[m,g]=w.useState(""),[p,b]=w.useState("false"),[y,v]=w.useState([]),[S,N]=w.useState(null),[D,z]=w.useState(!0),[_,M]=w.useState(!1),[H,oe]=w.useState(""),[ce,R]=w.useState(""),[W,ie]=w.useState(0),[F,A]=w.useState(""),[G,V]=w.useState(null),se=w.useRef(null),ae=w.useRef(null),P=w.useRef(null),E=w.useRef(null);w.useEffect(()=>{G?.id&&se.current?.focus()},[G?.id]),w.useEffect(()=>{G?.error&&ae.current?.focus()},[G?.error]);const U=()=>{V(null),requestAnimationFrame(()=>{P.current?.isConnected?P.current.focus():E.current?.focus()})};w.useEffect(()=>{f?.(!!G||!!F)},[G,F,f]),w.useEffect(()=>()=>f?.(!1),[f]);const te=w.useRef(null),he=w.useRef(null),k=w.useRef({onAuthLost:n,onChanged:r,onOpen:i});k.current={onAuthLost:n,onChanged:r,onOpen:i};const T=w.useCallback(Q=>{Q instanceof We&&Q.status===401?k.current.onAuthLost():oe(Q instanceof Error?Q.message:"会话操作失败,请重试。")},[]);w.useEffect(()=>{const Q=setTimeout(()=>g(d.trim()),200);return()=>clearTimeout(Q)},[d]),w.useEffect(()=>{te.current?.abort();const Q=new AbortController;return te.current=Q,z(!0),M(!1),oe(""),Dc({query:m,archived:p,signal:Q.signal}).then(pe=>{Q.signal.aborted||(v(pe.sessions),N(pe.nextCursor))}).catch(pe=>{Q.signal.aborted||T(pe)}).finally(()=>{Q.signal.aborted||z(!1)}),()=>Q.abort()},[m,p,s,W,T]),w.useEffect(()=>()=>{te.current?.abort(),he.current?.abort()},[]);const K=()=>{if(!S||_||D)return;const Q=new AbortController;te.current?.abort(),te.current=Q,M(!0),Dc({query:m,archived:p,cursor:S,signal:Q.signal}).then(pe=>{Q.signal.aborted||(v(je=>{const Y=new Set(je.map(xe=>xe.sessionId));return[...je,...pe.sessions.filter(xe=>!Y.has(xe.sessionId))]}),N(pe.nextCursor))}).catch(pe=>{Q.signal.aborted||T(pe)}).finally(()=>{Q.signal.aborted||M(!1)})},C=async(Q,pe,je=!1)=>{if(he.current)return;const Y=new AbortController;he.current=Y,A(Q),oe(""),R(""),"title"in pe&&V(xe=>xe&&{...xe,error:""});try{if(await Ve(`/api/v1/sessions/${encodeURIComponent(Q)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(pe),signal:Y.signal}),Y.signal.aborted)return;"title"in pe?(U(),R(pe.title?"标题已保存。":"已恢复自动标题。")):R(pe.archived?"对话已归档,可以在“已归档”中恢复。":"对话已恢复。"),ie(xe=>xe+1),k.current.onChanged?.(),je&&k.current.onOpen(Q)}catch(xe){Y.signal.aborted||("title"in pe&&!(xe instanceof We&&xe.status===401)?V(J=>J?.id===Q?{...J,error:xe instanceof Error?xe.message:"标题保存失败,请重试。",conflict:xe instanceof We&&xe.status===409,unavailable:xe instanceof We&&xe.status===404}:J):T(xe))}finally{he.current===Y&&(he.current=null),Y.signal.aborted||A("")}},re=async()=>{if(!G||he.current)return;const Q=G.id,pe=new AbortController;he.current=pe,A(Q),V(je=>je&&{...je,error:""});try{const je=await Ve(`/api/v1/sessions/${encodeURIComponent(Q)}`,{signal:pe.signal});if(pe.signal.aborted)return;V(Y=>Y?.id===Q?{...Y,expectedTitle:je.customTitle,reviewedTitle:je.title,conflict:!1,unavailable:!1,error:""}:Y),se.current?.focus()}catch(je){pe.signal.aborted||(je instanceof We&&je.status===401?T(je):V(Y=>Y?.id===Q?{...Y,error:je instanceof Error?je.message:"无法读取最新标题,请重试。",unavailable:je instanceof We&&je.status===404}:Y))}finally{he.current===pe&&(he.current=null),pe.signal.aborted||A("")}},ve=Q=>Q.archivedAt?void C(Q.sessionId,{archived:!1},!0):k.current.onOpen(Q.sessionId);return u.jsxs("section",{className:"hub-library hub-sessions","aria-labelledby":"hub-history-heading",children:[u.jsxs("header",{className:"library-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{id:"hub-history-heading",children:"历史对话"}),u.jsx("p",{children:"查找、整理并导出当前工作区的对话。"})]}),u.jsx("button",{className:"library-button",onClick:()=>ie(Q=>Q+1),children:"刷新"})]}),H?u.jsx("div",{className:"library-error",role:"alert",children:H}):null,ce?u.jsx("p",{className:"library-hint",role:"status",children:ce}):null,u.jsxs("div",{className:"session-toolbar",children:[u.jsxs("label",{className:"library-search",children:[u.jsx("span",{className:"sr-only",children:"搜索对话标题"}),u.jsx("input",{ref:E,type:"search",placeholder:"搜索对话标题…",value:d,onChange:Q=>o(Q.target.value)})]}),u.jsxs("label",{children:[u.jsx("span",{className:"sr-only",children:"对话范围"}),u.jsxs("select",{value:p,onChange:Q=>b(Q.target.value),children:[u.jsx("option",{value:"false",children:"当前对话"}),u.jsx("option",{value:"true",children:"已归档"}),u.jsx("option",{value:"all",children:"全部对话"})]})]})]}),G?u.jsxs("form",{className:"session-history-editor","aria-labelledby":"session-title-editor-heading",onSubmit:Q=>{Q.preventDefault(),!F&&!G.conflict&&!G.unavailable&&C(G.id,{title:G.title,expectedTitle:G.expectedTitle})},children:[u.jsxs("div",{children:[u.jsx("h2",{id:"session-title-editor-heading",children:"重命名对话"}),u.jsxs("p",{className:"library-hint",children:["正在编辑:",G.originalTitle]}),!D&&!y.some(Q=>Q.sessionId===G.id)?u.jsx("p",{className:"library-hint",children:"此对话已不在当前列表中,标题草稿仍保留在这里。"}):null]}),G.error?u.jsx("div",{className:"library-error",id:"session-title-error",role:"alert",tabIndex:-1,ref:ae,children:G.error}):null,G.reviewedTitle?u.jsxs("p",{className:"session-title-review",role:"status",children:["最新标题:",u.jsx("strong",{children:G.reviewedTitle}),"。你的草稿仍保留,请核对后再保存。"]}):null,u.jsxs("label",{children:[u.jsx("span",{children:"对话标题"}),u.jsx("input",{ref:se,className:"library-title-input",value:G.title,maxLength:1024,"aria-describedby":G.error?"session-title-error":void 0,onChange:Q=>{const pe=Q.target.value;V(je=>je&&{...je,title:pe})},readOnly:!!F})]}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{type:"submit",className:"library-button primary",disabled:!!F||G.conflict||G.unavailable,children:F?"处理中…":G.reviewedTitle?"确认保存我的标题":"保存标题"}),G.conflict||G.unavailable?u.jsx("button",{type:"button",className:"library-button",disabled:!!F,onClick:()=>{re()},children:"读取最新标题"}):null,u.jsx("button",{type:"button",className:"library-button",disabled:!!F,onClick:U,children:"取消"}),G.expectedTitle?u.jsx("button",{type:"button",className:"library-button",disabled:!!F||G.conflict||G.unavailable,onClick:()=>{C(G.id,{title:"",expectedTitle:G.expectedTitle})},children:"使用自动标题"}):null]})]}):null,u.jsx("div",{className:"session-history-list","aria-busy":D,children:D?u.jsx("p",{className:"library-empty",role:"status",children:"正在读取对话…"}):y.length===0?u.jsx("p",{className:"library-empty",children:m?"没有找到匹配的对话。":p==="true"?"还没有归档的对话。":"还没有保存的对话,开始一条新对话后会显示在这里。"}):y.map(Q=>u.jsxs("article",{className:"session-history-row",children:[u.jsxs("div",{className:"session-history-info",children:[u.jsx("button",{className:"session-history-title",onClick:()=>ve(Q),children:Q.title}),Q.preview&&Q.preview!==Q.title?u.jsx("p",{children:Q.preview.slice(0,150)}):null,u.jsxs("div",{className:"session-history-meta",children:[u.jsx("span",{children:new Date(Q.lastActiveAt||Q.startedAt).toLocaleString()}),u.jsxs("span",{children:[Q.turnCount," 轮"]}),Q.running?u.jsx("span",{children:"正在运行"}):Q.archivedAt?u.jsx("span",{children:"已归档"}):null]})]}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button",disabled:!!F||!!G,onClick:pe=>{P.current=pe.currentTarget,R(""),V({id:Q.sessionId,title:Q.title,originalTitle:Q.title,expectedTitle:Q.customTitle})},children:G?.id===Q.sessionId?"正在编辑":"重命名"}),u.jsx("button",{className:"library-button",disabled:!!F||Q.running,onClick:()=>{C(Q.sessionId,{archived:!Q.archivedAt})},children:F===Q.sessionId?"处理中…":Q.archivedAt?"恢复":"归档"}),Q.running?u.jsx("button",{className:"library-button",disabled:!0,children:"运行结束后导出"}):u.jsxs("details",{className:"session-export",children:[u.jsx("summary",{className:"library-button",children:"导出"}),u.jsxs("div",{children:[u.jsx("a",{href:_m(Q.sessionId),download:!0,children:"Markdown 文档"}),u.jsx("a",{href:_m(Q.sessionId,"json"),download:!0,children:"完整 JSON 记录"})]})]})]})]},Q.sessionId))}),S&&!D?u.jsx("div",{className:"session-load-more",children:u.jsx("button",{className:"library-button",disabled:_,onClick:K,children:_?"读取中…":"加载更多"})}):null]})}const Ol="/api/v1/links",d0={connected:"已连接",expired:"授权已过期",invalid:"需要重新连接",unavailable:"凭据不可用"};function Vi(n){try{const i=new URL(n??"");return i.protocol==="https:"&&!i.username&&!i.password?i.href:void 0}catch{return}}function h0({onAuthLost:n,onDirtyChange:i,hostLabel:r="服务端",configurationVersion:s=0}){const[f,d]=w.useState(),[o,m]=w.useState(),[g,p]=w.useState(""),[b,y]=w.useState(""),[v,S]=w.useState(""),[N,D]=w.useState(!0),[z,_]=w.useState(!1),[M,H]=w.useState(),[oe,ce]=w.useState(),[R,W]=w.useState(),[ie,F]=w.useState(0),A=w.useRef(!1),G=w.useRef(void 0),V=w.useRef(void 0),se=w.useRef(void 0),ae=w.useRef({onAuthLost:n,onDirtyChange:i});ae.current={onAuthLost:n,onDirtyChange:i};const P=z||R?.state==="pending"||!!(o&&(o.token||o.label!==(o.original?.label??o.provider.displayName))),E=w.useCallback(J=>{J instanceof We&&J.status===401?ae.current.onAuthLost():y(J instanceof Error?J.message:"连接操作失败,请重试。")},[]);w.useEffect(()=>{ae.current.onDirtyChange?.(P)},[P]),w.useEffect(()=>(A.current=!0,()=>{A.current=!1,ae.current.onDirtyChange?.(!1),G.current?.abort(),V.current&&Ve(V.current,{method:"DELETE",keepalive:!0}).catch(()=>{})}),[]),w.useEffect(()=>{const J=new AbortController;return se.current=J,D(!0),Ve(Ol,{signal:J.signal}).then(ye=>{J.signal.aborted||d(ye)}).catch(ye=>{J.signal.aborted||E(ye)}).finally(()=>{J.signal.aborted||D(!1)}),()=>J.abort()},[ie,s,E]),w.useEffect(()=>{if(R?.state!=="pending"||!V.current)return;const J=V.current,ye=new AbortController;let Ae;const we=async()=>{try{const Ye=await Ve(J,{signal:ye.signal});if(ye.signal.aborted||V.current!==J)return;W(Ye),Ye.state==="connected"?(V.current=void 0,m(void 0),S("授权完成,连接已保存。"),F(nt=>nt+1)):Ye.state!=="pending"?(V.current=void 0,y(Ye.state==="cancelled"?"授权已取消。":"授权未完成或已过期,请重新开始。")):Ae=setTimeout(()=>{we()},2e3)}catch(Ye){if(ye.signal.aborted||V.current!==J)return;E(Ye),Ye instanceof We&&[401,404].includes(Ye.status)?(V.current=void 0,W(nt=>nt?{...nt,state:"failed"}:void 0)):Ae=setTimeout(()=>{we()},4e3)}};return Ae=setTimeout(()=>{we()},1e3),()=>{ye.abort(),clearTimeout(Ae)}},[R?.id,R?.state,E]);async function U(J,ye){if(G.current)return;const Ae=new AbortController;G.current=Ae,se.current?.abort(),_(!0),D(!1),y(""),S("");try{const we=await J(Ae.signal);A.current&&!Ae.signal.aborted&&ye(we)}catch(we){A.current&&!Ae.signal.aborted&&(E(we),we instanceof We&&we.status===409&&F(Ye=>Ye+1))}finally{G.current===Ae&&(G.current=void 0),A.current&&_(!1)}}function te(J,ye,Ae,we){return Ve(J,{method:ye,headers:{"Content-Type":"application/json"},body:JSON.stringify(Ae),signal:we})}function he(){return{providerId:o.provider.id,methodId:o.methodId,label:o.label.trim(),expectedRevision:o.original?.revision??null,...o.original?{connectionId:o.original.id}:{}}}function k(){m(void 0),ce(void 0),S("连接已保存。"),F(J=>J+1)}function T(J,ye){if(z||R?.state==="pending"||P&&!window.confirm("放弃当前未保存的连接修改?"))return;const Ae=J.connectionMethods.find(we=>we.id===ye?.methodId)??J.connectionMethods.find(we=>we.executionRuntime==="local"&&we.availability==="available");Ae&&(m({provider:J,original:ye,methodId:Ae.id,label:ye?.label??J.displayName,token:""}),ce(void 0),W(void 0),y(""),S(""))}async function K(){if(!V.current)return;const J=V.current;await U(ye=>Ve(J,{method:"DELETE",signal:ye}),()=>{V.current=void 0,W(void 0),S("授权已取消。")})}function C(J){const ye=o?.original?.id===J.id&&R?.state==="pending"?V.current:void 0,Ae=Rt(`${Ol}/connections/${encodeURIComponent(J.id)}`);U(async we=>{if(ye){try{await Ve(ye,{method:"DELETE",signal:we})}catch(Ye){if(!(Ye instanceof We&&Ye.status===404))throw Ye}A.current&&!we.aborted&&V.current===ye&&(V.current=void 0,W(void 0))}return te(Ae,"DELETE",{expectedRevision:J.revision},we)},()=>{o?.original?.id===J.id&&m(void 0),H(void 0),F(we=>we+1),S("连接已断开。")})}const re=o?.provider.connectionMethods.find(J=>J.id===o.methodId),ve=R?.state==="pending",Q=z||ve,pe=g.trim().toLowerCase(),je=(f?.providers??[]).filter(J=>`${J.displayName} ${J.description.zh}`.toLowerCase().includes(pe)),Y=o&&f?.connections.find(J=>o.original?J.id===o.original.id:J.id===`link-${o.provider.id}-${o.methodId}`&&J.providerId===o.provider.id&&J.methodId===o.methodId),xe=o&&f&&(o.original?Y?.revision!==o.original.revision:!!Y);return u.jsxs("section",{className:"hub-links",children:[u.jsxs("header",{className:"links-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{children:"Link"}),u.jsx("p",{children:"连接你的工具与账号,让任务访问已授权的服务。"})]}),u.jsx("button",{onClick:()=>{y(""),F(J=>J+1)},disabled:z||N,children:"刷新"})]}),u.jsxs("p",{className:"links-host",children:["连接由",r,"执行,凭据保存在",r,"。CLI 使用这台机器上已有的登录。"]}),b&&u.jsx("p",{className:"form-error",role:"alert",children:b}),v&&u.jsx("p",{className:"links-notice",role:"status",children:v}),N&&!f&&u.jsx("p",{role:"status",children:"正在加载连接…"}),u.jsx("h2",{children:"已连接"}),f&&f.connections.length===0&&u.jsx("p",{className:"links-muted",children:"还没有连接。选择下面的服务开始。"}),u.jsx("div",{className:"links-connections",children:f?.connections.map(J=>{const ye=f.providers.find(Ae=>Ae.id===J.providerId);return u.jsxs("article",{className:"links-connection",children:[u.jsxs("div",{children:[u.jsx("strong",{children:J.label}),u.jsxs("p",{children:[ye?.displayName??J.providerId," ·"," ",J.account?.label??J.account?.id??"已授权账号"]}),u.jsx("span",{className:`links-state ${J.status==="connected"?"ready":""}`,children:d0[J.status]}),u.jsxs("small",{children:[J.authSource==="cli-session"?"CLI 登录":J.authSource==="browser-oauth"?"浏览器授权":"Token",J.expiresAt?` · 到期 ${new Date(J.expiresAt).toLocaleString()}`:""]}),J.account?.resources.length?u.jsx("p",{children:J.account.resources.join("、")}):null]}),u.jsx("div",{className:"links-actions",children:J.editable?u.jsxs(u.Fragment,{children:[u.jsx("button",{disabled:Q||!ye,onClick:()=>ye&&T(ye,J),children:"管理连接"}),u.jsx("button",{disabled:z,onClick:()=>H(J),children:"断开"})]}):u.jsx("small",{children:"项目配置管理"})})]},J.id)})}),M&&u.jsxs("div",{className:"links-confirm",role:"alertdialog","aria-label":"断开连接",children:[u.jsxs("p",{children:["断开「",M.label,"」后,后续任务将无法使用这个连接,正在执行的请求会尝试停止。"]}),u.jsx("button",{disabled:z,onClick:()=>C(M),children:"确认断开"}),u.jsx("button",{disabled:z,onClick:()=>H(void 0),children:"取消"})]}),o&&re&&u.jsxs("section",{className:"links-editor","aria-label":`${o.provider.displayName} 连接设置`,children:[u.jsxs("div",{className:"links-heading",children:[u.jsxs("h2",{children:[o.provider.displayName," · ",o.original?"管理连接":"添加连接"]}),u.jsx("button",{disabled:Q,onClick:()=>{(!P||window.confirm("放弃未保存的连接修改?"))&&m(void 0)},children:"关闭"})]}),u.jsxs("label",{children:["连接名称",u.jsx("input",{maxLength:100,value:o.label,disabled:Q,onChange:J=>m({...o,label:J.target.value})})]}),xe&&u.jsxs("div",{className:"links-conflict",role:"alert",children:[u.jsx("p",{children:"这个连接已在其他设备创建、修改或删除。你的输入仍然保留,请先载入最新版本。"}),u.jsx("button",{disabled:Q,onClick:()=>m({...o,original:Y||void 0}),children:"载入最新版本,保留输入"})]}),re.browserAuth&&u.jsxs("div",{className:"links-auth-option",children:[u.jsx("h3",{children:"浏览器授权"}),o.provider.deviceAuth?.configured?u.jsx("button",{disabled:Q||!o.label.trim()||!!xe,onClick:()=>{const J=Jc()??"",ye=Us(),Ae=Rt(`${Ol}/authorizations/device`,J,ye);U(we=>te(Ae,"POST",he(),we),we=>{V.current=Rt(`${Ol}/authorizations/${encodeURIComponent(we.id)}`,J,ye),W(we)})},children:"开始授权"}):u.jsxs("p",{className:"links-muted",children:["这台",r,"尚未配置此服务的浏览器授权,可使用下面的连接方式。"]}),ve&&R.prompt&&u.jsxs("div",{className:"links-device-code",role:"status",children:[u.jsx("p",{children:"在服务商页面输入验证码:"}),u.jsx("strong",{children:R.prompt.userCode}),u.jsx("p",{children:Vi(R.prompt.verificationUriComplete??R.prompt.verificationUri)&&u.jsx("a",{href:Vi(R.prompt.verificationUriComplete??R.prompt.verificationUri),target:"_blank",rel:"noreferrer",children:"打开授权页面 ↗"})}),u.jsxs("p",{children:["完成后会自动保存。有效期至"," ",new Date(R.prompt.expiresAt).toLocaleTimeString(),"。"]}),u.jsx("button",{disabled:z,onClick:()=>{K()},children:"取消授权"})]})]}),re.quickAuth&&u.jsxs("div",{className:"links-auth-option",children:[u.jsx("h3",{children:"使用已登录的 CLI"}),u.jsxs("p",{children:[r,"需要已安装并登录 ",re.quickAuth.command,"。"]}),u.jsx("button",{disabled:Q,onClick:()=>{U(J=>Ve(`${Ol}/providers/${encodeURIComponent(o.provider.id)}/cli`,{signal:J}),ce)},children:"检查登录状态"}),oe&&u.jsx("p",{role:"status",children:oe.authenticated?`已登录${oe.account?`:${oe.account}`:""}`:oe.installed?"已安装,尚未登录。请在运行服务的机器上登录。":"尚未安装。"}),oe?.authenticated&&u.jsx("button",{disabled:Q||!o.label.trim()||!!xe,onClick:()=>{U(J=>te(`${Ol}/connections/cli`,"POST",he(),J),k)},children:"绑定这个登录"})]}),u.jsxs("form",{className:"links-auth-option",onSubmit:J=>{J.preventDefault(),!(Q||xe)&&U(ye=>o.original&&!o.token.trim()?te(`${Ol}/connections/${encodeURIComponent(o.original.id)}`,"PATCH",{label:o.label.trim(),expectedRevision:o.original.revision},ye):te(`${Ol}/connections/token`,"POST",{...he(),token:o.token.trim()},ye),k)},children:[u.jsx("h3",{children:o.original?"名称与 Token":"使用 Token"}),re.authGuide&&u.jsxs(u.Fragment,{children:[u.jsx("p",{children:re.authGuide.summary.zh}),u.jsxs("div",{className:"links-actions",children:[Vi(re.authGuide.createCredentialUrl)&&u.jsx("a",{href:Vi(re.authGuide.createCredentialUrl),target:"_blank",rel:"noreferrer",children:"创建凭据 ↗"}),Vi(re.authGuide.docsUrl)&&u.jsx("a",{href:Vi(re.authGuide.docsUrl),target:"_blank",rel:"noreferrer",children:"授权说明 ↗"})]}),u.jsxs("details",{children:[u.jsx("summary",{children:"所需权限与设置步骤"}),u.jsx("ul",{children:re.authGuide.permissions.map(J=>u.jsxs("li",{children:[J.label,"(",J.level==="required"?"必需":"可选",")",J.description?`:${J.description.zh}`:""]},J.id))}),u.jsx("ol",{children:re.authGuide.steps.map((J,ye)=>u.jsx("li",{children:J.zh},ye))})]})]}),u.jsxs("label",{children:[re.tokenLabel??o.provider.tokenLabel,u.jsx("input",{type:"password",autoComplete:"off",value:o.token,disabled:Q,placeholder:o.original?"留空保留当前授权,仅修改名称":re.tokenPlaceholder??o.provider.tokenPlaceholder,onChange:J=>m({...o,token:J.target.value}),required:!o.original,maxLength:16384})]}),u.jsx("button",{type:"submit",className:"send",disabled:Q||!!xe||!o.label.trim(),children:z?"正在验证并保存…":o.token.trim()||!o.original?"验证并保存":"保存名称"})]}),u.jsxs("details",{children:[u.jsxs("summary",{children:["可用操作(",o.provider.actions.length,")"]}),u.jsx("ul",{children:o.provider.actions.map(J=>u.jsxs("li",{children:[u.jsx("strong",{children:J.title}),J.risk==="write"?" · 执行前需要确认":"",u.jsx("p",{children:J.description})]},J.id))})]})]}),u.jsxs("div",{className:"links-heading",children:[u.jsx("h2",{children:"添加服务"}),u.jsx("input",{type:"search","aria-label":"搜索 Link 服务",placeholder:"搜索服务",value:g,onChange:J=>p(J.target.value)})]}),u.jsx("div",{className:"links-providers",children:je.map(J=>{const ye=f?.connections.find(Ae=>Ae.providerId===J.id);return u.jsxs("article",{className:"links-provider",children:[u.jsx("div",{className:`links-brand accent-${J.accent}`,"aria-hidden":"true",children:J.brandText}),u.jsx("h3",{children:J.displayName}),u.jsx("p",{children:J.description.zh}),u.jsxs("small",{children:[J.actions.length," 项操作"]}),u.jsx("button",{disabled:Q||!!(ye&&!ye.editable),onClick:()=>T(J,ye),children:ye?ye.editable?"管理连接":"项目配置管理":"添加连接"})]},J.id)})}),f&&je.length===0&&u.jsx("p",{className:"links-muted",children:"没有匹配的服务。"})]})}const Dm="/api/v1/panels",Om="https://github.com/cjhyy/codeshell-panel-apps.git",p0={"context.session":"读取当前对话信息","context.workspace":"读取当前工作区信息",storage:"保存面板自己的数据","external.open":"打开外部网页","agent.submitPrompt":"向当前对话提交任务","agent.task":"创建和管理 Agent 任务","workspace.info":"查看工作区信息","workspace.read":"读取工作区文件","workspace.write":"修改工作区文件","notifications.send":"发送通知","audio.transcribe":"将音频转成文字","credentials.cookies":"使用宿主授权的浏览器 Cookie","automations.manage":"管理自动化任务",process:"在宿主运行命令和进程",media:"处理宿主上的音视频文件","media.capture":"使用麦克风、摄像头或屏幕录制"};function sl(n){return n["zh-CN"]||n.default}function Mm({value:n}){return n.supported&&n.reasons.length===0?null:u.jsxs("div",{className:"panels-warning",children:[u.jsx("strong",{children:n.supported?"部分功能可用":"当前 Web 工作台暂不支持此面板"}),n.supported&&u.jsx("p",{children:"可以打开面板,以下功能当前不可用或需要额外配置。"}),n.reasons.length>0&&u.jsx("ul",{children:n.reasons.map(i=>u.jsx("li",{children:i},i))})]})}function m0({onAuthLost:n,onDirtyChange:i,onChanged:r,onOpen:s,hostLabel:f="服务端",configurationVersion:d=0}){const[o,m]=w.useState(),[g,p]=w.useState(""),[b,y]=w.useState(""),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(),[M,H]=w.useState(),[oe,ce]=w.useState(),[R,W]=w.useState(),[ie,F]=w.useState(!1),[A,G]=w.useState(!0),[V,se]=w.useState(!1),[ae,P]=w.useState(),[E,U]=w.useState(!0),[te,he]=w.useState(""),[k,T]=w.useState(""),[K,C]=w.useState(""),[re,ve]=w.useState(0),Q=w.useRef(!1),pe=w.useRef(void 0),je=w.useRef(void 0),Y=w.useRef(!1),xe=w.useRef(null),J=w.useRef({onAuthLost:n,onDirtyChange:i,onChanged:r,onOpen:s});J.current={onAuthLost:n,onDirtyChange:i,onChanged:r,onOpen:s};const ye=!!(te||M||R||ae||g.trim()||b.trim()||v.trim()),Ae=w.useCallback(B=>{B instanceof We&&B.status===401?J.current.onAuthLost():T(B instanceof Error?B.message:"面板操作失败,请重试。")},[]);w.useEffect(()=>(Q.current=!0,()=>{Q.current=!1,pe.current?.abort(),je.current?.abort(),J.current.onDirtyChange?.(!1)}),[]),w.useEffect(()=>{J.current.onDirtyChange?.(ye)},[ye]),w.useEffect(()=>{if(pe.current){Y.current=!0;return}const B=new AbortController;return je.current=B,U(!0),Ve(Rt(Dm),{signal:B.signal}).then(Se=>{B.signal.aborted||m(Se)}).catch(Se=>{B.signal.aborted||Ae(Se)}).finally(()=>{B.signal.aborted||U(!1)}),()=>B.abort()},[re,d,Ae]),w.useEffect(()=>{M&&xe.current?.focus()},[M?.reviewToken]);async function we(B,Se,Ke,lt,Be=!1){if(pe.current)return;const q=new AbortController;pe.current=q,je.current?.abort(),U(!1),he(B),T(""),C("");const ze=Rt(`${Dm}${Se}`);try{const St=await Ve(ze,{method:Ke,headers:{"Content-Type":"application/json"},body:JSON.stringify(lt),signal:q.signal});return q.signal.aborted||!Q.current?void 0:(Be&&(Y.current=!0,J.current.onChanged?.()),St)}catch(St){if(q.signal.aborted||!Q.current)return;St instanceof We&&(St.status===409||St.status===410)&&(M&&F(!0),Y.current=!0),Ae(St);return}finally{pe.current===q&&(pe.current=void 0),Q.current&&!q.signal.aborted&&(he(""),Y.current&&(Y.current=!1,ve(St=>St+1)))}}const Ye=async B=>{W(void 0),H(void 0),P(void 0),_(void 0);const Se=await we("正在读取仓库…","/github/discover","POST",{url:B.url,...B.ref?{ref:B.ref}:{},...B.subdir?{subdir:B.subdir}:{}});Se&&_(Se)},nt=async B=>{const Se=await we("正在准备安装审阅…","/preview","POST",{source:B});Se&&(P(void 0),ce(B),H(Se),F(!1),se(!1),G(!!o?.hasProject&&Se.compatibility.supported))},jt=async B=>{const Se=await we("正在检查更新…",`/${encodeURIComponent(B.id)}/update-preview`,"POST",{expectedRevision:B.revision});Se&&(P(void 0),ce(void 0),H(Se),F(!1),se(B.bound),G(B.bound&&Se.compatibility.supported))},Yt=()=>{if(M)if(M.kind==="update"){const B=o?.panels.find(Se=>Se.id===M.preview.id);B?jt(B):(T("此面板已被卸载,请重新从 GitHub 选择安装。"),H(void 0))}else oe&&nt(oe)},at=()=>{W(void 0),_(void 0),p(""),y(""),S("")},mt=async()=>{if(H(void 0),!R||R.position+1>=R.candidates.length){at();return}const B=R.position+1;W({...R,position:B}),await nt(R.candidates[B].source)},ut=async B=>{B.length&&(W({candidates:B,position:0}),await nt(B[0].source))},ot=async()=>{if(!M||ie)return;if(M.expiresAt<=Date.now()){F(!0),T("安装审阅已过期,请重新审阅后继续。");return}await we(M.kind==="update"?"正在更新面板…":"正在安装面板…","/install","POST",{reviewToken:M.reviewToken,bind:A},!0)&&(C(`${sl(M.preview.title)} 已${M.kind==="update"?"更新":"安装"}${A?"并绑定当前工作区":""}。`),H(void 0),R?await mt():at())},Gt=async B=>{const Se=await we(B.bound?"正在解除绑定…":"正在绑定工作区…",`/${encodeURIComponent(B.id)}/binding`,"PATCH",{bound:!B.bound,expectedRevision:B.revision},!0);Se&&(m(Se),C(`${sl(B.title)} 已${B.bound?"解除当前工作区绑定":"绑定当前工作区"}。`))},vt=async()=>{if(!ae||o?.panels.find(Se=>Se.id===ae.id)?.revision!==ae.revision)return;(await we("正在卸载面板…",`/${encodeURIComponent(ae.id)}`,"DELETE",{expectedRevision:ae.revision},!0))?.removed&&(C(`${sl(ae.title)} 已卸载。`),P(void 0))},qt=!!te||!o||!!R,ne=N.trim().toLowerCase(),me=(o?.panels??[]).filter(B=>[sl(B.title),B.id,B.description??"",B.source.label].join(" ").toLowerCase().includes(ne)),Te=z?.panels.filter(B=>!o?.panels.some(Se=>Se.id===B.id)&&z.panels.filter(Se=>Se.id===B.id).length===1)??[],ge=ae&&o?.panels.find(B=>B.id===ae.id),ke=!!ae&&ge?.revision!==ae.revision,Ce=M?.kind==="update"?o?.panels.find(B=>B.id===M.preview.id):void 0;return u.jsxs("section",{className:"hub-panels",children:[u.jsxs("header",{className:"panels-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{children:"面板"}),u.jsx("p",{children:"从 GitHub 安装工具面板,绑定工作区后直接在工作台中打开。"})]}),u.jsx("button",{disabled:!!te||E,onClick:()=>ve(B=>B+1),children:E?"正在刷新…":"刷新"})]}),u.jsxs("p",{className:"panels-muted",children:["面板安装在",f,"上,文件和任务操作使用当前工作区。"]}),o&&!o.hasProject&&u.jsx("div",{className:"panels-warning",children:"请先选择一个项目,才能绑定和打开面板。"}),k&&u.jsx("p",{role:"alert",className:"error",children:k}),K&&u.jsx("p",{role:"status",className:"panels-notice",children:K}),te&&u.jsx("p",{role:"status",className:"panels-muted",children:te}),R&&u.jsxs("section",{className:"panels-confirm","aria-label":"逐个审阅面板",children:[u.jsxs("p",{children:["正在审阅第 ",R.position+1," / ",R.candidates.length," 个面板:",sl(R.candidates[R.position].title),"。每个面板都需要单独确认安装。"]}),u.jsxs("div",{className:"panels-actions",children:[!M&&u.jsx("button",{disabled:!!te,onClick:()=>{nt(R.candidates[R.position].source)},children:"重新读取此面板"}),u.jsx("button",{disabled:!!te,onClick:()=>{mt()},children:"跳过此面板"}),u.jsx("button",{disabled:!!te,onClick:()=>{W(void 0),H(void 0),T("")},children:"取消逐个审阅"})]})]}),M&&u.jsxs("section",{className:"panels-review","aria-labelledby":"panel-review-heading",children:[u.jsxs("header",{className:"panels-heading",children:[u.jsxs("div",{children:[u.jsx("h2",{id:"panel-review-heading",ref:xe,tabIndex:-1,children:M.kind==="update"?"审阅面板更新":"审阅面板安装"}),u.jsxs("p",{children:[sl(M.preview.title)," · ",M.preview.id," · v",M.preview.version]})]}),u.jsx("button",{disabled:!!te,onClick:()=>{W(void 0),H(void 0),T("")},children:"取消审阅"})]}),M.preview.description&&u.jsx("p",{children:M.preview.description}),Ce&&u.jsxs("p",{className:"panels-warning",children:["当前版本 v",Ce.version," → 更新后 v",M.preview.version,Ce.source.commit&&u.jsxs(u.Fragment,{children:[u.jsx("br",{}),"当前提交 ",u.jsx("code",{children:Ce.source.commit.slice(0,12)})," → 更新提交"," ",u.jsx("code",{children:M.source.commit.slice(0,12)})]})]}),u.jsxs("section",{children:[u.jsx("h3",{children:"安装来源"}),u.jsxs("dl",{children:[u.jsx("dt",{children:"仓库"}),u.jsx("dd",{children:M.source.url}),u.jsx("dt",{children:"分支 / 标签"}),u.jsx("dd",{children:M.source.ref}),u.jsx("dt",{children:"已锁定提交"}),u.jsx("dd",{children:u.jsx("code",{children:M.source.commit})}),u.jsx("dt",{children:"面板目录"}),u.jsx("dd",{children:M.source.subdir||"仓库根目录"}),u.jsx("dt",{children:"界面入口"}),u.jsx("dd",{children:u.jsx("code",{children:M.preview.entry})})]})]}),u.jsxs("section",{children:[u.jsx("h3",{children:"面板请求的权限"}),M.preview.permissions.length===0?u.jsx("p",{className:"panels-muted",children:"未申请宿主权限。"}):M.preview.permissions.map(B=>u.jsxs("div",{className:"panels-permission",children:[u.jsx("span",{children:p0[B]??B}),u.jsx("small",{children:B})]},B))]}),u.jsxs("section",{children:[u.jsx("h3",{children:"随面板安装的工具与 Skills"}),M.preview.agent?.tools.length||M.preview.agent?.skills.length?u.jsxs("div",{className:"panels-badges",children:[M.preview.agent?.tools.map(B=>u.jsxs("span",{className:"panels-badge",title:B.description,children:[B.name," · ",B.readOnly?"只读":"可修改数据"]},B.name)),M.preview.agent?.skills.map(B=>u.jsxs("span",{className:"panels-badge",children:["Skill · ",B.split("/").at(-2)??B]},B))]}):u.jsx("p",{className:"panels-muted",children:"此面板没有额外的 Agent 工具或 Skills。"})]}),u.jsx(Mm,{value:M.compatibility}),M.preview.warnings.length>0&&u.jsx("div",{className:"panels-warning",children:u.jsx("ul",{children:M.preview.warnings.map(B=>u.jsx("li",{children:B},B))})}),u.jsxs("footer",{children:[!M.compatibility.supported&&u.jsxs("p",{className:"panels-muted",children:["可以安装到",f,",但当前 Web 工作台无法绑定或打开它。"]}),V?u.jsx("p",{className:"panels-muted",children:"已绑定当前工作区,更新将保留绑定。"}):u.jsxs("label",{className:"panels-check",children:[u.jsx("input",{type:"checkbox",checked:A,disabled:!!te||!o?.hasProject||!M.compatibility.supported,onChange:B=>G(B.target.checked)}),"绑定当前工作区"]}),ie?u.jsxs("div",{className:"panels-actions",children:[u.jsx("span",{className:"panels-muted",children:"安装内容或本地版本已变化,请重新审阅。"}),u.jsx("button",{disabled:!!te,onClick:Yt,children:"重新审阅"})]}):u.jsx("button",{className:"panels-primary",disabled:!!te,onClick:()=>{ot()},children:M.kind==="update"?"确认更新":"确认安装"})]})]}),u.jsxs("section",{className:"panels-section","aria-labelledby":"installed-panels-heading",children:[u.jsxs("div",{className:"panels-heading",children:[u.jsxs("h2",{id:"installed-panels-heading",children:["已安装面板",o?` · ${o.panels.length}`:""]}),u.jsx("input",{type:"search","aria-label":"搜索已安装面板",placeholder:"搜索已安装面板",value:N,onChange:B=>D(B.target.value)})]}),!o&&u.jsx("p",{className:"panels-muted",children:E?"正在读取面板…":"暂时无法读取面板,请刷新重试。"}),o&&me.length===0&&u.jsxs("div",{className:"panels-empty",children:[u.jsx("strong",{children:o.panels.length?"没有匹配的面板":"还没有安装面板"}),u.jsx("p",{className:"panels-muted",children:o.panels.length?"试试其他名称或清除搜索。":"在下方粘贴 GitHub 仓库地址,或浏览官方面板仓库。"})]}),u.jsx("div",{className:"panels-grid",children:me.map(B=>u.jsxs("article",{className:"panels-card",children:[u.jsxs("div",{className:"panels-card-heading",children:[u.jsx("h3",{children:sl(B.title)}),u.jsxs("span",{className:"panels-badge",children:["v",B.version]})]}),u.jsx("small",{children:B.id}),B.description&&u.jsx("p",{children:B.description}),u.jsx("div",{className:"panels-badges",children:u.jsx("span",{className:`panels-badge ${B.enabled&&B.compatibility.supported?"panels-badge-ready":""}`,children:B.globalDisabled?"已全局停用":B.bound?"已绑定当前工作区":"未绑定当前工作区"})}),u.jsxs("dl",{children:[u.jsx("dt",{children:"来源"}),u.jsx("dd",{children:B.source.label}),B.source.ref&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"分支 / 标签"}),u.jsx("dd",{children:B.source.ref})]})]}),u.jsx(Mm,{value:B.compatibility}),B.globalDisabled&&u.jsx("p",{className:"panels-muted",children:"请在宿主配置中启用此面板后使用。"}),u.jsxs("div",{className:"panels-actions",children:[u.jsx("button",{className:"panels-primary",disabled:qt||!B.enabled||!B.compatibility.supported,onClick:()=>J.current.onOpen(B),children:"打开面板"}),u.jsx("button",{disabled:qt||!o?.hasProject||!B.bound&&(B.globalDisabled||!B.compatibility.supported),onClick:()=>{Gt(B)},children:B.bound?"解除绑定":"绑定工作区"}),B.updatable&&u.jsx("button",{disabled:qt,onClick:()=>{jt(B)},children:"检查更新"}),u.jsx("button",{className:"panels-danger",disabled:qt,onClick:()=>{P(B),H(void 0),T(""),C("")},children:"卸载"})]})]},B.id))}),ae&&u.jsxs("section",{className:"panels-confirm","aria-label":"确认卸载面板",children:[u.jsxs("p",{children:["卸载「",sl(ae.title),"」v",ae.version,"?面板将从",f,"移除,其他工作区也将无法打开它。"]}),u.jsxs("div",{className:"panels-actions",children:[u.jsx("button",{disabled:!!te,onClick:()=>P(void 0),children:"取消卸载"}),ke&&u.jsx("span",{className:"panels-muted",children:ge?"面板已被其他设备修改,请查看最新版本后重新确认。":"此面板已被其他设备卸载。"}),ke&&ge&&u.jsx("button",{disabled:!!te||E,onClick:()=>{P(ge),T("")},children:"查看最新版本"}),u.jsx("button",{className:"panels-danger",disabled:!!te||E||ke,onClick:()=>{vt()},children:"确认卸载"})]})]})]}),u.jsxs("section",{className:"panels-import panels-section","aria-labelledby":"github-panels-heading",children:[u.jsxs("div",{className:"panels-heading",children:[u.jsxs("div",{children:[u.jsx("h2",{id:"github-panels-heading",children:"从 GitHub 安装"}),u.jsx("p",{children:"先读取仓库并选择面板,再查看安装内容和所需权限。"})]}),u.jsx("button",{disabled:qt,onClick:()=>{p(Om),y(""),S(""),Ye({url:Om})},children:"浏览官方仓库"})]}),u.jsxs("form",{onSubmit:B=>{B.preventDefault(),g.trim()&&Ye({url:g.trim(),...b.trim()?{ref:b.trim()}:{},...v.trim()?{subdir:v.trim()}:{}})},children:[u.jsxs("label",{children:["GitHub 仓库地址",u.jsx("input",{type:"url",placeholder:"https://github.com/owner/repository",value:g,required:!0,disabled:!!te||!!R,onChange:B=>{p(B.target.value),_(void 0)}})]}),u.jsxs("details",{children:[u.jsx("summary",{children:"指定分支或子目录"}),u.jsxs("div",{className:"panels-source-fields",children:[u.jsxs("label",{children:["分支 / 标签(可选)",u.jsx("input",{value:b,placeholder:"使用默认分支",disabled:!!te||!!R,onChange:B=>{y(B.target.value),_(void 0)}})]}),u.jsxs("label",{children:["子目录(可选)",u.jsx("input",{value:v,placeholder:"例如 apps/my-panel",disabled:!!te||!!R,onChange:B=>{S(B.target.value),_(void 0)}})]})]})]}),u.jsxs("div",{className:"panels-actions",children:[u.jsx("button",{type:"submit",disabled:qt||!g.trim(),children:"读取仓库"}),(g||b||v||z)&&u.jsx("button",{type:"button",disabled:!!te,onClick:()=>{at(),H(void 0)},children:"清除"})]})]}),z&&u.jsxs("div",{className:"panels-candidates",children:[u.jsxs("h3",{children:["找到 ",z.panels.length," 个面板"]}),u.jsxs("p",{className:"panels-muted",children:[z.source.url," · ",z.source.ref," ·"," ",u.jsx("code",{children:z.source.commit.slice(0,12)})]}),z.panels.length===0&&u.jsx("p",{className:"panels-muted",children:"仓库中没有找到可安装的面板。请检查地址和子目录。"}),Te.length>1&&u.jsxs("div",{className:"panels-actions panels-batch-start",children:[u.jsxs("button",{disabled:qt,onClick:()=>{ut(Te)},children:["逐个审阅未安装面板(",Te.length,")"]}),u.jsx("small",{children:"按顺序确认,可随时跳过或停止。"})]}),u.jsx("div",{className:"panels-grid",children:z.panels.map(B=>{const Se=o?.panels.find(Ke=>Ke.id===B.id);return u.jsxs("article",{className:"panels-card",children:[u.jsxs("div",{className:"panels-card-heading",children:[u.jsx("h3",{children:sl(B.title)}),u.jsxs("span",{className:"panels-badge",children:["v",B.version]})]}),B.description&&u.jsx("p",{children:B.description}),u.jsx("small",{children:B.subdir==="."?"仓库根目录":B.subdir}),u.jsx("div",{className:"panels-actions",children:u.jsx("button",{disabled:qt||!!(Se&&!Se.updatable),onClick:()=>Se?void jt(Se):void nt(B.source),children:Se?Se.updatable?"已安装 · 检查更新":"已从其他来源安装":"审阅安装"})})]},`${B.id}:${B.subdir}`)})}),z.issues.length>0&&u.jsxs("div",{className:"panels-warning",children:[u.jsx("strong",{children:"部分目录无法作为面板安装"}),u.jsx("ul",{children:z.issues.map(B=>u.jsxs("li",{children:[B.subdir,":",B.error]},B.subdir))})]})]})]})]})}function g0(n){const i=n.projectId===void 0?Us():n.projectId,r=`/api/v1/panels/runtime/${encodeURIComponent(n.instanceId)}`,s=new Set,f=new Set;let d=!1,o=n.expiresAt,m=o-6e4,g,p=0,b=0,y=0,v,S;const N=(A,G)=>{const V=setTimeout(()=>{s.delete(V),d||A()},Math.max(0,Math.min(G,2147483647)));return s.add(V),V},D=A=>{A!==void 0&&(clearTimeout(A),s.delete(A))},z=()=>{if(!d){d=!0;for(const A of s)clearTimeout(A);s.clear();for(const A of f)A.abort();f.clear()}},_=A=>{d||(z(),n.onTerminal(A))},M=()=>_(new Error("面板连接已到期,请重新打开继续使用。")),H=A=>A instanceof We&&[401,403,410].includes(A.status),oe=()=>{d||n.onStatus(p||b?"面板连接暂时中断,正在重试;当前内容会保留。":"")},ce=async(A,G="GET")=>{const V=new AbortController;f.add(V);const se=N(()=>V.abort(),8e3);try{return await Ve(Rt(`${r}${A}`,n.workspace,i),{method:G,...G==="POST"?{headers:{"Content-Type":"application/json"},body:"{}"}:{},signal:V.signal})}finally{D(se),f.delete(V)}},R=()=>{D(v),v=N(()=>{Date.now()>=o?M():R()},o-Date.now())},W=()=>{D(S),p<5&&(S=N(ie,m-Date.now()))};function ie(){if(!d){if(Date.now()>=o){M();return}g||p>=5||Date.now()<m||(g=(async()=>{try{const A=await ce("/renew","POST");if(d)return;if(!A||typeof A!="object"||!("expiresAt"in A)||typeof A.expiresAt!="number"||!Number.isFinite(A.expiresAt)||A.expiresAt<=Date.now()+6e4)throw new Error("面板续期响应无效。");o=A.expiresAt,m=o-6e4,p=0,R(),oe()}catch(A){if(d)return;if(H(A)){_(A);return}p++,m=Date.now()+Math.min(5e3*2**(p-1),3e4),oe()}finally{g=void 0,d||W()}})())}}async function F(){try{const A=await ce(`/events?after=${y}`);if(d)return;if(!A||typeof A!="object"||!("cursor"in A)||!("events"in A))throw new Error("面板事件响应无效。");if(!Number.isSafeInteger(A.cursor)||A.cursor<y||!Array.isArray(A.events)||A.events.length>2048)throw new Error("面板事件响应无效。");const G=[];let V=y;for(const se of A.events){if(!se||typeof se!="object"||!Number.isSafeInteger(se.id)||se.id<=V||se.id>A.cursor||typeof se.event!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,100}$/.test(se.event))throw new Error("面板事件响应无效。");V=se.id,G.push(se)}n.onEvents(G),y=A.cursor,b=0,oe()}catch(A){if(d)return;if(H(A)){_(A);return}b++,oe()}finally{d||N(()=>{F()},Math.min(1e3*2**b,5e3))}}return R(),W(),F(),{stop:z,refresh:ie}}const Zi="/api/v1/panels/runtime";function Hn(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function y0(n){try{if(typeof n!="string"||n.length>2048)return;const i=new URL(n);if(i.protocol==="https:"&&!i.username&&!i.password)return i.href}catch{}}function b0(n,i){const r=`${Zi}/${i}/directory/`;return typeof n=="string"&&n.startsWith(r)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n.slice(r.length))}function x0(n){if(typeof n!="string"||!/^\/api\/v1\/panel-assets\/[A-Za-z0-9_-]{20,128}\/[A-Za-z0-9_%./-]+$/.test(n))return!1;try{return n.split("/").slice(5).every(i=>{const r=decodeURIComponent(i);return!!r&&!r.startsWith(".")&&!/[\\/:\u0000-\u001f\u007f]/.test(r)})}catch{return!1}}function v0(n){return Hn(n)?typeof n.instanceId=="string"&&/^[A-Za-z0-9_-]{20,128}$/.test(n.instanceId)&&x0(n.src)&&typeof n.expiresAt=="number"&&Number.isFinite(n.expiresAt)&&Hn(n.context)&&Array.isArray(n.limitations)&&n.limitations.every(i=>typeof i=="string"):!1}function S0({panel:n,sessionId:i,busy:r,onClose:s,onAuthLost:f,onDirtyChange:d,onSubmitPrompt:o}){const m=w.useRef(null),[g,p]=w.useState(),[b,y]=w.useState(!0),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(),[M,H]=w.useState(""),[oe,ce]=w.useState(""),[R,W]=w.useState(),[ie,F]=w.useState(!1),[A,G]=w.useState(0),V=w.useRef({onClose:s,onAuthLost:f,onDirtyChange:d,onSubmitPrompt:o,busy:r});V.current={onClose:s,onAuthLost:f,onDirtyChange:d,onSubmitPrompt:o,busy:r};const se=w.useRef(!1),ae=w.useRef(void 0),P=w.useRef(void 0),E=w.useRef(null);return w.useEffect(()=>{V.current.onDirtyChange?.(!!R||ie),R&&(E.current?.focus(),E.current?.scrollIntoView?.({block:"nearest"}))},[R,ie]),w.useEffect(()=>{const U=Jc()??"",te=Us(),he={grant:void 0},k=new AbortController,T=new Set,K=new Set;let C=!1,re;const ve=[],Q=[],pe=new Set,je=new Set;let Y,xe=!1,J=!1,ye=!1,Ae=!1;const we=()=>{const ge=m.current?.contentWindow;if(!(C||!he.grant||!ge||!Ae))for(const ke of ve.splice(0))ke.event==="tools.invoke"&&Hn(ke.payload)&&typeof ke.payload.requestId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(ke.payload.requestId)&&je.add(ke.payload.requestId),ge.postMessage({type:"codeshell-panel:event",instanceId:he.grant.instanceId,event:ke.event,payload:ke.payload},"*")},Ye=()=>{C||!ye||!Ae||!he.grant||(Y&&clearTimeout(Y),y(!1),we())},nt={loaded:()=>{ye=!0,Ye()}};P.current=nt,p(void 0),y(!0),S(""),D(""),_(void 0),H(""),ce(""),W(void 0),F(!1);const jt=ge=>{xe||(xe=!0,Ve(Rt(`${Zi}/${encodeURIComponent(ge.instanceId)}`,U,te),{method:"DELETE",keepalive:!0}).catch(()=>{}))},Yt=ge=>{C||(ge instanceof We&&ge.status===401&&!se.current&&(se.current=!0,V.current.onAuthLost()),S(ge instanceof Error?ge.message:"面板连接失败,请重新打开。"))},at=ge=>{if(C||!he.grant)return;const ke=he.grant;he.grant=void 0,re?.stop(),ae.current?.cancel(),Q.length=0,ve.length=0,jt(ke);for(const Ce of T)Ce.abort();Y&&clearTimeout(Y),p(void 0),_(void 0),y(!1),F(!1),H(""),Yt(ge)},mt=ge=>({...ge,...typeof ge.sessionId=="string"?{busy:V.current.busy}:{}}),ut=(ge,ke,Ce,B,Se)=>{C||!he.grant||ge!==m.current?.contentWindow||ge.postMessage({type:"codeshell-panel:response",instanceId:he.grant.instanceId,requestId:ke,...B?{error:B,...Se?.code?{code:Se.code}:{},...Se?.retryAfterMs!==void 0?{retryAfterMs:Se.retryAfterMs}:{}}:{result:Ce}},"*")},ot=()=>{if(C||!he.grant||ae.current||J)return;const ge=Q.shift();if(!ge)return;if(ge.expiresAt<=Date.now()){ot();return}let ke=!1;const Ce={effect:ge,cancel:()=>{ae.current===Ce&&(clearTimeout(B),ae.current=void 0,C||(W(void 0),ce(""),F(!1)))},finish:Se=>{if(C||!he.grant||ae.current!==Ce||ke)return;ke=!0,F(!0),ce("");const Ke=new AbortController;T.add(Ke);const lt=setTimeout(()=>Ke.abort(),8e3);Ve(Rt(`${Zi}/${he.grant.instanceId}/confirm`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({requestId:ge.requestId,allowed:Se}),signal:Ke.signal}).then(Be=>{if(!(C||ae.current!==Ce)){if(typeof Be.allowed!="boolean")throw new Error("确认响应无效。");Se&&Be.allowed===!1&&D("此确认已超时或被取消,操作未获准执行,请在面板中重新发起。"),!Se&&Be.allowed===!0&&D("该操作此前已获准执行,请在面板中查看进度或停止。"),Ce.cancel(),ot()}}).catch(Be=>{if(!(C||ae.current!==Ce)){if(Be instanceof We&&[401,403,410].includes(Be.status)){at(Be);return}if(Be instanceof We&&Be.status===409){Ce.cancel(),D("面板操作确认已失效,请在面板中重新发起。"),ot();return}ce("暂未收到确认结果。可以重试本次确认,或取消尚未执行的请求。")}}).finally(()=>{clearTimeout(lt),T.delete(Ke),ke=!1,!C&&ae.current===Ce&&F(!1)})}},B=setTimeout(()=>{Ce.cancel(),!C&&he.grant&&(D("面板操作确认已超时,请在面板中重新发起。"),ot())},ge.expiresAt-Date.now());ae.current=Ce,W(Ce),ce("")},Gt=ge=>{for(const ke of ge){if(ke.event!=="host.confirm"){ve.push(ke);continue}const Ce=ke.payload;if(!Hn(Ce)||typeof Ce.requestId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(Ce.requestId)||typeof Ce.title!="string"||Ce.title.length>500||typeof Ce.body!="string"||Ce.body.length>3e4)throw new Error("面板操作确认格式无效。");pe.has(Ce.requestId)||(pe.add(Ce.requestId),Q.push({effect:"host.confirm",requestId:Ce.requestId,title:Ce.title,body:Ce.body,expiresAt:Date.now()+5e4}))}if(ve.length>2048||Q.length>32){at(new Error("面板状态积压过多,请重新打开面板。"));return}ot(),we()},vt=ge=>new Promise(ke=>{if(ae.current||J){ke(!1);return}const Ce={effect:ge,finish:Se=>{ae.current===Ce&&(clearTimeout(B),ae.current=void 0,C||W(void 0),ke(Se),queueMicrotask(ot))},cancel:()=>Ce.finish(!1)},B=setTimeout(()=>Ce.finish(!1),55e3);ae.current=Ce,W(Ce)}),qt=async ge=>{const ke=m.current?.contentWindow,Ce=he.grant,B=ge.data;if(C||!ke||ge.source!==ke||ge.origin!=="null"||!Ce||!Hn(B)||B.instanceId!==Ce.instanceId)return;if(B.type==="codeshell-panel:ready"){Ae=!0,Ye();return}if(B.type==="codeshell-panel:tool-result"){if(typeof B.requestId!="string"||!je.has(B.requestId)||T.size>=32)return;let q;try{if(q=JSON.stringify({requestId:B.requestId,...typeof B.error=="string"?{error:B.error}:{result:B.result}}),new TextEncoder().encode(q).length>512*1024)return}catch{return}je.delete(B.requestId);const ze=new AbortController;T.add(ze);const St=setTimeout(()=>ze.abort(),8e3);try{await Ve(Rt(`${Zi}/${Ce.instanceId}/tool-results`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:q,signal:ze.signal})}catch(de){!C&&he.grant&&(de instanceof We&&[401,410].includes(de.status)?at(de):D("面板工具结果未能送达,请在对话中重新发起操作。"))}finally{clearTimeout(St),T.delete(ze)}return}if(B.type!=="codeshell-panel:call"||typeof B.requestId!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(B.requestId))return;const Se=B.requestId;if(K.has(Se)){ut(ke,Se,void 0,"此请求已经处理,请重新发起。");return}if(K.size>=8192||T.size>=32){ut(ke,Se,void 0,"面板请求过于频繁,请稍后重试。");return}if(K.add(Se),typeof B.method!="string"||!/^[A-Za-z][A-Za-z0-9.]{0,63}$/.test(B.method)){ut(ke,Se,void 0,"面板方法无效。");return}let Ke;try{if(Ke=JSON.stringify({method:B.method,params:B.params}),Ke.length>2*1024*1024)throw new Error("too large")}catch{ut(ke,Se,void 0,"面板请求内容过大或格式无效。");return}const lt=new AbortController;let Be=!1;T.add(lt);try{const q=await Ve(Rt(`${Zi}/${Ce.instanceId}/call`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:Ke,signal:lt.signal});if(C||lt.signal.aborted)return;if(B.method==="context.get"&&(Ae=!0,Ye()),B.method==="external.open"){const ze=Hn(q)&&q.effect===B.method?y0(q.url):void 0;if(!ze)throw new Error("面板返回的外部链接无效。");if(!await vt({effect:"external.open",url:ze}))throw new Error("你取消了打开链接,或确认已超时。");ut(ke,Se,{opened:!0})}else if(B.method==="agent.submitPrompt"){if(!Hn(q)||q.effect!==B.method||typeof q.prompt!="string"||!q.prompt.trim()||q.prompt.length>2e4||q.sessionId!==i)throw new Error("面板任务与当前对话不匹配,请重新打开面板。");if(!await vt({effect:"agent.submitPrompt",prompt:q.prompt,sessionId:i}))throw new Error("你取消了发送任务,或确认已超时。");if(C||lt.signal.aborted)return;Be=!0,J=!0,F(!0);const ze=await V.current.onSubmitPrompt({prompt:q.prompt,sessionId:i});if(C||lt.signal.aborted)return;D("面板任务已提交到当前对话,可切换到对话查看进度。"),ut(ke,Se,ze)}else if(B.method==="filesystem.openDirectory"){if(_(void 0),!Hn(q)||q.effect!==B.method||typeof q.path!="string")throw new Error("面板目录信息无效。");if(q.url!==void 0&&!b0(q.url,Ce.instanceId))throw new Error("面板目录链接无效,请重新打开目录。");_({path:q.path,...typeof q.url=="string"?{url:Rt(q.url,U,te)}:{}}),ut(ke,Se,{opened:!1,path:q.path})}else if(B.method==="notifications.send"){if(!Hn(q)||q.effect!==B.method||typeof q.title!="string"||q.title.length>160||typeof q.body!="string"||q.body.length>2e3)throw new Error("面板通知格式无效。");D(`${q.title}${q.body?`:${q.body}`:""}`),ut(ke,Se,{sent:!0})}else ut(ke,Se,B.method==="context.get"&&Hn(q)?mt(q):q)}catch(q){!C&&!lt.signal.aborted&&(q instanceof We&&[401,410].includes(q.status)&&at(q),(B.method==="agent.submitPrompt"||B.method==="external.open")&&D(q instanceof Error?q.message:"面板操作未完成。"),ut(ke,Se,void 0,q instanceof Error?q.message:"面板请求失败。",q instanceof We?{code:q.code,retryAfterMs:q.retryAfterMs}:void 0))}finally{T.delete(lt),Be&&(J=!1,C||F(!1),ot())}},ne=ge=>{qt(ge)};window.addEventListener("message",ne);const me=()=>re?.refresh(),Te=()=>{document.visibilityState==="visible"&&me()};return window.addEventListener("focus",me),window.addEventListener("online",me),document.addEventListener("visibilitychange",Te),Ve(Rt(`${Zi}/prepare`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:n.id,revision:n.revision,...i?{sessionId:i}:{},theme:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",locale:"zh-CN"}),signal:k.signal}).then(ge=>{if(!v0(ge))throw new Error("面板启动信息无效,请刷新面板列表后重试。");if(C||k.signal.aborted){jt(ge);return}if(ge.expiresAt<=Date.now())throw jt(ge),new Error("面板授权已过期,请重新打开。");he.grant=ge,p({...ge,src:Rt(ge.src,U,te)}),Y=setTimeout(()=>{at(new Error("面板未能完成加载,请重新打开。若仍无法加载,可检查面板文件或使用桌面客户端。"))},45e3),re=g0({instanceId:ge.instanceId,expiresAt:ge.expiresAt,workspace:U,projectId:te,onEvents:Gt,onTerminal:at,onStatus:H})}).catch(ge=>{!C&&!k.signal.aborted&&(y(!1),Yt(ge))}),()=>{C=!0,ae.current?.cancel(),window.removeEventListener("message",ne),window.removeEventListener("focus",me),window.removeEventListener("online",me),document.removeEventListener("visibilitychange",Te),re?.stop(),k.abort();for(const ge of T)ge.abort();Y&&clearTimeout(Y),he.grant&&jt(he.grant),V.current.onDirtyChange?.(!1),P.current===nt&&(P.current=void 0)}},[n.id,n.revision,i,A]),w.useEffect(()=>{!g||!m.current?.contentWindow||m.current.contentWindow.postMessage({type:"codeshell-panel:event",instanceId:g.instanceId,event:"context.changed",payload:{...g.context,...typeof g.context.sessionId=="string"?{busy:r}:{}}},"*")},[r,g]),u.jsxs("section",{className:"panel-host",children:[u.jsxs("header",{className:"panel-host-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{children:n.title["zh-CN"]||n.title.default}),u.jsxs("p",{children:["v",n.version," · 运行于当前工作区"]})]}),u.jsx("button",{onClick:s,children:"返回面板"})]}),(g?.limitations??n.compatibility.reasons).length>0&&u.jsxs("details",{className:"panel-host-limitations",open:!0,children:[u.jsx("summary",{children:"部分功能可用"}),u.jsx("p",{children:"面板界面可以使用;以下功能尚未接入网页,使用时会显示具体限制。"}),u.jsx("ul",{children:(g?.limitations??n.compatibility.reasons).map(U=>u.jsx("li",{children:U},U))})]}),N&&u.jsx("p",{className:"panel-host-notice",role:"status",children:N}),z&&u.jsxs("div",{className:"panel-host-notice panel-host-directory",role:"status",children:[u.jsxs("p",{children:["文件保存在服务器目录:",z.path]}),z.url&&u.jsx("a",{href:z.url,target:"_blank",rel:"noopener noreferrer",children:"查看并下载文件"})]}),M&&u.jsx("p",{className:"panel-host-notice",role:"status",children:M}),v&&u.jsxs("div",{className:"panel-host-error",role:"alert",children:[u.jsx("p",{children:v}),u.jsx("button",{disabled:b,onClick:()=>G(U=>U+1),children:"重新打开面板"})]}),b&&u.jsx("p",{className:"panel-host-loading",role:"status",children:"正在打开面板…"}),R&&u.jsxs("section",{className:"panel-host-confirm",ref:E,tabIndex:-1,onKeyDown:U=>{U.key==="Escape"&&!ie&&(U.preventDefault(),R.finish(!1))},"aria-label":R.effect.effect==="external.open"?"确认打开外部链接":R.effect.effect==="host.confirm"?"确认面板操作":"确认发送面板任务",children:[u.jsx("h2",{children:R.effect.effect==="external.open"?"面板请求打开网页":R.effect.effect==="host.confirm"?R.effect.title:"面板请求向当前对话发送任务"}),R.effect.effect==="external.open"?u.jsx("p",{className:"panel-host-url",children:R.effect.url}):R.effect.effect==="host.confirm"?u.jsx("pre",{children:R.effect.body}):u.jsx("pre",{children:R.effect.prompt}),oe&&u.jsx("p",{role:"alert",children:oe}),u.jsxs("div",{className:"panel-host-actions",children:[u.jsx("button",{disabled:ie,onClick:()=>R.finish(!1),children:"取消"}),R.effect.effect==="external.open"?u.jsx("a",{href:R.effect.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>R.finish(!0),children:"确认打开网页"}):u.jsx("button",{className:"panel-host-primary",disabled:ie,onClick:()=>R.finish(!0),children:ie?"正在确认…":R.effect.effect==="host.confirm"?"确认执行":"确认发送任务"})]})]}),g&&u.jsx("iframe",{ref:m,src:g.src,title:`${n.title["zh-CN"]||n.title.default}面板`,sandbox:"allow-scripts",referrerPolicy:"no-referrer",inert:!!R||ie,onLoad:()=>P.current?.loaded(),allow:"camera 'none'; microphone 'none'; geolocation 'none'; display-capture 'none'; clipboard-read 'none'; clipboard-write 'none'",className:"panel-host-frame"})]})}function j0(n,i){const r={};return(n[n.length-1]===""?[...n,""]:n).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const k0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,w0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,C0={};function Lm(n,i){return(C0.jsx?w0:k0).test(n)}const E0=/[ \t\n\f\r]/g;function N0(n){return typeof n=="object"?n.type==="text"?Um(n.value):!1:Um(n)}function Um(n){return n.replace(E0,"")===""}class ia{constructor(i,r,s){this.normal=r,this.property=i,s&&(this.space=s)}}ia.prototype.normal={};ia.prototype.property={};ia.prototype.space=void 0;function Gg(n,i){const r={},s={};for(const f of n)Object.assign(r,f.property),Object.assign(s,f.normal);return new ia(r,s,i)}function Oc(n){return n.toLowerCase()}class cn{constructor(i,r){this.attribute=r,this.property=i}}cn.prototype.attribute="";cn.prototype.booleanish=!1;cn.prototype.boolean=!1;cn.prototype.commaOrSpaceSeparated=!1;cn.prototype.commaSeparated=!1;cn.prototype.defined=!1;cn.prototype.mustUseProperty=!1;cn.prototype.number=!1;cn.prototype.overloadedBoolean=!1;cn.prototype.property="";cn.prototype.spaceSeparated=!1;cn.prototype.space=void 0;let T0=0;const qe=ri(),Ut=ri(),Mc=ri(),be=ri(),bt=ri(),ni=ri(),bn=ri();function ri(){return 2**++T0}const Lc=Object.freeze(Object.defineProperty({__proto__:null,boolean:qe,booleanish:Ut,commaOrSpaceSeparated:bn,commaSeparated:ni,number:be,overloadedBoolean:Mc,spaceSeparated:bt},Symbol.toStringTag,{value:"Module"})),pc=Object.keys(Lc);class tf extends cn{constructor(i,r,s,f){let d=-1;if(super(i,r),Bm(this,"space",f),typeof s=="number")for(;++d<pc.length;){const o=pc[d];Bm(this,pc[d],(s&Lc[o])===Lc[o])}}}tf.prototype.defined=!0;function Bm(n,i,r){r&&(n[i]=r)}function Ji(n){const i={},r={};for(const[s,f]of Object.entries(n.properties)){const d=new tf(s,n.transform(n.attributes||{},s),f,n.space);n.mustUseProperty&&n.mustUseProperty.includes(s)&&(d.mustUseProperty=!0),i[s]=d,r[Oc(s)]=s,r[Oc(d.attribute)]=s}return new ia(i,r,n.space)}const Vg=Ji({properties:{ariaActiveDescendant:null,ariaAtomic:Ut,ariaAutoComplete:null,ariaBusy:Ut,ariaChecked:Ut,ariaColCount:be,ariaColIndex:be,ariaColSpan:be,ariaControls:bt,ariaCurrent:null,ariaDescribedBy:bt,ariaDetails:null,ariaDisabled:Ut,ariaDropEffect:bt,ariaErrorMessage:null,ariaExpanded:Ut,ariaFlowTo:bt,ariaGrabbed:Ut,ariaHasPopup:null,ariaHidden:Ut,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:bt,ariaLevel:be,ariaLive:null,ariaModal:Ut,ariaMultiLine:Ut,ariaMultiSelectable:Ut,ariaOrientation:null,ariaOwns:bt,ariaPlaceholder:null,ariaPosInSet:be,ariaPressed:Ut,ariaReadOnly:Ut,ariaRelevant:null,ariaRequired:Ut,ariaRoleDescription:bt,ariaRowCount:be,ariaRowIndex:be,ariaRowSpan:be,ariaSelected:Ut,ariaSetSize:be,ariaSort:null,ariaValueMax:be,ariaValueMin:be,ariaValueNow:be,ariaValueText:null,role:null},transform(n,i){return i==="role"?i:"aria-"+i.slice(4).toLowerCase()}});function Qg(n,i){return i in n?n[i]:i}function Xg(n,i){return Qg(n,i.toLowerCase())}const A0=Ji({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ni,acceptCharset:bt,accessKey:bt,action:null,allow:null,allowFullScreen:qe,allowPaymentRequest:qe,allowUserMedia:qe,alpha:qe,alt:null,as:null,async:qe,autoCapitalize:null,autoComplete:bt,autoFocus:qe,autoPlay:qe,blocking:bt,capture:null,charSet:null,checked:qe,cite:null,className:bt,closedBy:null,colorSpace:null,cols:be,colSpan:be,command:null,commandFor:null,content:null,contentEditable:Ut,controls:qe,controlsList:bt,coords:be|ni,crossOrigin:null,data:null,dateTime:null,decoding:null,default:qe,defer:qe,dir:null,dirName:null,disabled:qe,download:Mc,draggable:Ut,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:qe,formTarget:null,headers:bt,height:be,hidden:Mc,high:be,href:null,hrefLang:null,htmlFor:bt,httpEquiv:bt,id:null,imageSizes:null,imageSrcSet:null,inert:qe,inputMode:null,integrity:null,is:null,isMap:qe,itemId:null,itemProp:bt,itemRef:bt,itemScope:qe,itemType:bt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:qe,low:be,manifest:null,max:null,maxLength:be,media:null,method:null,min:null,minLength:be,multiple:qe,muted:qe,name:null,nonce:null,noModule:qe,noValidate:qe,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:qe,optimum:be,pattern:null,ping:bt,placeholder:null,playsInline:qe,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:qe,referrerPolicy:null,rel:bt,required:qe,reversed:qe,rows:be,rowSpan:be,sandbox:bt,scope:null,scoped:qe,seamless:qe,selected:qe,shadowRootClonable:qe,shadowRootCustomElementRegistry:qe,shadowRootDelegatesFocus:qe,shadowRootMode:null,shadowRootSerializable:qe,shape:null,size:be,sizes:null,slot:null,span:be,spellCheck:Ut,src:null,srcDoc:null,srcLang:null,srcSet:null,start:be,step:null,style:null,tabIndex:be,target:null,title:null,translate:null,type:null,typeMustMatch:qe,useMap:null,value:Ut,width:be,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:bt,axis:null,background:null,bgColor:null,border:be,borderColor:null,bottomMargin:be,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:qe,declare:qe,event:null,face:null,frame:null,frameBorder:null,hSpace:be,leftMargin:be,link:null,longDesc:null,lowSrc:null,marginHeight:be,marginWidth:be,noResize:qe,noHref:qe,noShade:qe,noWrap:qe,object:null,profile:null,prompt:null,rev:null,rightMargin:be,rules:null,scheme:null,scrolling:Ut,standby:null,summary:null,text:null,topMargin:be,valueType:null,version:null,vAlign:null,vLink:null,vSpace:be,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:qe,disablePictureInPicture:qe,disableRemotePlayback:qe,exportParts:ni,part:bt,prefix:null,property:null,results:be,security:null,unselectable:null},space:"html",transform:Xg}),z0=Ji({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",maskType:"mask-type",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:bn,accentHeight:be,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:be,amplitude:be,arabicForm:null,ascent:be,attributeName:null,attributeType:null,azimuth:be,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:be,by:null,calcMode:null,capHeight:be,className:bt,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:be,diffuseConstant:be,direction:null,display:null,dur:null,divisor:be,dominantBaseline:null,download:qe,dx:null,dy:null,edgeMode:null,editable:null,elevation:be,enableBackground:null,end:null,event:null,exponent:be,externalResourcesRequired:null,fill:null,fillOpacity:be,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:ni,g2:ni,glyphName:ni,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:be,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:be,horizOriginX:be,horizOriginY:be,id:null,ideographic:be,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:be,k:be,k1:be,k2:be,k3:be,k4:be,kernelMatrix:bn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:be,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:be,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:be,overlineThickness:be,paintOrder:null,panose1:null,path:null,pathLength:be,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:bt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:be,pointsAtY:be,pointsAtZ:be,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:bn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:bn,rev:bn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:bn,requiredFeatures:bn,requiredFonts:bn,requiredFormats:bn,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:be,specularExponent:be,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:be,strikethroughThickness:be,string:null,stroke:null,strokeDashArray:bn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:be,strokeOpacity:be,strokeWidth:null,style:null,surfaceScale:be,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:bn,tabIndex:be,tableValues:null,target:null,targetX:be,targetY:be,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:bn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:be,underlineThickness:be,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:be,values:null,vAlphabetic:be,vMathematical:be,vectorEffect:null,vHanging:be,vIdeographic:be,version:null,vertAdvY:be,vertOriginX:be,vertOriginY:be,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:be,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Qg}),Zg=Ji({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(n,i){return"xlink:"+i.slice(5).toLowerCase()}}),Kg=Ji({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Xg}),Fg=Ji({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(n,i){return"xml:"+i.slice(3).toLowerCase()}}),R0={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"},_0=/[A-Z]/g,qm=/-[a-z]/g,D0=/^data[-\w.:]+$/i;function O0(n,i){const r=Oc(i);let s=i,f=cn;if(r in n.normal)return n.property[n.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&D0.test(i)){if(i.charAt(4)==="-"){const d=i.slice(5).replace(qm,L0);s="data"+d.charAt(0).toUpperCase()+d.slice(1)}else{const d=i.slice(4);if(!qm.test(d)){let o=d.replace(_0,M0);o.charAt(0)!=="-"&&(o="-"+o),i="data"+o}}f=tf}return new f(s,i)}function M0(n){return"-"+n.toLowerCase()}function L0(n){return n.charAt(1).toUpperCase()}const U0=Gg([Vg,A0,Zg,Kg,Fg],"html"),nf=Gg([Vg,z0,Zg,Kg,Fg],"svg");function B0(n){return n.join(" ").trim()}var Qi={},mc,Hm;function q0(){if(Hm)return mc;Hm=1;var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,i=/\n/g,r=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,f=/^:\s*/,d=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,m=/^\s+|\s+$/g,g=`
20
+ `),reuseStoredSecrets:!1}}function fc(n){return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean)}function Qv(n,i){const r={},s=new Set;for(const f of n){if(!f.stored&&f.removed)continue;const d=f.name.trim();if(["__proto__","prototype","constructor"].includes(d))throw new Error(`${i}名称无效。`);if(!d&&!f.value&&!f.stored)continue;if(!d||!f.stored&&!f.value)throw new Error(`请完整填写${i}的名称和值,或移除空行。`);const o=i==="环境变量"?d:d.toLowerCase();if(s.has(o))throw new Error(`${i}名称不能重复。`);s.add(o),f.removed?r[d]=null:f.value&&f.value!==f.initialValue&&(r[d]=f.value)}return r}function Nm(n){try{return new URL(n).origin}catch{return""}}function Xv(n,i){if(!i)return!1;const r=i.envKeys.length||i.headerKeys.length||i.envVars.length||Object.keys(i.envHeaders).length||i.credentialRef||i.bearerTokenEnvVar||i.argsCount,s=n.transport!==i.transport||(n.transport==="stdio"?n.command.trim()!==i.command||!!n.args.trim()||n.clearArgs:Nm(n.url)!==Nm(i.url??""));return!!r&&s}function Zv(n,i){const r={name:n.name.trim()};(!i||n.transport!==i.transport)&&(r.transport=n.transport),(!i||n.enabled!==i.enabled)&&(r.enabled=n.enabled),n.transport==="stdio"?((!i||n.command.trim()!==i.command)&&(r.command=n.command.trim()),n.clearArgs?r.args=[]:n.args.trim()&&(r.args=n.args.split(/\r?\n/).filter(o=>o.length>0))):(!i||n.url.trim()!==i.url)&&(r.url=n.url.trim());for(const[o,m]of[["env","环境变量"],["headers","请求头"],["envHeaders","环境变量请求头"]]){const g=Qv(n[o],m);Object.keys(g).length&&(r[o]=g)}const s=fc(n.envVars);(!i||JSON.stringify(s)!==JSON.stringify(i.envVars))&&(r.envVars=s);for(const o of["bearerTokenEnvVar","credentialRef"])(!i||n[o].trim()!==(i[o]??""))&&(r[o]=n[o].trim()||null);const f=n.restrictTools?fc(n.allowedTools):void 0;(!i||JSON.stringify(f)!==JSON.stringify(i.allowedTools))&&(r.allowedTools=f??null);const d=fc(n.disabledTools);return(!i||JSON.stringify(d)!==JSON.stringify(i.disabledTools))&&(r.disabledTools=d),n.reuseStoredSecrets&&(r.reuseStoredSecrets=!0),r}function Yg(n){if(!n||typeof n.workspacePath!="string"||!Array.isArray(n.servers)||!Array.isArray(n.removed))throw new Error("服务端返回了无效的 MCP 配置,请刷新重试。");return n}const $i=(n,i="")=>`/api/v1/mcp/servers/${encodeURIComponent(n)}${i}`;async function Kv(n){return Yg(await Ve("/api/v1/mcp",{signal:n}))}async function Bs(n,i,r,s){return Yg(await Ve(n,{method:i,headers:{"Content-Type":"application/json"},...r===void 0?{}:{body:JSON.stringify(r)},signal:s}))}function Fv(n,i,r){return Bs(i?$i(i.name):"/api/v1/mcp/servers",i?"PUT":"POST",Zv(n,i),r)}function $v(n,i,r){return Bs($i(n,"/enabled"),"PUT",{enabled:i},r)}function Jv(n,i){return Bs($i(n),"DELETE",void 0,i)}function Tm(n,i){return Bs($i(n,"/inherit"),"POST",{},i)}async function Pv(n,i){const r=await Ve($i(n,"/probe"),{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:i});if(r.name!==n||!["ok","error","cancelled"].includes(r.status))throw new Error("服务端返回了无效的连接测试结果。");return r}function Am(n,i,r){return Ve(Rt($i(n,"/cancel-probe"),i,r),{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",keepalive:!0})}const Wv={local:"工作区本地",project:"工作区配置",user:"用户级",managed:"启动配置",plugin:"插件提供"};function e0({onAuthLost:n,onConfigurationChange:i,configurationVersion:r=0,onDirtyChange:s}){const[f,d]=w.useState(null),[o,m]=w.useState(!0),[g,p]=w.useState(!1),[b,y]=w.useState(!1),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(null),[M,H]=w.useState(null),[oe,ce]=w.useState(""),[R,W]=w.useState({}),[ie,F]=w.useState(null),[A,G]=w.useState(0),V=w.useRef({onAuthLost:n,onConfigurationChange:i,onDirtyChange:s});V.current={onAuthLost:n,onConfigurationChange:i,onDirtyChange:s};const se=w.useRef(!1),ae=w.useRef(null),P=w.useRef(null),E=w.useRef(null),U=w.useRef(0),te=w.useRef(!1),he=w.useRef(r);w.useEffect(()=>{V.current.onDirtyChange?.(b||g)},[b,g]);const k=w.useCallback(Y=>{Y instanceof We&&Y.status===401?V.current.onAuthLost():S(Y instanceof Error?Y.message:"MCP 操作失败,请重试。")},[]);w.useEffect(()=>(se.current=!0,()=>{se.current=!1,V.current.onDirtyChange?.(!1),P.current?.abort();const Y=E.current;Y&&(Y.controller.abort(),Am(Y.name,Y.workspace,Y.projectId).catch(()=>{}))}),[]),w.useEffect(()=>{he.current!==r&&(he.current=r,P.current?te.current=!0:G(Y=>Y+1))},[r]),w.useEffect(()=>{const Y=new AbortController;ae.current=Y;const xe=Date.now(),J=++U.current;return m(!0),S(""),Kv(Y.signal).then(ye=>{!Y.signal.aborted&&J===U.current&&(d(ye),W(Ae=>Object.fromEntries(Object.entries(Ae).filter(([,we])=>Date.parse(we.checkedAt)>=xe))))}).catch(ye=>{!Y.signal.aborted&&J===U.current&&k(ye)}).finally(()=>{!Y.signal.aborted&&J===U.current&&m(!1)}),()=>Y.abort()},[A,k]);const T=async(Y,xe="MCP 设置已保存,任务进程会加载新的配置。")=>{if(P.current||E.current)return!1;ae.current?.abort();const J=++U.current,ye=new AbortController;P.current=ye,p(!0),m(!1),S(""),D("");try{const Ae=await Y(ye.signal);return!se.current||ye.signal.aborted||J!==U.current?!1:(d(Ae),W({}),D(xe),V.current.onConfigurationChange?.(),!0)}catch(Ae){return se.current&&!ye.signal.aborted&&k(Ae),!1}finally{P.current===ye&&(P.current=null),se.current&&!ye.signal.aborted&&(p(!1),te.current&&(te.current=!1,G(Ae=>Ae+1)))}},K=async Y=>{if(E.current||P.current)return;const xe=new AbortController;E.current={name:Y,controller:xe,workspace:Jc()??"",projectId:Us()},F(Y),S(""),D(""),W(J=>{const ye={...J};return delete ye[Y],ye});try{const J=await Pv(Y,xe.signal);se.current&&!xe.signal.aborted&&W(ye=>({...ye,[Y]:J}))}catch(J){se.current&&!xe.signal.aborted&&k(J)}finally{E.current?.controller===xe&&(E.current=null),se.current&&F(null)}},C=async()=>{const Y=E.current;if(Y)try{await Am(Y.name,Y.workspace,Y.projectId)}catch(xe){se.current&&k(xe)}finally{Y.controller.abort(),E.current===Y&&(E.current=null),se.current&&(F(null),W(xe=>({...xe,[Y.name]:{name:Y.name,status:"cancelled",checkedAt:new Date().toISOString(),durationMs:0,error:{code:"cancelled",message:"测试已取消。"}}})))}},re=g||o||ie!==null,ve=oe.trim().toLocaleLowerCase(),Q=[...f?.servers??[]];z?.kind==="edit"&&!Q.some(Y=>Y.name===z.name)&&Q.push(z.original);const pe=Q.filter(Y=>!ve||Y.name.toLocaleLowerCase().includes(ve)||z?.kind==="edit"&&z.name===Y.name),je=z?.kind==="edit"?Q.find(Y=>Y.name===z.name):void 0;return u.jsxs("div",{className:"hub-mcp",children:[u.jsxs("div",{className:"config-section-heading hub-mcp-toolbar",children:[u.jsxs("label",{className:"config-search",children:[u.jsx("span",{"aria-hidden":"true",children:"⌕"}),u.jsx("input",{type:"search",value:oe,onChange:Y=>ce(Y.target.value),placeholder:"搜索 MCP 服务…","aria-label":"搜索 MCP 服务"})]}),u.jsxs("div",{className:"hub-mcp-toolbar-actions",children:[u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>G(Y=>Y+1),children:"刷新 MCP"}),u.jsx("button",{className:"config-button",disabled:re||z!==null,onClick:()=>_({kind:"new"}),children:"+ 添加服务"})]})]}),v&&u.jsx("p",{className:"config-message config-error",role:"alert",children:v}),N&&u.jsx("p",{className:"config-message config-success",role:"status",children:N}),g&&u.jsx("p",{className:"config-help",role:"status",children:"正在保存 MCP 配置…"}),o&&!f&&u.jsx("p",{className:"config-help",role:"status",children:"正在读取 MCP 配置…"}),z?.kind==="new"&&u.jsxs("div",{className:"config-card hub-mcp-editor-card",children:[u.jsx("h2",{children:"添加 MCP 服务"}),u.jsx(zm,{disabled:re,save:T,onDone:()=>_(null),onProbe:Y=>{K(Y)},onDirtyChange:y})]}),!pe.length&&f&&z?.kind!=="new"&&u.jsxs("div",{className:"config-empty",children:[u.jsx("span",{"aria-hidden":"true",children:"⌘"}),u.jsx("h3",{children:ve?"没有匹配的服务":"连接你的工具与数据"}),u.jsx("p",{children:ve?"试试其他服务名称。":"添加运行 CodeShell 的设备上的命令,或连接提供 MCP 接口的 HTTP 服务。"})]}),u.jsx("div",{className:"hub-mcp-list",children:pe.map(Y=>u.jsxs("article",{className:"config-card hub-mcp-card",children:[u.jsxs("div",{className:"hub-mcp-card-head",children:[u.jsx("span",{className:"config-row-icon","aria-hidden":"true",children:"⌘"}),u.jsxs("div",{className:"config-row-copy",children:[u.jsx("strong",{children:Y.name}),u.jsxs("span",{children:[Y.transport==="stdio"?"本地命令":Y.transport==="inprocess"?"内置工具":"HTTP 服务"," ","· ",Wv[Y.scope]]})]}),u.jsx("button",{className:"config-switch",type:"button",role:"switch","aria-checked":Y.enabled,"aria-label":`${Y.enabled?"停用":"启用"} MCP ${Y.name}`,disabled:re||Y.pluginDisabled,onClick:()=>{T(xe=>$v(Y.name,!Y.enabled,xe))},children:u.jsx("span",{})})]}),z?.kind==="edit"&&z.name===Y.name&&je?u.jsx(zm,{server:je,disabled:re,save:T,onDone:()=>_(null),onProbe:xe=>{K(xe)},onDirtyChange:y},Y.name):u.jsxs(u.Fragment,{children:[u.jsxs("p",{className:"hub-mcp-endpoint",children:[u.jsx("code",{children:Y.transport==="stdio"?Y.command:Y.url||"由任务进程提供"}),Y.argsCount>0&&u.jsxs("span",{children:[Y.argsCount," 个已保存参数"]})]}),u.jsxs("div",{className:"hub-mcp-metadata",children:[u.jsx("span",{className:`config-badge${Y.enabled?" config-badge-accent":""}`,children:Y.enabled?"配置启用":"配置停用"}),Y.envKeys.length>0&&u.jsxs("span",{children:[Y.envKeys.length," 个环境变量"]}),(Y.headerKeys.length>0||Y.credentialRef||Y.bearerTokenEnvVar||Object.keys(Y.envHeaders).length>0)&&u.jsx("span",{children:"已配置认证"}),Y.hasLocalOverride&&u.jsx("span",{children:"本地覆盖"})]}),Y.source==="plugin"&&u.jsx("p",{className:"config-help",children:Y.pluginDisabled?"所属插件已停用。启用插件后,才能启用或测试这个服务。":"连接命令与地址由插件提供,可在此启停或测试。"}),u.jsxs("div",{className:"hub-mcp-card-actions",children:[ie===Y.name?u.jsx("button",{className:"config-button",onClick:()=>{C()},children:"取消测试"}):u.jsx("button",{className:"config-button",disabled:re||Y.pluginDisabled||Y.transport==="inprocess",onClick:()=>{K(Y.name)},children:"测试连接"}),Y.editable&&u.jsx("button",{className:"config-button config-button-quiet",disabled:re||z!==null,onClick:()=>{H(null),_({kind:"edit",name:Y.name,original:Y})},children:"编辑"}),Y.hasLocalOverride&&u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>{T(xe=>Tm(Y.name,xe),"已移除本地覆盖,恢复继承配置。")},children:"恢复继承"}),Y.deletable&&u.jsx("button",{className:"config-button config-button-quiet hub-mcp-remove",disabled:re||z!==null,onClick:()=>H(Y.name),children:"移除"})]}),M===Y.name&&u.jsxs("div",{className:"hub-mcp-delete",role:"alert",children:[u.jsxs("span",{children:["从当前工作区移除 ",Y.name,"?其他工作区的配置不受影响。"]}),u.jsxs("div",{children:[u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>H(null),children:"取消"}),u.jsx("button",{className:"config-button hub-mcp-remove",disabled:re,onClick:async()=>{await T(xe=>Jv(Y.name,xe),"已从当前工作区移除服务。")&&H(null)},children:"确认移除"})]})]}),ie===Y.name&&u.jsx("p",{className:"hub-mcp-probing",role:"status",children:"正在建立测试连接并读取工具列表…"}),R[Y.name]&&u.jsx(t0,{result:R[Y.name]})]})]},Y.name))}),!!f?.removed.length&&u.jsxs("details",{className:"hub-mcp-removed",children:[u.jsxs("summary",{children:["已在当前工作区移除(",f.removed.length,")"]}),f.removed.map(Y=>u.jsxs("div",{className:"hub-mcp-removed-row",children:[u.jsx("span",{children:Y.name}),u.jsx("button",{className:"config-button config-button-quiet",disabled:re,onClick:()=>{T(xe=>Tm(Y.name,xe),"已恢复继承的 MCP 配置。")},children:"恢复继承"})]},Y.name))]}),u.jsx("p",{className:"config-help hub-mcp-explanation",children:"连接使用运行 CodeShell 的设备上的网络、环境和凭据。测试只建立一次短连接并读取工具列表,完成后关闭;不会调用工具或改变启用状态。"})]})}function zm({server:n,disabled:i,save:r,onDone:s,onProbe:f,onDirtyChange:d}){const o=w.useRef(n).current,[m,g]=w.useState(()=>Vv(o)),p=w.useRef(JSON.stringify(m)).current,b=JSON.stringify(m)!==p;w.useEffect(()=>{d(b)},[b,d]),w.useEffect(()=>()=>d(!1),[d]);const[y,v]=w.useState(""),S=(z,_)=>g(M=>({...M,[z]:_})),N=Xv(m,o),D=m.transport==="stdio";return u.jsx("form",{className:"hub-mcp-editor",onSubmit:async z=>{z.preventDefault(),v("");const _=z.nativeEvent.submitter?.getAttribute("data-probe")==="true";try{await r(M=>Fv(m,o,M))&&(s(),_&&f(m.name.trim()))}catch(M){v(M instanceof Error?M.message:"请检查填写内容。")}},children:u.jsxs("fieldset",{disabled:i,children:[u.jsx("legend",{className:"config-sr-only",children:o?`编辑 MCP ${o.name}`:"新 MCP 服务"}),u.jsxs("div",{className:"config-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"服务名称"}),u.jsx("input",{required:!0,readOnly:!!o,maxLength:128,pattern:"[A-Za-z0-9][A-Za-z0-9._:\\-]*",value:m.name,onChange:z=>S("name",z.target.value),placeholder:"例如 workspace-tools"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"连接方式"}),u.jsxs("select",{"aria-label":"连接方式",value:m.transport,onChange:z=>S("transport",z.target.value),children:[u.jsx("option",{value:"stdio",children:"本地命令(stdio)"}),u.jsx("option",{value:"streamable-http",children:"HTTP(Streamable HTTP)"}),o?.transport==="sse"&&u.jsx("option",{value:"sse",children:"HTTP(已有 SSE 配置)"})]})]}),D?u.jsxs(u.Fragment,{children:[u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"启动命令"}),u.jsx("input",{required:!0,"aria-label":"启动命令",value:m.command,onChange:z=>S("command",z.target.value),placeholder:"例如 node、uvx 或可执行文件路径"}),u.jsx("small",{children:"在当前工作区执行。命令与参数分别填写。"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"命令参数"}),u.jsx("textarea",{"aria-label":"命令参数",rows:3,disabled:m.clearArgs,value:m.args,onChange:z=>S("args",z.target.value),placeholder:o?.argsCount?`已有 ${o.argsCount} 个参数,留空保留。填写后将完整替换。`:"每行一个参数,不需要额外添加引号",autoComplete:"off",spellCheck:!1}),u.jsx("small",{children:"参数可能含密钥,因此不会读回已有值。每一行会作为一个完整参数。"})]}),!!o?.argsCount&&u.jsxs("label",{className:"hub-mcp-check config-full-width",children:[u.jsx("input",{type:"checkbox",checked:m.clearArgs,onChange:z=>S("clearArgs",z.target.checked)}),u.jsx("span",{children:"清空已保存的所有参数"})]})]}):u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"MCP 接口地址"}),u.jsx("input",{type:"url","aria-label":"MCP 接口地址",required:!0,value:m.url,onChange:z=>S("url",z.target.value),placeholder:"https://example.com/mcp"}),o?.urlHasHiddenParts&&u.jsx("small",{children:"已有地址的查询参数已隐藏;不修改地址时会保留。"})]})]}),D?u.jsx(dc,{title:"环境变量",rows:m.env,onChange:z=>S("env",z)}):u.jsx(dc,{title:"请求头",rows:m.headers,onChange:z=>S("headers",z)}),u.jsxs("details",{className:"hub-mcp-advanced",children:[u.jsx("summary",{children:"高级配置"}),u.jsx("div",{className:"config-form-grid",children:D?u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"转发运行环境变量"}),u.jsx("textarea",{"aria-label":"转发运行环境变量",rows:2,value:m.envVars,onChange:z=>S("envVars",z.target.value),placeholder:"每行一个环境变量名称,例如 GITHUB_TOKEN"}),u.jsx("small",{children:"只填写名称,实际值在连接时从CodeShell 的启动环境读取。"})]}):u.jsxs(u.Fragment,{children:[u.jsxs("label",{children:[u.jsx("span",{children:"Bearer Token 环境变量"}),u.jsx("input",{"aria-label":"Bearer Token 环境变量",value:m.bearerTokenEnvVar,onChange:z=>S("bearerTokenEnvVar",z.target.value),placeholder:"例如 MCP_ACCESS_TOKEN",autoComplete:"off"}),u.jsx("small",{children:"填写运行环境中的变量名称。"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"已存储的凭据 ID"}),u.jsx("input",{"aria-label":"已存储的凭据 ID",value:m.credentialRef,onChange:z=>S("credentialRef",z.target.value),placeholder:"可选",autoComplete:"off"}),u.jsx("small",{children:"引用已有凭据;优先于 Bearer 环境变量。"})]})]})}),!D&&u.jsx(dc,{title:"环境变量请求头",rows:m.envHeaders,onChange:z=>S("envHeaders",z),visibleValues:!0}),u.jsxs("label",{className:"hub-mcp-check",children:[u.jsx("input",{type:"checkbox",checked:m.restrictTools,onChange:z=>S("restrictTools",z.target.checked)}),u.jsx("span",{children:"只允许指定工具"})]}),u.jsxs("div",{className:"config-form-grid",children:[m.restrictTools&&u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"允许的工具名称"}),u.jsx("textarea",{rows:2,value:m.allowedTools,onChange:z=>S("allowedTools",z.target.value),placeholder:"每行一个精确工具名称;留空则不开放任何工具"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"停用的工具名称"}),u.jsx("textarea",{rows:2,value:m.disabledTools,onChange:z=>S("disabledTools",z.target.value),placeholder:"每行一个精确工具名称,可留空"})]})]})]}),u.jsxs("label",{className:"hub-mcp-check",children:[u.jsx("input",{type:"checkbox",checked:m.enabled,onChange:z=>S("enabled",z.target.checked)}),u.jsx("span",{children:"启用服务,让任务可以使用这些工具"})]}),N&&u.jsxs("label",{className:"hub-mcp-check hub-mcp-reuse",children:[u.jsx("input",{type:"checkbox",required:!0,checked:m.reuseStoredSecrets,onChange:z=>S("reuseStoredSecrets",z.target.checked)}),u.jsx("span",{children:"允许新的启动方式或服务地址使用已保存的参数、环境变量和认证配置。"})]}),y&&u.jsx("p",{className:"config-error config-message",role:"alert",children:y}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{type:"button",className:"config-button config-button-quiet",onClick:s,children:"取消"}),u.jsx("button",{type:"submit","data-probe":"true",className:"config-button",children:"保存并测试"}),u.jsx("button",{type:"submit",className:"config-button config-button-primary",children:"保存配置"})]})]})})}function dc({title:n,rows:i,onChange:r,visibleValues:s=!1}){const f=(d,o)=>r(i.map(m=>m.id===d?{...m,...o}:m));return u.jsxs("div",{className:"hub-mcp-keys",children:[u.jsxs("div",{className:"hub-mcp-key-heading",children:[u.jsx("h3",{children:n}),u.jsxs("button",{className:"config-text-button",type:"button",onClick:()=>r([...i,{id:la(),name:"",value:"",stored:!1,removed:!1}]),children:["+ 添加",n]})]}),!i.length&&u.jsx("p",{className:"config-help",children:s?"可按请求头名称引用运行环境变量。":"无需此项时可以留空。"}),i.map(d=>u.jsxs("div",{className:`hub-mcp-key-row${d.removed?" hub-mcp-key-removed":""}`,children:[u.jsxs("label",{children:[u.jsxs("span",{className:"config-sr-only",children:[n,"名称"]}),u.jsx("input",{"aria-label":`${n}名称`,value:d.name,readOnly:d.stored,disabled:d.removed,onChange:o=>f(d.id,{name:o.target.value}),placeholder:n==="环境变量"?"例如 API_KEY":"例如 Authorization",autoComplete:"off"})]}),u.jsxs("label",{children:[u.jsxs("span",{className:"config-sr-only",children:[n,"值"]}),u.jsx("input",{"aria-label":`${n} ${d.name||"新条目"} 的值`,type:s?"text":"password",value:d.value,disabled:d.removed,onChange:o=>f(d.id,{value:o.target.value}),placeholder:d.removed?"保存时移除":s?"运行环境变量名称":d.stored?"已配置 · 留空保留":"输入值",autoComplete:s?"off":"new-password",spellCheck:!1})]}),u.jsx("button",{className:"config-button config-button-quiet",type:"button",onClick:()=>d.stored?f(d.id,{removed:!d.removed}):r(i.filter(o=>o.id!==d.id)),children:d.removed?"撤销移除":"移除"})]},d.id)),!!i.length&&!s&&u.jsx("p",{className:"config-help",children:"已有值保留在运行 CodeShell 的设备上;留空保留,填写新值替换,点击“移除”后保存才能删除。"})]})}function t0({result:n}){return u.jsxs("div",{className:`hub-mcp-probe-result hub-mcp-probe-${n.status}`,role:"status",children:[u.jsxs("div",{className:"hub-mcp-probe-summary",children:[u.jsx("strong",{children:n.status==="ok"?"测试连接成功":n.status==="cancelled"?"测试已取消":"连接测试失败"}),u.jsxs("span",{children:[new Date(n.checkedAt).toLocaleTimeString()," ·"," ",n.durationMs<1e3?`${n.durationMs} ms`:`${(n.durationMs/1e3).toFixed(1)} 秒`]})]}),n.error&&u.jsx("p",{children:n.error.message}),n.status==="ok"&&u.jsxs(u.Fragment,{children:[u.jsxs("p",{children:["发现 ",n.toolCount??0," 个工具",n.truncated?"(列表已截取)":"","。测试连接现已关闭。"]}),!!n.tools?.length&&u.jsxs("details",{children:[u.jsx("summary",{children:"查看工具列表"}),u.jsx("ul",{children:n.tools.map((i,r)=>u.jsxs("li",{children:[u.jsxs("div",{children:[u.jsx("code",{children:i.name}),!i.allowed&&u.jsx("span",{className:"config-badge",children:"被工具策略停用"})]}),i.description&&u.jsx("p",{children:i.description})]},`${i.name}-${r}`))})]})]})]})}const n0={overview:{title:"设置",description:"管理当前工作区的模型、Skills 和工具连接。"},models:{title:"模型与连接",description:"选择默认模型,管理工作区使用的服务商连接与凭据。"},skills:{title:"Skills",description:"让 CodeShell 按照你熟悉的工作方式完成任务。"},mcp:{title:"MCP 工具",description:"管理工具连接,测试连接并查看可用工具。"}};function l0(n){return n.section==="skills"?u.jsx(Hv,{onAuthLost:n.onAuthLost,onDirtyChange:n.onDirtyChange,onChanged:n.onConfigurationChange,configurationVersion:n.configurationVersion}):u.jsx(i0,{...n})}function i0({host:n="hub",section:i,onSectionChange:r,onAuthLost:s,onDirtyChange:f,onConfigurationChange:d,configurationVersion:o=0}){const[m,g]=w.useState(null),[p,b]=w.useState(!0),[y,v]=w.useState(""),[S,N]=w.useState(""),[D,z]=w.useState(null),[_,M]=w.useState(0),H=w.useRef({onAuthLost:s,onConfigurationChange:d});H.current={onAuthLost:s,onConfigurationChange:d};const oe=w.useRef(!1),ce=w.useRef(0),R=w.useRef(null),W=w.useRef(null),ie=w.useRef(!1),F=w.useRef(o),A=w.useCallback(se=>{se instanceof We&&se.status===401?H.current.onAuthLost():v(Ig(se))},[]);w.useEffect(()=>{o!==F.current&&(F.current=o,W.current?ie.current=!0:M(se=>se+1))},[o]),w.useEffect(()=>(oe.current=!0,()=>{oe.current=!1,W.current?.abort()}),[]),w.useEffect(()=>{const se=new AbortController;R.current=se;const ae=++ce.current;return b(!0),v(""),Hg(se.signal).then(P=>{!se.signal.aborted&&ae===ce.current&&g(P)}).catch(P=>{!se.signal.aborted&&ae===ce.current&&A(P)}).finally(()=>{!se.signal.aborted&&ae===ce.current&&b(!1)}),()=>se.abort()},[_,A]);const G=async(se,ae)=>{if(W.current)return!1;R.current?.abort();const P=++ce.current,E=new AbortController;W.current=E,b(!1),z(se),v(""),N("");try{const U=await ae(E.signal);return!oe.current||E.signal.aborted||P!==ce.current?!1:(g(U),N(U.restartRequired?"设置已保存,重启服务后生效。":"设置已保存,下次运行任务时生效。"),H.current.onConfigurationChange?.(),!0)}catch(U){return U instanceof We&&U.status===409&&(ie.current=!0),oe.current&&!E.signal.aborted&&A(U),!1}finally{W.current===E&&(W.current=null),oe.current&&!E.signal.aborted&&(z(null),ie.current&&(ie.current=!1,M(U=>U+1)))}},V=n0[i];return u.jsxs("section",{className:"hub-settings","aria-labelledby":"hub-settings-title",children:[u.jsxs("div",{className:"hub-settings-heading",children:[u.jsxs("div",{children:[u.jsx("span",{className:"hub-settings-eyebrow",children:n==="desktop"?"桌面工作区":"服务端工作区"}),u.jsx("h1",{id:"hub-settings-title",children:V.title}),u.jsx("p",{children:V.description})]}),u.jsx("button",{className:"config-button config-button-quiet",disabled:p||D!==null,onClick:()=>{N(""),M(se=>se+1)},children:p?"读取中…":"刷新"})]}),y&&u.jsx("div",{className:"config-message config-error",role:"alert",children:y}),S&&u.jsx("div",{className:"config-message config-success",role:"status",children:S}),D&&u.jsxs("p",{className:"config-loading",role:"status",children:["正在保存",D,"…"]}),!m&&p?u.jsx("p",{className:"config-loading",role:"status",children:"正在读取工作区设置…"}):null,m&&u.jsxs(u.Fragment,{children:[i==="overview"&&u.jsx(r0,{host:n,configuration:m,onSectionChange:r}),i==="models"&&u.jsx(a0,{configuration:m,disabled:D!==null||p,saving:D!==null,save:G,onDirtyChange:f,onAuthLost:s}),i==="mcp"&&u.jsx(e0,{onAuthLost:s,onDirtyChange:f,onConfigurationChange:d,configurationVersion:o}),u.jsx("p",{className:"config-scope-note",children:"配置作用于当前工作区,所有连接到这里的设备共用。"})]})]})}function r0({host:n,configuration:i,onSectionChange:r}){const s=i.connections.find(o=>o.id===i.defaults.text),f=i.skills.filter(o=>o.enabled).length,d=[{section:"models",title:"模型与连接",summary:s?`${s.id} · ${s.model}`:"尚未设置默认模型",icon:"◈"},{section:"skills",title:"Skills",summary:`${i.skills.length} 个可用 · ${f} 个已启用`,icon:"✧"},{section:"mcp",title:"MCP 工具",summary:`${i.mcpServers.length} 个已配置的工具服务`,icon:"⌘"}];return u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"config-workspace-card",children:[u.jsx("span",{className:"config-workspace-icon","aria-hidden":"true",children:"▱"}),u.jsxs("div",{children:[u.jsx("strong",{children:"当前工作区"}),u.jsx("code",{children:i.workspace.path}),u.jsx("p",{children:n==="desktop"?"对话、文件操作和工具都由已连接的桌面端执行。":"对话、文件操作和工具都在服务端运行。"})]}),u.jsx("span",{className:"config-badge",children:n==="desktop"?"桌面工作区":"服务端工作区"})]}),u.jsx("h2",{className:"config-section-title",children:"工作区配置"}),u.jsx("div",{className:"config-card config-overview-list",children:d.map(o=>{const m=u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"config-row-icon","aria-hidden":"true",children:o.icon}),u.jsxs("span",{className:"config-row-copy",children:[u.jsx("strong",{children:o.title}),u.jsx("span",{children:o.summary})]}),r&&u.jsx("span",{className:"config-chevron","aria-hidden":"true",children:"›"})]});return r?u.jsx("button",{className:"config-overview-row",onClick:()=>r(o.section),children:m},o.section):u.jsx("div",{className:"config-overview-row",children:m},o.section)})}),u.jsxs("div",{className:"config-explanation",children:[u.jsx("h2",{children:"工作区与执行位置"}),u.jsx("p",{children:n==="desktop"?"这里直接使用桌面端的任务、模型、Skills 和工具连接。修改配置后,桌面窗口和已配对的网页共同使用。":"这里使用服务端的任务、模型、Skills 和工具连接。修改配置后,连接到这个服务端的网页共同使用。"}),u.jsx("p",{children:n==="desktop"?"切换项目会切换对应的文件、历史和工作区设置;无需复制桌面配置。":"独立部署使用自己的运行环境。部署到另一台机器时,需要迁移配置和数据,或在这里重新设置。"})]})]})}function a0({configuration:n,disabled:i,saving:r,save:s,onDirtyChange:f,onAuthLost:d}){const[o,m]=w.useState(null),[g,p]=w.useState(null),[b,y]=w.useState(""),[v,S]=w.useState(!1),[N,D]=w.useState(!1),[z,_]=w.useState(null),[M,H]=w.useState({}),oe=w.useRef(null),ce=n.connections.filter(A=>A.tag==="text"),R=n.connections.length-ce.length,W=i||!!z;w.useEffect(()=>{g&&!n.connections.some(A=>A.id===g.id)&&p(null)},[n.connections,g]),w.useEffect(()=>()=>oe.current?.abort(),[]);const ie=w.useRef(new Map);w.useEffect(()=>{const A=new Map(n.connections.map(V=>[V.id,V.revision??JSON.stringify(V)])),G=new Set([...ie.current].filter(([V,se])=>A.get(V)!==se).map(([V])=>V));ie.current=A,z&&G.has(z)&&oe.current?.abort(),G.size&&H(V=>Object.fromEntries(Object.entries(V).filter(([se])=>!G.has(se))))},[n,z]),w.useEffect(()=>(f?.(v||N||r||!!z),()=>f?.(!1)),[v,N,r,z,f]);const F=async A=>{if(oe.current)return;const G=new AbortController;oe.current=G,_(A.id),H(V=>({...V,[A.id]:"正在发送一条简短测试请求…"}));try{const V=await zv(A.id,G.signal);G.signal.aborted||H(se=>({...se,[A.id]:V}))}catch(V){G.signal.aborted||(V instanceof We&&V.status===401?d():H(se=>({...se,[A.id]:Ig(V)})))}finally{oe.current===G&&(oe.current=null,_(null))}};return u.jsxs(u.Fragment,{children:[u.jsx(s0,{configuration:n,disabled:W,save:s,onDirtyChange:D}),u.jsxs("div",{className:"config-section-heading",children:[u.jsxs("h2",{children:["文字模型连接 ",u.jsx("span",{className:"config-count",children:ce.length})]}),u.jsxs("button",{className:"config-button",disabled:W||o!==null||g!==null||!n.catalog.length,onClick:()=>m("__new__"),children:[u.jsx("span",{"aria-hidden":"true",children:"+"})," 添加连接"]})]}),o!==null&&u.jsxs("div",{className:"config-card config-editor-card",children:[u.jsx("h3",{children:o==="__new__"?"添加模型连接":`编辑 ${o.id}`}),u.jsx(u0,{connection:o==="__new__"?void 0:o,configuration:n,disabled:W,save:s,onDone:()=>m(null),onDirtyChange:S},o==="__new__"?"new":o.id)]}),!ce.length&&o!=="__new__"&&u.jsx(o0,{title:"还没有文字模型连接",description:"添加服务商地址、模型名称和 API Key,再选择一个默认模型。"}),u.jsx("div",{className:"config-connection-list",children:ce.map(A=>{const G=n.catalog.find(E=>E.id===A.catalogId),V=g?.id===A.id,se=V&&g?.revision!==A.revision,ae=n.defaults.text===A.id&&ce.length>1,P=M[A.id];return u.jsxs("article",{className:"config-card config-connection-card",children:[u.jsxs("div",{className:"config-connection-head",children:[u.jsx("span",{className:"config-model-icon","aria-hidden":"true",children:"◈"}),u.jsxs("div",{className:"config-row-copy",children:[u.jsx("strong",{children:A.id}),u.jsx("span",{children:G?.displayName??A.catalogId})]}),n.defaults.text===A.id&&u.jsx("span",{className:"config-badge config-badge-accent",children:"默认"}),u.jsx("button",{className:"config-button config-button-quiet",disabled:W||o!==null||g!==null,onClick:()=>m(A),children:"编辑"})]}),u.jsxs("dl",{className:"config-connection-facts",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"模型"}),u.jsx("dd",{children:A.model||"未填写"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"服务地址"}),u.jsx("dd",{children:A.baseUrl||G?.defaultBaseUrl||"服务商默认地址"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"API Key"}),u.jsx("dd",{children:A.hasApiKey?"•••••••• · 已配置":A.needsKey?"未配置":"无需 API Key"})]})]}),u.jsxs("div",{className:"config-model-actions",children:[z===A.id?u.jsx("button",{className:"config-button",onClick:()=>{oe.current?.abort(),H(E=>({...E,[A.id]:"已取消连接测试。"}))},children:"取消测试"}):u.jsx("button",{className:"config-button",disabled:W||o!==null||g!==null,onClick:()=>{F(A)},children:"测试连接"}),u.jsx("span",{className:"config-help",children:"发送一条简短请求,服务商可能计费。"}),u.jsx("button",{className:"config-button config-button-quiet config-remove-connection",disabled:W||o!==null||g!==null,onClick:()=>{p(A),y("")},children:"删除"})]}),P&&u.jsxs("div",{className:`config-probe-result ${typeof P!="string"&&P.ok?"is-success":""}`,role:"status",children:[u.jsx("span",{children:typeof P=="string"?P:P.message}),typeof P!="string"&&u.jsxs("small",{children:[Math.max(.01,P.latencyMs/1e3).toFixed(2)," 秒 ·"," ",new Date(P.checkedAt).toLocaleTimeString()]})]}),V&&u.jsxs("div",{className:"config-remove-confirm",children:[u.jsxs("h3",{children:["删除连接 ",A.id,"?"]}),u.jsx("p",{children:"连接会从当前工作区移除,已有对话记录会保留。"}),se&&u.jsx("p",{role:"alert",children:"连接已被其他设备更新,请取消后重新检查再删除。"}),ce.length===1&&u.jsx("p",{children:"这是最后一个文字模型连接。删除后需重新添加连接才能继续对话。"}),ae&&u.jsxs("label",{children:[u.jsx("span",{children:"替代默认模型"}),u.jsxs("select",{"aria-label":"替代默认模型",value:b,onChange:E=>y(E.target.value),disabled:W,children:[u.jsx("option",{value:"",children:"请选择其他连接"}),ce.filter(E=>E.id!==A.id).map(E=>u.jsxs("option",{value:E.id,children:[E.id," · ",E.model]},E.id))]})]}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{className:"config-button",disabled:W,onClick:()=>p(null),children:"取消删除"}),u.jsx("button",{className:"config-button config-button-danger",disabled:W||se||ae&&!b,onClick:()=>{s("删除连接",E=>Av(A.id,b||void 0,E,g?.revision)).then(E=>{E&&p(null)})},children:"确认删除连接"})]})]})]},A.id)})}),R>0&&u.jsxs("p",{className:"config-help",children:["另有 ",R," 个其他类型的模型连接,保留在工作区配置中。目前此处提供文字模型编辑。"]})]})}function s0({configuration:n,disabled:i,save:r,onDirtyChange:s}){const[f,d]=w.useState(n.defaults.text??""),[o,m]=w.useState(n.defaults.auxText??""),g=w.useRef(n.defaults);w.useEffect(()=>{const y=g.current;g.current=n.defaults,d(v=>v===(y.text??"")?n.defaults.text??"":v),m(v=>v===(y.auxText??"")?n.defaults.auxText??"":v)},[n.defaults]);const p=n.connections.filter(y=>y.tag==="text"),b=f!==(n.defaults.text??"")||o!==(n.defaults.auxText??"");return w.useEffect(()=>(s(b),()=>s(!1)),[b,s]),u.jsx("form",{className:"config-card config-defaults",onSubmit:y=>{y.preventDefault(),r("默认模型",v=>Nv({text:f,auxText:o||null},v))},children:u.jsxs("fieldset",{disabled:i||!p.length,children:[u.jsx("legend",{children:"默认模型"}),u.jsxs("div",{className:"config-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"对话模型"}),u.jsxs("select",{required:!0,value:f,onChange:y=>d(y.target.value),"aria-label":"默认对话模型",children:[u.jsx("option",{value:"",disabled:!0,children:"选择模型连接"}),f&&!p.some(y=>y.id===f)&&u.jsxs("option",{value:f,disabled:!0,children:[f,"(连接不可用)"]}),p.map(y=>u.jsxs("option",{value:y.id,children:[y.id," · ",y.model]},y.id))]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"辅助模型"}),u.jsxs("select",{value:o,onChange:y=>m(y.target.value),"aria-label":"默认辅助模型",children:[u.jsx("option",{value:"",children:"跟随对话模型"}),o&&!p.some(y=>y.id===o)&&u.jsxs("option",{value:o,disabled:!0,children:[o,"(连接不可用)"]}),p.map(y=>u.jsxs("option",{value:y.id,children:[y.id," · ",y.model]},y.id))]})]})]}),u.jsxs("div",{className:"config-form-footer",children:[u.jsx("p",{className:"config-help",children:"辅助模型用于标题生成等轻量任务。"}),u.jsx("button",{className:"config-button",disabled:!b||!f,type:"submit",children:"保存默认模型"})]})]})})}function u0({connection:n,configuration:i,disabled:r,save:s,onDone:f,onDirtyChange:d}){const[o,m]=w.useState(()=>{const M=cc(n);return n||(M.catalogId=i.catalog[0]?.id??""),M}),g=w.useRef(o),p=JSON.stringify(o)!==JSON.stringify(g.current),[b,y]=w.useState(!1),v=n?i.connections.find(M=>M.id===n.id):void 0,S=!!n&&(!v||o.expectedRevision!==v.revision);w.useEffect(()=>{if(!p&&v&&o.expectedRevision!==v.revision){const M=cc(v);g.current=M,m(M)}},[p,v,o.expectedRevision]);const N=()=>{if(!v)return;const M=cc(v);g.current=M,m(M),y(!1)};w.useEffect(()=>(d(p),()=>d(!1)),[p,d]);const D=i.catalog.find(M=>M.id===o.catalogId),z=!n&&i.connections.some(M=>M.id===o.id.trim()),_=(M,H)=>m(oe=>({...oe,[M]:H}));return u.jsx("form",{className:"config-connection-editor",onSubmit:async M=>{M.preventDefault(),!S&&await s("模型连接",H=>Ev(o,H))&&f()},children:u.jsxs("fieldset",{disabled:r,children:[u.jsx("legend",{className:"config-sr-only",children:n?`编辑 ${n.id}`:"新模型连接"}),S&&u.jsxs("div",{className:"config-remove-confirm",role:"alert",children:[u.jsx("p",{children:v?"其他设备已更新这个连接。你的草稿已保留,请检查最新设置后再保存。":"这个连接已被其他设备删除。草稿仍保留,你可以复制内容后关闭编辑。"}),v&&u.jsx("button",{className:"config-button",type:"button",onClick:N,children:"放弃草稿并载入最新设置"})]}),u.jsxs("div",{className:"config-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"连接名称"}),u.jsx("input",{required:!0,maxLength:120,value:o.id,readOnly:!!n,onChange:M=>_("id",M.target.value),placeholder:"例如 work-model",autoComplete:"off"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"服务商"}),u.jsxs("select",{required:!0,disabled:!!n,"aria-label":"服务商",value:o.catalogId,onChange:M=>_("catalogId",M.target.value),children:[n&&!D&&u.jsx("option",{value:o.catalogId,children:o.catalogId}),i.catalog.map(M=>u.jsx("option",{value:M.id,children:M.displayName},M.id))]})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"模型名称"}),u.jsx("input",{required:!0,maxLength:240,value:o.model,onChange:M=>_("model",M.target.value),placeholder:"服务商提供的模型 ID",autoComplete:"off"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsx("span",{children:"服务地址"}),u.jsx("input",{type:"url","aria-label":"服务地址",value:o.baseUrl,onChange:M=>_("baseUrl",M.target.value),placeholder:D?.defaultBaseUrl||"使用服务商默认地址",autoComplete:"off"}),u.jsx("small",{children:"留空使用服务商默认地址,支持兼容接口。"})]}),u.jsxs("label",{className:"config-full-width",children:[u.jsxs("span",{children:["API Key ",n?.hasApiKey&&u.jsx("span",{className:"config-field-meta",children:"已配置"})]}),u.jsx("input",{type:"password","aria-label":"API Key",required:D?.needsKey&&!n?.hasApiKey,value:o.apiKey,onChange:M=>_("apiKey",M.target.value),placeholder:n?.hasApiKey?"留空保留现有 API Key":D?.needsKey?"输入 API Key":"可选",autoComplete:"new-password",spellCheck:!1}),u.jsx("small",{children:n?.hasApiKey?"现有密钥保留在运行 CodeShell 的设备上,输入新值可替换。":"密钥保存在当前工作区配置中。"})]})]}),z&&u.jsx("p",{className:"config-error config-message",role:"alert",children:"连接名称已存在,请使用其他名称或编辑现有连接。"}),u.jsx("p",{className:"config-help",children:"保存后可在连接卡片中测试实际连接。"}),b&&u.jsxs("div",{className:"config-remove-confirm",role:"alert",children:[u.jsx("p",{children:"还有未保存的修改,确定放弃?"}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{type:"button",className:"config-button",onClick:()=>y(!1),children:"继续编辑"}),u.jsx("button",{type:"button",className:"config-button config-button-danger",onClick:f,children:"放弃修改"})]})]}),u.jsxs("div",{className:"config-form-actions",children:[u.jsx("button",{type:"button",className:"config-button config-button-quiet",onClick:()=>p?y(!0):f(),children:"取消"}),u.jsx("button",{type:"submit",className:"config-button config-button-primary",disabled:z||S,children:"保存连接"})]})]})})}function o0({title:n,description:i}){return u.jsxs("div",{className:"config-empty",children:[u.jsx("span",{"aria-hidden":"true",children:"◇"}),u.jsx("h3",{children:n}),u.jsx("p",{children:i})]})}function hc(n,i=!1){return Rt(`/api/v1/files/content?path=${encodeURIComponent(n)}${i?"&inline=true":""}`)}function Rm(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function c0({initialPath:n,openVersion:i=0,onAuthLost:r}){const[s,f]=w.useState(""),[d,o]=w.useState(null),[m,g]=w.useState(null),[p,b]=w.useState(!1),[y,v]=w.useState(!1),[S,N]=w.useState(""),[D,z]=w.useState(0),[_,M]=w.useState(""),H=w.useRef(null),oe=w.useRef(r);oe.current=r;const ce=w.useCallback(F=>{F instanceof We&&F.status===401?oe.current():N(F instanceof Error?F.message:"文件读取失败,请重试。")},[]);w.useEffect(()=>{const F=new AbortController;return b(!0),N(""),Ve(`/api/v1/files?path=${encodeURIComponent(s)}`,{signal:F.signal}).then(A=>{F.signal.aborted||o(A)}).catch(A=>{F.signal.aborted||ce(A)}).finally(()=>{F.signal.aborted||b(!1)}),()=>F.abort()},[s,D,ce]);const R=w.useCallback((F,A=!1)=>{H.current?.abort();const G=new AbortController;H.current=G,g(null),v(!0),N(""),Ve(`${hc(F)}&preview=true`,{signal:G.signal}).then(V=>{G.signal.aborted||(A&&f(V.path.split("/").slice(0,-1).join("/")),g(V))}).catch(V=>{G.signal.aborted||ce(V)}).finally(()=>{G.signal.aborted||v(!1)})},[ce]);w.useEffect(()=>{n&&R(n,!0)},[n,i,R]),w.useEffect(()=>()=>H.current?.abort(),[]);const W=F=>{H.current?.abort(),v(!1),g(null),f(F),M("")},ie=d?.files.filter(F=>F.name.toLocaleLowerCase().includes(_.toLocaleLowerCase()))??[];return u.jsxs("section",{className:"hub-library hub-files","aria-labelledby":"hub-files-heading",children:[u.jsxs("header",{className:"library-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{id:"hub-files-heading",children:"工作区文件"}),u.jsx("p",{children:"查看任务生成的内容,下载到当前设备。"})]}),u.jsx("button",{className:"library-button",onClick:()=>{z(F=>F+1),m&&R(m.path)},children:"刷新"})]}),S?u.jsx("div",{className:"library-error",role:"alert",children:S}):null,u.jsxs("nav",{className:"file-breadcrumbs","aria-label":"文件位置",children:[u.jsx("button",{onClick:()=>W(""),children:"工作区"}),(d?.path??s).split("/").filter(Boolean).map((F,A,G)=>u.jsxs(w.Fragment,{children:[u.jsx("span",{"aria-hidden":"true",children:"/"}),u.jsx("button",{onClick:()=>W(G.slice(0,A+1).join("/")),children:F})]},A))]}),u.jsxs("div",{className:`file-columns${m||y?" has-preview":""}`,children:[u.jsxs("div",{className:"file-directory",children:[u.jsxs("label",{className:"library-search",children:[u.jsx("span",{className:"sr-only",children:"筛选当前文件夹"}),u.jsx("input",{type:"search",placeholder:"筛选当前文件夹…",value:_,onChange:F=>M(F.target.value)})]}),u.jsx("div",{className:"file-entries","aria-busy":p,children:p?u.jsx("p",{className:"library-empty",role:"status",children:"正在读取文件…"}):ie.length===0?u.jsx("p",{className:"library-empty",children:_?"没有匹配的文件。":"这个文件夹还没有文件。"}):ie.map(F=>u.jsxs("button",{className:`file-entry${m?.path===F.path?" selected":""}`,onClick:()=>F.kind==="directory"?W(F.path):R(F.path),children:[u.jsx("span",{className:"file-glyph","aria-hidden":"true",children:F.kind==="directory"?"▱":"▤"}),u.jsx("span",{className:"file-entry-name",children:F.name}),u.jsx("span",{className:"file-entry-size",children:F.kind==="directory"?"文件夹":Rm(F.size)})]},F.path))}),d?.truncated?u.jsx("p",{className:"library-hint",children:"这里只显示前 500 项。可以进入子文件夹继续查看。"}):null]}),y||m?u.jsxs("article",{className:"file-preview","aria-label":"文件预览",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("strong",{children:m?.name??"正在打开…"}),m?u.jsx("span",{children:Rm(m.size)}):null]}),u.jsxs("div",{className:"library-actions",children:[m?u.jsx("a",{className:"library-button",href:hc(m.path),download:!0,children:"下载"}):null,u.jsx("button",{className:"library-button",onClick:()=>{H.current?.abort(),v(!1),g(null)},children:"关闭预览"})]})]}),y?u.jsx("p",{className:"library-empty",role:"status",children:"正在读取内容…"}):m?.kind==="text"?u.jsxs(u.Fragment,{children:[u.jsx("pre",{tabIndex:0,children:m.content}),m.truncated?u.jsx("p",{className:"library-hint",children:"预览显示前 512 KB,下载可获取完整内容。"}):null]}):m?.kind==="image"?u.jsx("img",{src:hc(m.path,!0),alt:m.name,onError:()=>N("图片无法预览,可以下载后打开。")}):u.jsx("div",{className:"library-empty",children:"这个文件暂不支持直接预览,可以下载后打开。"})]}):null]})]})}async function Dc(n={}){const i=new URLSearchParams({archived:n.archived??"false",limit:"50"});return n.query&&i.set("query",n.query),n.cursor&&i.set("cursor",n.cursor),Ve(`/api/v1/sessions?${i}`,{signal:n.signal})}function _m(n,i="markdown"){return Rt(`/api/v1/sessions/${encodeURIComponent(n)}/export?format=${i}`)}function f0({onAuthLost:n,onOpen:i,onChanged:r,version:s=0,onDirtyChange:f}){const[d,o]=w.useState(""),[m,g]=w.useState(""),[p,b]=w.useState("false"),[y,v]=w.useState([]),[S,N]=w.useState(null),[D,z]=w.useState(!0),[_,M]=w.useState(!1),[H,oe]=w.useState(""),[ce,R]=w.useState(""),[W,ie]=w.useState(0),[F,A]=w.useState(""),[G,V]=w.useState(null),se=w.useRef(null),ae=w.useRef(null),P=w.useRef(null),E=w.useRef(null);w.useEffect(()=>{G?.id&&se.current?.focus()},[G?.id]),w.useEffect(()=>{G?.error&&ae.current?.focus()},[G?.error]);const U=()=>{V(null),requestAnimationFrame(()=>{P.current?.isConnected?P.current.focus():E.current?.focus()})};w.useEffect(()=>{f?.(!!G||!!F)},[G,F,f]),w.useEffect(()=>()=>f?.(!1),[f]);const te=w.useRef(null),he=w.useRef(null),k=w.useRef({onAuthLost:n,onChanged:r,onOpen:i});k.current={onAuthLost:n,onChanged:r,onOpen:i};const T=w.useCallback(Q=>{Q instanceof We&&Q.status===401?k.current.onAuthLost():oe(Q instanceof Error?Q.message:"会话操作失败,请重试。")},[]);w.useEffect(()=>{const Q=setTimeout(()=>g(d.trim()),200);return()=>clearTimeout(Q)},[d]),w.useEffect(()=>{te.current?.abort();const Q=new AbortController;return te.current=Q,z(!0),M(!1),oe(""),Dc({query:m,archived:p,signal:Q.signal}).then(pe=>{Q.signal.aborted||(v(pe.sessions),N(pe.nextCursor))}).catch(pe=>{Q.signal.aborted||T(pe)}).finally(()=>{Q.signal.aborted||z(!1)}),()=>Q.abort()},[m,p,s,W,T]),w.useEffect(()=>()=>{te.current?.abort(),he.current?.abort()},[]);const K=()=>{if(!S||_||D)return;const Q=new AbortController;te.current?.abort(),te.current=Q,M(!0),Dc({query:m,archived:p,cursor:S,signal:Q.signal}).then(pe=>{Q.signal.aborted||(v(je=>{const Y=new Set(je.map(xe=>xe.sessionId));return[...je,...pe.sessions.filter(xe=>!Y.has(xe.sessionId))]}),N(pe.nextCursor))}).catch(pe=>{Q.signal.aborted||T(pe)}).finally(()=>{Q.signal.aborted||M(!1)})},C=async(Q,pe,je=!1)=>{if(he.current)return;const Y=new AbortController;he.current=Y,A(Q),oe(""),R(""),"title"in pe&&V(xe=>xe&&{...xe,error:""});try{if(await Ve(`/api/v1/sessions/${encodeURIComponent(Q)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(pe),signal:Y.signal}),Y.signal.aborted)return;"title"in pe?(U(),R(pe.title?"标题已保存。":"已恢复自动标题。")):R(pe.archived?"对话已归档,可以在“已归档”中恢复。":"对话已恢复。"),ie(xe=>xe+1),k.current.onChanged?.(),je&&k.current.onOpen(Q)}catch(xe){Y.signal.aborted||("title"in pe&&!(xe instanceof We&&xe.status===401)?V(J=>J?.id===Q?{...J,error:xe instanceof Error?xe.message:"标题保存失败,请重试。",conflict:xe instanceof We&&xe.status===409,unavailable:xe instanceof We&&xe.status===404}:J):T(xe))}finally{he.current===Y&&(he.current=null),Y.signal.aborted||A("")}},re=async()=>{if(!G||he.current)return;const Q=G.id,pe=new AbortController;he.current=pe,A(Q),V(je=>je&&{...je,error:""});try{const je=await Ve(`/api/v1/sessions/${encodeURIComponent(Q)}`,{signal:pe.signal});if(pe.signal.aborted)return;V(Y=>Y?.id===Q?{...Y,expectedTitle:je.customTitle,reviewedTitle:je.title,conflict:!1,unavailable:!1,error:""}:Y),se.current?.focus()}catch(je){pe.signal.aborted||(je instanceof We&&je.status===401?T(je):V(Y=>Y?.id===Q?{...Y,error:je instanceof Error?je.message:"无法读取最新标题,请重试。",unavailable:je instanceof We&&je.status===404}:Y))}finally{he.current===pe&&(he.current=null),pe.signal.aborted||A("")}},ve=Q=>Q.archivedAt?void C(Q.sessionId,{archived:!1},!0):k.current.onOpen(Q.sessionId);return u.jsxs("section",{className:"hub-library hub-sessions","aria-labelledby":"hub-history-heading",children:[u.jsxs("header",{className:"library-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{id:"hub-history-heading",children:"历史对话"}),u.jsx("p",{children:"查找、整理并导出当前工作区的对话。"})]}),u.jsx("button",{className:"library-button",onClick:()=>ie(Q=>Q+1),children:"刷新"})]}),H?u.jsx("div",{className:"library-error",role:"alert",children:H}):null,ce?u.jsx("p",{className:"library-hint",role:"status",children:ce}):null,u.jsxs("div",{className:"session-toolbar",children:[u.jsxs("label",{className:"library-search",children:[u.jsx("span",{className:"sr-only",children:"搜索对话标题"}),u.jsx("input",{ref:E,type:"search",placeholder:"搜索对话标题…",value:d,onChange:Q=>o(Q.target.value)})]}),u.jsxs("label",{children:[u.jsx("span",{className:"sr-only",children:"对话范围"}),u.jsxs("select",{value:p,onChange:Q=>b(Q.target.value),children:[u.jsx("option",{value:"false",children:"当前对话"}),u.jsx("option",{value:"true",children:"已归档"}),u.jsx("option",{value:"all",children:"全部对话"})]})]})]}),G?u.jsxs("form",{className:"session-history-editor","aria-labelledby":"session-title-editor-heading",onSubmit:Q=>{Q.preventDefault(),!F&&!G.conflict&&!G.unavailable&&C(G.id,{title:G.title,expectedTitle:G.expectedTitle})},children:[u.jsxs("div",{children:[u.jsx("h2",{id:"session-title-editor-heading",children:"重命名对话"}),u.jsxs("p",{className:"library-hint",children:["正在编辑:",G.originalTitle]}),!D&&!y.some(Q=>Q.sessionId===G.id)?u.jsx("p",{className:"library-hint",children:"此对话已不在当前列表中,标题草稿仍保留在这里。"}):null]}),G.error?u.jsx("div",{className:"library-error",id:"session-title-error",role:"alert",tabIndex:-1,ref:ae,children:G.error}):null,G.reviewedTitle?u.jsxs("p",{className:"session-title-review",role:"status",children:["最新标题:",u.jsx("strong",{children:G.reviewedTitle}),"。你的草稿仍保留,请核对后再保存。"]}):null,u.jsxs("label",{children:[u.jsx("span",{children:"对话标题"}),u.jsx("input",{ref:se,className:"library-title-input",value:G.title,maxLength:1024,"aria-describedby":G.error?"session-title-error":void 0,onChange:Q=>{const pe=Q.target.value;V(je=>je&&{...je,title:pe})},readOnly:!!F})]}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{type:"submit",className:"library-button primary",disabled:!!F||G.conflict||G.unavailable,children:F?"处理中…":G.reviewedTitle?"确认保存我的标题":"保存标题"}),G.conflict||G.unavailable?u.jsx("button",{type:"button",className:"library-button",disabled:!!F,onClick:()=>{re()},children:"读取最新标题"}):null,u.jsx("button",{type:"button",className:"library-button",disabled:!!F,onClick:U,children:"取消"}),G.expectedTitle?u.jsx("button",{type:"button",className:"library-button",disabled:!!F||G.conflict||G.unavailable,onClick:()=>{C(G.id,{title:"",expectedTitle:G.expectedTitle})},children:"使用自动标题"}):null]})]}):null,u.jsx("div",{className:"session-history-list","aria-busy":D,children:D?u.jsx("p",{className:"library-empty",role:"status",children:"正在读取对话…"}):y.length===0?u.jsx("p",{className:"library-empty",children:m?"没有找到匹配的对话。":p==="true"?"还没有归档的对话。":"还没有保存的对话,开始一条新对话后会显示在这里。"}):y.map(Q=>u.jsxs("article",{className:"session-history-row",children:[u.jsxs("div",{className:"session-history-info",children:[u.jsx("button",{className:"session-history-title",onClick:()=>ve(Q),children:Q.title}),Q.preview&&Q.preview!==Q.title?u.jsx("p",{children:Q.preview.slice(0,150)}):null,u.jsxs("div",{className:"session-history-meta",children:[u.jsx("span",{children:new Date(Q.lastActiveAt||Q.startedAt).toLocaleString()}),u.jsxs("span",{children:[Q.turnCount," 轮"]}),Q.running?u.jsx("span",{children:"正在运行"}):Q.archivedAt?u.jsx("span",{children:"已归档"}):null]})]}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button",disabled:!!F||!!G,onClick:pe=>{P.current=pe.currentTarget,R(""),V({id:Q.sessionId,title:Q.title,originalTitle:Q.title,expectedTitle:Q.customTitle})},children:G?.id===Q.sessionId?"正在编辑":"重命名"}),u.jsx("button",{className:"library-button",disabled:!!F||Q.running,onClick:()=>{C(Q.sessionId,{archived:!Q.archivedAt})},children:F===Q.sessionId?"处理中…":Q.archivedAt?"恢复":"归档"}),Q.running?u.jsx("button",{className:"library-button",disabled:!0,children:"运行结束后导出"}):u.jsxs("details",{className:"session-export",children:[u.jsx("summary",{className:"library-button",children:"导出"}),u.jsxs("div",{children:[u.jsx("a",{href:_m(Q.sessionId),download:!0,children:"Markdown 文档"}),u.jsx("a",{href:_m(Q.sessionId,"json"),download:!0,children:"完整 JSON 记录"})]})]})]})]},Q.sessionId))}),S&&!D?u.jsx("div",{className:"session-load-more",children:u.jsx("button",{className:"library-button",disabled:_,onClick:K,children:_?"读取中…":"加载更多"})}):null]})}const Ol="/api/v1/links",d0={connected:"已连接",expired:"授权已过期",invalid:"需要重新连接",unavailable:"凭据不可用"};function Vi(n){try{const i=new URL(n??"");return i.protocol==="https:"&&!i.username&&!i.password?i.href:void 0}catch{return}}function h0({onAuthLost:n,onDirtyChange:i,hostLabel:r="服务端",configurationVersion:s=0}){const[f,d]=w.useState(),[o,m]=w.useState(),[g,p]=w.useState(""),[b,y]=w.useState(""),[v,S]=w.useState(""),[N,D]=w.useState(!0),[z,_]=w.useState(!1),[M,H]=w.useState(),[oe,ce]=w.useState(),[R,W]=w.useState(),[ie,F]=w.useState(0),A=w.useRef(!1),G=w.useRef(void 0),V=w.useRef(void 0),se=w.useRef(void 0),ae=w.useRef({onAuthLost:n,onDirtyChange:i});ae.current={onAuthLost:n,onDirtyChange:i};const P=z||R?.state==="pending"||!!(o&&(o.token||o.label!==(o.original?.label??o.provider.displayName))),E=w.useCallback(J=>{J instanceof We&&J.status===401?ae.current.onAuthLost():y(J instanceof Error?J.message:"连接操作失败,请重试。")},[]);w.useEffect(()=>{ae.current.onDirtyChange?.(P)},[P]),w.useEffect(()=>(A.current=!0,()=>{A.current=!1,ae.current.onDirtyChange?.(!1),G.current?.abort(),V.current&&Ve(V.current,{method:"DELETE",keepalive:!0}).catch(()=>{})}),[]),w.useEffect(()=>{const J=new AbortController;return se.current=J,D(!0),Ve(Ol,{signal:J.signal}).then(ye=>{J.signal.aborted||d(ye)}).catch(ye=>{J.signal.aborted||E(ye)}).finally(()=>{J.signal.aborted||D(!1)}),()=>J.abort()},[ie,s,E]),w.useEffect(()=>{if(R?.state!=="pending"||!V.current)return;const J=V.current,ye=new AbortController;let Ae;const we=async()=>{try{const Ye=await Ve(J,{signal:ye.signal});if(ye.signal.aborted||V.current!==J)return;W(Ye),Ye.state==="connected"?(V.current=void 0,m(void 0),S("授权完成,连接已保存。"),F(nt=>nt+1)):Ye.state!=="pending"?(V.current=void 0,y(Ye.state==="cancelled"?"授权已取消。":"授权未完成或已过期,请重新开始。")):Ae=setTimeout(()=>{we()},2e3)}catch(Ye){if(ye.signal.aborted||V.current!==J)return;E(Ye),Ye instanceof We&&[401,404].includes(Ye.status)?(V.current=void 0,W(nt=>nt?{...nt,state:"failed"}:void 0)):Ae=setTimeout(()=>{we()},4e3)}};return Ae=setTimeout(()=>{we()},1e3),()=>{ye.abort(),clearTimeout(Ae)}},[R?.id,R?.state,E]);async function U(J,ye){if(G.current)return;const Ae=new AbortController;G.current=Ae,se.current?.abort(),_(!0),D(!1),y(""),S("");try{const we=await J(Ae.signal);A.current&&!Ae.signal.aborted&&ye(we)}catch(we){A.current&&!Ae.signal.aborted&&(E(we),we instanceof We&&we.status===409&&F(Ye=>Ye+1))}finally{G.current===Ae&&(G.current=void 0),A.current&&_(!1)}}function te(J,ye,Ae,we){return Ve(J,{method:ye,headers:{"Content-Type":"application/json"},body:JSON.stringify(Ae),signal:we})}function he(){return{providerId:o.provider.id,methodId:o.methodId,label:o.label.trim(),expectedRevision:o.original?.revision??null,...o.original?{connectionId:o.original.id}:{}}}function k(){m(void 0),ce(void 0),S("连接已保存。"),F(J=>J+1)}function T(J,ye){if(z||R?.state==="pending"||P&&!window.confirm("放弃当前未保存的连接修改?"))return;const Ae=J.connectionMethods.find(we=>we.id===ye?.methodId)??J.connectionMethods.find(we=>we.executionRuntime==="local"&&we.availability==="available");Ae&&(m({provider:J,original:ye,methodId:Ae.id,label:ye?.label??J.displayName,token:""}),ce(void 0),W(void 0),y(""),S(""))}async function K(){if(!V.current)return;const J=V.current;await U(ye=>Ve(J,{method:"DELETE",signal:ye}),()=>{V.current=void 0,W(void 0),S("授权已取消。")})}function C(J){const ye=o?.original?.id===J.id&&R?.state==="pending"?V.current:void 0,Ae=Rt(`${Ol}/connections/${encodeURIComponent(J.id)}`);U(async we=>{if(ye){try{await Ve(ye,{method:"DELETE",signal:we})}catch(Ye){if(!(Ye instanceof We&&Ye.status===404))throw Ye}A.current&&!we.aborted&&V.current===ye&&(V.current=void 0,W(void 0))}return te(Ae,"DELETE",{expectedRevision:J.revision},we)},()=>{o?.original?.id===J.id&&m(void 0),H(void 0),F(we=>we+1),S("连接已断开。")})}const re=o?.provider.connectionMethods.find(J=>J.id===o.methodId),ve=R?.state==="pending",Q=z||ve,pe=g.trim().toLowerCase(),je=(f?.providers??[]).filter(J=>`${J.displayName} ${J.description.zh}`.toLowerCase().includes(pe)),Y=o&&f?.connections.find(J=>o.original?J.id===o.original.id:J.id===`link-${o.provider.id}-${o.methodId}`&&J.providerId===o.provider.id&&J.methodId===o.methodId),xe=o&&f&&(o.original?Y?.revision!==o.original.revision:!!Y);return u.jsxs("section",{className:"hub-links",children:[u.jsxs("header",{className:"links-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{children:"Link"}),u.jsx("p",{children:"连接你的工具与账号,让任务访问已授权的服务。"})]}),u.jsx("button",{onClick:()=>{y(""),F(J=>J+1)},disabled:z||N,children:"刷新"})]}),u.jsxs("p",{className:"links-host",children:["连接由",r,"执行,凭据保存在",r,"。CLI 使用这台机器上已有的登录。"]}),b&&u.jsx("p",{className:"form-error",role:"alert",children:b}),v&&u.jsx("p",{className:"links-notice",role:"status",children:v}),N&&!f&&u.jsx("p",{role:"status",children:"正在加载连接…"}),u.jsx("h2",{children:"已连接"}),f&&f.connections.length===0&&u.jsx("p",{className:"links-muted",children:"还没有连接。选择下面的服务开始。"}),u.jsx("div",{className:"links-connections",children:f?.connections.map(J=>{const ye=f.providers.find(Ae=>Ae.id===J.providerId);return u.jsxs("article",{className:"links-connection",children:[u.jsxs("div",{children:[u.jsx("strong",{children:J.label}),u.jsxs("p",{children:[ye?.displayName??J.providerId," ·"," ",J.account?.label??J.account?.id??"已授权账号"]}),u.jsx("span",{className:`links-state ${J.status==="connected"?"ready":""}`,children:d0[J.status]}),u.jsxs("small",{children:[J.authSource==="cli-session"?"CLI 登录":J.authSource==="browser-oauth"?"浏览器授权":"Token",J.expiresAt?` · 到期 ${new Date(J.expiresAt).toLocaleString()}`:""]}),J.account?.resources.length?u.jsx("p",{children:J.account.resources.join("、")}):null]}),u.jsx("div",{className:"links-actions",children:J.editable?u.jsxs(u.Fragment,{children:[u.jsx("button",{disabled:Q||!ye,onClick:()=>ye&&T(ye,J),children:"管理连接"}),u.jsx("button",{disabled:z,onClick:()=>H(J),children:"断开"})]}):u.jsx("small",{children:"项目配置管理"})})]},J.id)})}),M&&u.jsxs("div",{className:"links-confirm",role:"alertdialog","aria-label":"断开连接",children:[u.jsxs("p",{children:["断开「",M.label,"」后,后续任务将无法使用这个连接,正在执行的请求会尝试停止。"]}),u.jsx("button",{disabled:z,onClick:()=>C(M),children:"确认断开"}),u.jsx("button",{disabled:z,onClick:()=>H(void 0),children:"取消"})]}),o&&re&&u.jsxs("section",{className:"links-editor","aria-label":`${o.provider.displayName} 连接设置`,children:[u.jsxs("div",{className:"links-heading",children:[u.jsxs("h2",{children:[o.provider.displayName," · ",o.original?"管理连接":"添加连接"]}),u.jsx("button",{disabled:Q,onClick:()=>{(!P||window.confirm("放弃未保存的连接修改?"))&&m(void 0)},children:"关闭"})]}),u.jsxs("label",{children:["连接名称",u.jsx("input",{maxLength:100,value:o.label,disabled:Q,onChange:J=>m({...o,label:J.target.value})})]}),xe&&u.jsxs("div",{className:"links-conflict",role:"alert",children:[u.jsx("p",{children:"这个连接已在其他设备创建、修改或删除。你的输入仍然保留,请先载入最新版本。"}),u.jsx("button",{disabled:Q,onClick:()=>m({...o,original:Y||void 0}),children:"载入最新版本,保留输入"})]}),re.browserAuth&&u.jsxs("div",{className:"links-auth-option",children:[u.jsx("h3",{children:"浏览器授权"}),o.provider.deviceAuth?.configured?u.jsx("button",{disabled:Q||!o.label.trim()||!!xe,onClick:()=>{const J=Jc()??"",ye=Us(),Ae=Rt(`${Ol}/authorizations/device`,J,ye);U(we=>te(Ae,"POST",he(),we),we=>{V.current=Rt(`${Ol}/authorizations/${encodeURIComponent(we.id)}`,J,ye),W(we)})},children:"开始授权"}):u.jsxs("p",{className:"links-muted",children:["这台",r,"尚未配置此服务的浏览器授权,可使用下面的连接方式。"]}),ve&&R.prompt&&u.jsxs("div",{className:"links-device-code",role:"status",children:[u.jsx("p",{children:"在服务商页面输入验证码:"}),u.jsx("strong",{children:R.prompt.userCode}),u.jsx("p",{children:Vi(R.prompt.verificationUriComplete??R.prompt.verificationUri)&&u.jsx("a",{href:Vi(R.prompt.verificationUriComplete??R.prompt.verificationUri),target:"_blank",rel:"noreferrer",children:"打开授权页面 ↗"})}),u.jsxs("p",{children:["完成后会自动保存。有效期至"," ",new Date(R.prompt.expiresAt).toLocaleTimeString(),"。"]}),u.jsx("button",{disabled:z,onClick:()=>{K()},children:"取消授权"})]})]}),re.quickAuth&&u.jsxs("div",{className:"links-auth-option",children:[u.jsx("h3",{children:"使用已登录的 CLI"}),u.jsxs("p",{children:[r,"需要已安装并登录 ",re.quickAuth.command,"。"]}),u.jsx("button",{disabled:Q,onClick:()=>{U(J=>Ve(`${Ol}/providers/${encodeURIComponent(o.provider.id)}/cli`,{signal:J}),ce)},children:"检查登录状态"}),oe&&u.jsx("p",{role:"status",children:oe.authenticated?`已登录${oe.account?`:${oe.account}`:""}`:oe.installed?"已安装,尚未登录。请在运行服务的机器上登录。":"尚未安装。"}),oe?.authenticated&&u.jsx("button",{disabled:Q||!o.label.trim()||!!xe,onClick:()=>{U(J=>te(`${Ol}/connections/cli`,"POST",he(),J),k)},children:"绑定这个登录"})]}),u.jsxs("form",{className:"links-auth-option",onSubmit:J=>{J.preventDefault(),!(Q||xe)&&U(ye=>o.original&&!o.token.trim()?te(`${Ol}/connections/${encodeURIComponent(o.original.id)}`,"PATCH",{label:o.label.trim(),expectedRevision:o.original.revision},ye):te(`${Ol}/connections/token`,"POST",{...he(),token:o.token.trim()},ye),k)},children:[u.jsx("h3",{children:o.original?"名称与 Token":"使用 Token"}),re.authGuide&&u.jsxs(u.Fragment,{children:[u.jsx("p",{children:re.authGuide.summary.zh}),u.jsxs("div",{className:"links-actions",children:[Vi(re.authGuide.createCredentialUrl)&&u.jsx("a",{href:Vi(re.authGuide.createCredentialUrl),target:"_blank",rel:"noreferrer",children:"创建凭据 ↗"}),Vi(re.authGuide.docsUrl)&&u.jsx("a",{href:Vi(re.authGuide.docsUrl),target:"_blank",rel:"noreferrer",children:"授权说明 ↗"})]}),u.jsxs("details",{children:[u.jsx("summary",{children:"所需权限与设置步骤"}),u.jsx("ul",{children:re.authGuide.permissions.map(J=>u.jsxs("li",{children:[J.label,"(",J.level==="required"?"必需":"可选",")",J.description?`:${J.description.zh}`:""]},J.id))}),u.jsx("ol",{children:re.authGuide.steps.map((J,ye)=>u.jsx("li",{children:J.zh},ye))})]})]}),u.jsxs("label",{children:[re.tokenLabel??o.provider.tokenLabel,u.jsx("input",{type:"password",autoComplete:"off",value:o.token,disabled:Q,placeholder:o.original?"留空保留当前授权,仅修改名称":re.tokenPlaceholder??o.provider.tokenPlaceholder,onChange:J=>m({...o,token:J.target.value}),required:!o.original,maxLength:16384})]}),u.jsx("button",{type:"submit",className:"send",disabled:Q||!!xe||!o.label.trim(),children:z?"正在验证并保存…":o.token.trim()||!o.original?"验证并保存":"保存名称"})]}),u.jsxs("details",{children:[u.jsxs("summary",{children:["可用操作(",o.provider.actions.length,")"]}),u.jsx("ul",{children:o.provider.actions.map(J=>u.jsxs("li",{children:[u.jsx("strong",{children:J.title}),J.risk==="write"?" · 执行前需要确认":"",u.jsx("p",{children:J.description})]},J.id))})]})]}),u.jsxs("div",{className:"links-heading",children:[u.jsx("h2",{children:"添加服务"}),u.jsx("input",{type:"search","aria-label":"搜索 Link 服务",placeholder:"搜索服务",value:g,onChange:J=>p(J.target.value)})]}),u.jsx("div",{className:"links-providers",children:je.map(J=>{const ye=f?.connections.find(Ae=>Ae.providerId===J.id);return u.jsxs("article",{className:"links-provider",children:[u.jsx("div",{className:`links-brand accent-${J.accent}`,"aria-hidden":"true",children:J.brandText}),u.jsx("h3",{children:J.displayName}),u.jsx("p",{children:J.description.zh}),u.jsxs("small",{children:[J.actions.length," 项操作"]}),u.jsx("button",{disabled:Q||!!(ye&&!ye.editable),onClick:()=>T(J,ye),children:ye?ye.editable?"管理连接":"项目配置管理":"添加连接"})]},J.id)})}),f&&je.length===0&&u.jsx("p",{className:"links-muted",children:"没有匹配的服务。"})]})}const Dm="/api/v1/panels",Om="https://github.com/cjhyy/codeshell-panel-apps.git",p0={"context.session":"读取当前对话信息","context.workspace":"读取当前工作区信息",storage:"保存面板自己的数据","external.open":"打开外部网页","agent.submitPrompt":"向当前对话提交任务","agent.task":"创建和管理 Agent 任务","workspace.info":"查看工作区信息","workspace.read":"读取工作区文件","workspace.write":"修改工作区文件","notifications.send":"发送通知","audio.transcribe":"将音频转成文字","credentials.cookies":"使用宿主授权的浏览器 Cookie","automations.manage":"管理自动化任务",process:"在宿主运行命令和进程",media:"处理宿主上的音视频文件","media.capture":"使用麦克风、摄像头或屏幕录制"};function sl(n){return n["zh-CN"]||n.default}function Mm({value:n}){return n.supported&&n.reasons.length===0?null:u.jsxs("div",{className:"panels-warning",children:[u.jsx("strong",{children:n.supported?"部分功能可用":"当前 Web 工作台暂不支持此面板"}),n.supported&&u.jsx("p",{children:"可以打开面板,以下功能当前不可用或需要额外配置。"}),n.reasons.length>0&&u.jsx("ul",{children:n.reasons.map(i=>u.jsx("li",{children:i},i))})]})}function m0({onAuthLost:n,onDirtyChange:i,onChanged:r,onOpen:s,hostLabel:f="服务端",configurationVersion:d=0}){const[o,m]=w.useState(),[g,p]=w.useState(""),[b,y]=w.useState(""),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(),[M,H]=w.useState(),[oe,ce]=w.useState(),[R,W]=w.useState(),[ie,F]=w.useState(!1),[A,G]=w.useState(!0),[V,se]=w.useState(!1),[ae,P]=w.useState(),[E,U]=w.useState(!0),[te,he]=w.useState(""),[k,T]=w.useState(""),[K,C]=w.useState(""),[re,ve]=w.useState(0),Q=w.useRef(!1),pe=w.useRef(void 0),je=w.useRef(void 0),Y=w.useRef(!1),xe=w.useRef(null),J=w.useRef({onAuthLost:n,onDirtyChange:i,onChanged:r,onOpen:s});J.current={onAuthLost:n,onDirtyChange:i,onChanged:r,onOpen:s};const ye=!!(te||M||R||ae||g.trim()||b.trim()||v.trim()),Ae=w.useCallback(B=>{B instanceof We&&B.status===401?J.current.onAuthLost():T(B instanceof Error?B.message:"面板操作失败,请重试。")},[]);w.useEffect(()=>(Q.current=!0,()=>{Q.current=!1,pe.current?.abort(),je.current?.abort(),J.current.onDirtyChange?.(!1)}),[]),w.useEffect(()=>{J.current.onDirtyChange?.(ye)},[ye]),w.useEffect(()=>{if(pe.current){Y.current=!0;return}const B=new AbortController;return je.current=B,U(!0),Ve(Rt(Dm),{signal:B.signal}).then(Se=>{B.signal.aborted||m(Se)}).catch(Se=>{B.signal.aborted||Ae(Se)}).finally(()=>{B.signal.aborted||U(!1)}),()=>B.abort()},[re,d,Ae]),w.useEffect(()=>{M&&xe.current?.focus()},[M?.reviewToken]);async function we(B,Se,Ke,lt,Be=!1){if(pe.current)return;const q=new AbortController;pe.current=q,je.current?.abort(),U(!1),he(B),T(""),C("");const ze=Rt(`${Dm}${Se}`);try{const St=await Ve(ze,{method:Ke,headers:{"Content-Type":"application/json"},body:JSON.stringify(lt),signal:q.signal});return q.signal.aborted||!Q.current?void 0:(Be&&(Y.current=!0,J.current.onChanged?.()),St)}catch(St){if(q.signal.aborted||!Q.current)return;St instanceof We&&(St.status===409||St.status===410)&&(M&&F(!0),Y.current=!0),Ae(St);return}finally{pe.current===q&&(pe.current=void 0),Q.current&&!q.signal.aborted&&(he(""),Y.current&&(Y.current=!1,ve(St=>St+1)))}}const Ye=async B=>{W(void 0),H(void 0),P(void 0),_(void 0);const Se=await we("正在读取仓库…","/github/discover","POST",{url:B.url,...B.ref?{ref:B.ref}:{},...B.subdir?{subdir:B.subdir}:{}});Se&&_(Se)},nt=async B=>{const Se=await we("正在准备安装审阅…","/preview","POST",{source:B});Se&&(P(void 0),ce(B),H(Se),F(!1),se(!1),G(!!o?.hasProject&&Se.compatibility.supported))},jt=async B=>{const Se=await we("正在检查更新…",`/${encodeURIComponent(B.id)}/update-preview`,"POST",{expectedRevision:B.revision});Se&&(P(void 0),ce(void 0),H(Se),F(!1),se(B.bound),G(B.bound&&Se.compatibility.supported))},Yt=()=>{if(M)if(M.kind==="update"){const B=o?.panels.find(Se=>Se.id===M.preview.id);B?jt(B):(T("此面板已被卸载,请重新从 GitHub 选择安装。"),H(void 0))}else oe&&nt(oe)},at=()=>{W(void 0),_(void 0),p(""),y(""),S("")},mt=async()=>{if(H(void 0),!R||R.position+1>=R.candidates.length){at();return}const B=R.position+1;W({...R,position:B}),await nt(R.candidates[B].source)},ut=async B=>{B.length&&(W({candidates:B,position:0}),await nt(B[0].source))},ot=async()=>{if(!M||ie)return;if(M.expiresAt<=Date.now()){F(!0),T("安装审阅已过期,请重新审阅后继续。");return}await we(M.kind==="update"?"正在更新面板…":"正在安装面板…","/install","POST",{reviewToken:M.reviewToken,bind:A},!0)&&(C(`${sl(M.preview.title)} 已${M.kind==="update"?"更新":"安装"}${A?"并绑定当前工作区":""}。`),H(void 0),R?await mt():at())},Gt=async B=>{const Se=await we(B.bound?"正在解除绑定…":"正在绑定工作区…",`/${encodeURIComponent(B.id)}/binding`,"PATCH",{bound:!B.bound,expectedRevision:B.revision},!0);Se&&(m(Se),C(`${sl(B.title)} 已${B.bound?"解除当前工作区绑定":"绑定当前工作区"}。`))},vt=async()=>{if(!ae||o?.panels.find(Se=>Se.id===ae.id)?.revision!==ae.revision)return;(await we("正在卸载面板…",`/${encodeURIComponent(ae.id)}`,"DELETE",{expectedRevision:ae.revision},!0))?.removed&&(C(`${sl(ae.title)} 已卸载。`),P(void 0))},qt=!!te||!o||!!R,ne=N.trim().toLowerCase(),me=(o?.panels??[]).filter(B=>[sl(B.title),B.id,B.description??"",B.source.label].join(" ").toLowerCase().includes(ne)),Te=z?.panels.filter(B=>!o?.panels.some(Se=>Se.id===B.id)&&z.panels.filter(Se=>Se.id===B.id).length===1)??[],ge=ae&&o?.panels.find(B=>B.id===ae.id),ke=!!ae&&ge?.revision!==ae.revision,Ce=M?.kind==="update"?o?.panels.find(B=>B.id===M.preview.id):void 0;return u.jsxs("section",{className:"hub-panels",children:[u.jsxs("header",{className:"panels-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{children:"面板"}),u.jsx("p",{children:"从 GitHub 安装工具面板,绑定工作区后直接在工作台中打开。"})]}),u.jsx("button",{disabled:!!te||E,onClick:()=>ve(B=>B+1),children:E?"正在刷新…":"刷新"})]}),u.jsxs("p",{className:"panels-muted",children:["面板安装在",f,"上,文件和任务操作使用当前工作区。"]}),o&&!o.hasProject&&u.jsx("div",{className:"panels-warning",children:"请先选择一个项目,才能绑定和打开面板。"}),k&&u.jsx("p",{role:"alert",className:"error",children:k}),K&&u.jsx("p",{role:"status",className:"panels-notice",children:K}),te&&u.jsx("p",{role:"status",className:"panels-muted",children:te}),R&&u.jsxs("section",{className:"panels-confirm","aria-label":"逐个审阅面板",children:[u.jsxs("p",{children:["正在审阅第 ",R.position+1," / ",R.candidates.length," 个面板:",sl(R.candidates[R.position].title),"。每个面板都需要单独确认安装。"]}),u.jsxs("div",{className:"panels-actions",children:[!M&&u.jsx("button",{disabled:!!te,onClick:()=>{nt(R.candidates[R.position].source)},children:"重新读取此面板"}),u.jsx("button",{disabled:!!te,onClick:()=>{mt()},children:"跳过此面板"}),u.jsx("button",{disabled:!!te,onClick:()=>{W(void 0),H(void 0),T("")},children:"取消逐个审阅"})]})]}),M&&u.jsxs("section",{className:"panels-review","aria-labelledby":"panel-review-heading",children:[u.jsxs("header",{className:"panels-heading",children:[u.jsxs("div",{children:[u.jsx("h2",{id:"panel-review-heading",ref:xe,tabIndex:-1,children:M.kind==="update"?"审阅面板更新":"审阅面板安装"}),u.jsxs("p",{children:[sl(M.preview.title)," · ",M.preview.id," · v",M.preview.version]})]}),u.jsx("button",{disabled:!!te,onClick:()=>{W(void 0),H(void 0),T("")},children:"取消审阅"})]}),M.preview.description&&u.jsx("p",{children:M.preview.description}),Ce&&u.jsxs("p",{className:"panels-warning",children:["当前版本 v",Ce.version," → 更新后 v",M.preview.version,Ce.source.commit&&u.jsxs(u.Fragment,{children:[u.jsx("br",{}),"当前提交 ",u.jsx("code",{children:Ce.source.commit.slice(0,12)})," → 更新提交"," ",u.jsx("code",{children:M.source.commit.slice(0,12)})]})]}),u.jsxs("section",{children:[u.jsx("h3",{children:"安装来源"}),u.jsxs("dl",{children:[u.jsx("dt",{children:"仓库"}),u.jsx("dd",{children:M.source.url}),u.jsx("dt",{children:"分支 / 标签"}),u.jsx("dd",{children:M.source.ref}),u.jsx("dt",{children:"已锁定提交"}),u.jsx("dd",{children:u.jsx("code",{children:M.source.commit})}),u.jsx("dt",{children:"面板目录"}),u.jsx("dd",{children:M.source.subdir||"仓库根目录"}),u.jsx("dt",{children:"界面入口"}),u.jsx("dd",{children:u.jsx("code",{children:M.preview.entry})})]})]}),u.jsxs("section",{children:[u.jsx("h3",{children:"面板请求的权限"}),M.preview.permissions.length===0?u.jsx("p",{className:"panels-muted",children:"未申请宿主权限。"}):M.preview.permissions.map(B=>u.jsxs("div",{className:"panels-permission",children:[u.jsx("span",{children:p0[B]??B}),u.jsx("small",{children:B})]},B))]}),u.jsxs("section",{children:[u.jsx("h3",{children:"随面板安装的工具与 Skills"}),M.preview.agent?.tools.length||M.preview.agent?.skills.length?u.jsxs("div",{className:"panels-badges",children:[M.preview.agent?.tools.map(B=>u.jsxs("span",{className:"panels-badge",title:B.description,children:[B.name," · ",B.readOnly?"只读":"可修改数据"]},B.name)),M.preview.agent?.skills.map(B=>u.jsxs("span",{className:"panels-badge",children:["Skill · ",B.split("/").at(-2)??B]},B))]}):u.jsx("p",{className:"panels-muted",children:"此面板没有额外的 Agent 工具或 Skills。"})]}),u.jsx(Mm,{value:M.compatibility}),M.preview.warnings.length>0&&u.jsx("div",{className:"panels-warning",children:u.jsx("ul",{children:M.preview.warnings.map(B=>u.jsx("li",{children:B},B))})}),u.jsxs("footer",{children:[!M.compatibility.supported&&u.jsxs("p",{className:"panels-muted",children:["可以安装到",f,",但当前 Web 工作台无法绑定或打开它。"]}),V?u.jsx("p",{className:"panels-muted",children:"已绑定当前工作区,更新将保留绑定。"}):u.jsxs("label",{className:"panels-check",children:[u.jsx("input",{type:"checkbox",checked:A,disabled:!!te||!o?.hasProject||!M.compatibility.supported,onChange:B=>G(B.target.checked)}),"绑定当前工作区"]}),ie?u.jsxs("div",{className:"panels-actions",children:[u.jsx("span",{className:"panels-muted",children:"安装内容或本地版本已变化,请重新审阅。"}),u.jsx("button",{disabled:!!te,onClick:Yt,children:"重新审阅"})]}):u.jsx("button",{className:"panels-primary",disabled:!!te,onClick:()=>{ot()},children:M.kind==="update"?"确认更新":"确认安装"})]})]}),u.jsxs("section",{className:"panels-section","aria-labelledby":"installed-panels-heading",children:[u.jsxs("div",{className:"panels-heading",children:[u.jsxs("h2",{id:"installed-panels-heading",children:["已安装面板",o?` · ${o.panels.length}`:""]}),u.jsx("input",{type:"search","aria-label":"搜索已安装面板",placeholder:"搜索已安装面板",value:N,onChange:B=>D(B.target.value)})]}),!o&&u.jsx("p",{className:"panels-muted",children:E?"正在读取面板…":"暂时无法读取面板,请刷新重试。"}),o&&me.length===0&&u.jsxs("div",{className:"panels-empty",children:[u.jsx("strong",{children:o.panels.length?"没有匹配的面板":"还没有安装面板"}),u.jsx("p",{className:"panels-muted",children:o.panels.length?"试试其他名称或清除搜索。":"在下方粘贴 GitHub 仓库地址,或浏览官方面板仓库。"})]}),u.jsx("div",{className:"panels-grid",children:me.map(B=>u.jsxs("article",{className:"panels-card",children:[u.jsxs("div",{className:"panels-card-heading",children:[u.jsx("h3",{children:sl(B.title)}),u.jsxs("span",{className:"panels-badge",children:["v",B.version]})]}),u.jsx("small",{children:B.id}),B.description&&u.jsx("p",{children:B.description}),u.jsx("div",{className:"panels-badges",children:u.jsx("span",{className:`panels-badge ${B.enabled&&B.compatibility.supported?"panels-badge-ready":""}`,children:B.globalDisabled?"已全局停用":B.bound?"已绑定当前工作区":"未绑定当前工作区"})}),u.jsxs("dl",{children:[u.jsx("dt",{children:"来源"}),u.jsx("dd",{children:B.source.label}),B.source.ref&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"分支 / 标签"}),u.jsx("dd",{children:B.source.ref})]})]}),u.jsx(Mm,{value:B.compatibility}),B.globalDisabled&&u.jsx("p",{className:"panels-muted",children:"请在宿主配置中启用此面板后使用。"}),u.jsxs("div",{className:"panels-actions",children:[u.jsx("button",{className:"panels-primary",disabled:qt||!B.enabled||!B.compatibility.supported,onClick:()=>J.current.onOpen(B),children:"打开面板"}),u.jsx("button",{disabled:qt||!o?.hasProject||!B.bound&&(B.globalDisabled||!B.compatibility.supported),onClick:()=>{Gt(B)},children:B.bound?"解除绑定":"绑定工作区"}),B.updatable&&u.jsx("button",{disabled:qt,onClick:()=>{jt(B)},children:"检查更新"}),u.jsx("button",{className:"panels-danger",disabled:qt,onClick:()=>{P(B),H(void 0),T(""),C("")},children:"卸载"})]})]},B.id))}),ae&&u.jsxs("section",{className:"panels-confirm","aria-label":"确认卸载面板",children:[u.jsxs("p",{children:["卸载「",sl(ae.title),"」v",ae.version,"?面板将从",f,"移除,其他工作区也将无法打开它。"]}),u.jsxs("div",{className:"panels-actions",children:[u.jsx("button",{disabled:!!te,onClick:()=>P(void 0),children:"取消卸载"}),ke&&u.jsx("span",{className:"panels-muted",children:ge?"面板已被其他设备修改,请查看最新版本后重新确认。":"此面板已被其他设备卸载。"}),ke&&ge&&u.jsx("button",{disabled:!!te||E,onClick:()=>{P(ge),T("")},children:"查看最新版本"}),u.jsx("button",{className:"panels-danger",disabled:!!te||E||ke,onClick:()=>{vt()},children:"确认卸载"})]})]})]}),u.jsxs("section",{className:"panels-import panels-section","aria-labelledby":"github-panels-heading",children:[u.jsxs("div",{className:"panels-heading",children:[u.jsxs("div",{children:[u.jsx("h2",{id:"github-panels-heading",children:"从 GitHub 安装"}),u.jsx("p",{children:"先读取仓库并选择面板,再查看安装内容和所需权限。"})]}),u.jsx("button",{disabled:qt,onClick:()=>{p(Om),y(""),S(""),Ye({url:Om})},children:"浏览官方仓库"})]}),u.jsxs("form",{onSubmit:B=>{B.preventDefault(),g.trim()&&Ye({url:g.trim(),...b.trim()?{ref:b.trim()}:{},...v.trim()?{subdir:v.trim()}:{}})},children:[u.jsxs("label",{children:["GitHub 仓库地址",u.jsx("input",{type:"url",placeholder:"https://github.com/owner/repository",value:g,required:!0,disabled:!!te||!!R,onChange:B=>{p(B.target.value),_(void 0)}})]}),u.jsxs("details",{children:[u.jsx("summary",{children:"指定分支或子目录"}),u.jsxs("div",{className:"panels-source-fields",children:[u.jsxs("label",{children:["分支 / 标签(可选)",u.jsx("input",{value:b,placeholder:"使用默认分支",disabled:!!te||!!R,onChange:B=>{y(B.target.value),_(void 0)}})]}),u.jsxs("label",{children:["子目录(可选)",u.jsx("input",{value:v,placeholder:"例如 apps/my-panel",disabled:!!te||!!R,onChange:B=>{S(B.target.value),_(void 0)}})]})]})]}),u.jsxs("div",{className:"panels-actions",children:[u.jsx("button",{type:"submit",disabled:qt||!g.trim(),children:"读取仓库"}),(g||b||v||z)&&u.jsx("button",{type:"button",disabled:!!te,onClick:()=>{at(),H(void 0)},children:"清除"})]})]}),z&&u.jsxs("div",{className:"panels-candidates",children:[u.jsxs("h3",{children:["找到 ",z.panels.length," 个面板"]}),u.jsxs("p",{className:"panels-muted",children:[z.source.url," · ",z.source.ref," ·"," ",u.jsx("code",{children:z.source.commit.slice(0,12)})]}),z.panels.length===0&&u.jsx("p",{className:"panels-muted",children:"仓库中没有找到可安装的面板。请检查地址和子目录。"}),Te.length>1&&u.jsxs("div",{className:"panels-actions panels-batch-start",children:[u.jsxs("button",{disabled:qt,onClick:()=>{ut(Te)},children:["逐个审阅未安装面板(",Te.length,")"]}),u.jsx("small",{children:"按顺序确认,可随时跳过或停止。"})]}),u.jsx("div",{className:"panels-grid",children:z.panels.map(B=>{const Se=o?.panels.find(Ke=>Ke.id===B.id);return u.jsxs("article",{className:"panels-card",children:[u.jsxs("div",{className:"panels-card-heading",children:[u.jsx("h3",{children:sl(B.title)}),u.jsxs("span",{className:"panels-badge",children:["v",B.version]})]}),B.description&&u.jsx("p",{children:B.description}),u.jsx("small",{children:B.subdir==="."?"仓库根目录":B.subdir}),u.jsx("div",{className:"panels-actions",children:u.jsx("button",{disabled:qt||!!(Se&&!Se.updatable),onClick:()=>Se?void jt(Se):void nt(B.source),children:Se?Se.updatable?"已安装 · 检查更新":"已从其他来源安装":"审阅安装"})})]},`${B.id}:${B.subdir}`)})}),z.issues.length>0&&u.jsxs("div",{className:"panels-warning",children:[u.jsx("strong",{children:"部分目录无法作为面板安装"}),u.jsx("ul",{children:z.issues.map(B=>u.jsxs("li",{children:[B.subdir,":",B.error]},B.subdir))})]})]})]})]})}function g0(n){const i=n.projectId===void 0?Us():n.projectId,r=`/api/v1/panels/runtime/${encodeURIComponent(n.instanceId)}`,s=new Set,f=new Set;let d=!1,o=n.expiresAt,m=o-6e4,g,p=0,b=0,y=0,v,S;const N=(A,G)=>{const V=setTimeout(()=>{s.delete(V),d||A()},Math.max(0,Math.min(G,2147483647)));return s.add(V),V},D=A=>{A!==void 0&&(clearTimeout(A),s.delete(A))},z=()=>{if(!d){d=!0;for(const A of s)clearTimeout(A);s.clear();for(const A of f)A.abort();f.clear()}},_=A=>{d||(z(),n.onTerminal(A))},M=()=>_(new Error("面板连接已到期,请重新打开继续使用。")),H=A=>A instanceof We&&[401,403,410].includes(A.status),oe=()=>{d||n.onStatus(p||b?"面板连接暂时中断,正在重试;当前内容会保留。":"")},ce=async(A,G="GET")=>{const V=new AbortController;f.add(V);const se=N(()=>V.abort(),8e3);try{return await Ve(Rt(`${r}${A}`,n.workspace,i),{method:G,...G==="POST"?{headers:{"Content-Type":"application/json"},body:"{}"}:{},signal:V.signal})}finally{D(se),f.delete(V)}},R=()=>{D(v),v=N(()=>{Date.now()>=o?M():R()},o-Date.now())},W=()=>{D(S),p<5&&(S=N(ie,m-Date.now()))};function ie(){if(!d){if(Date.now()>=o){M();return}g||p>=5||Date.now()<m||(g=(async()=>{try{const A=await ce("/renew","POST");if(d)return;if(!A||typeof A!="object"||!("expiresAt"in A)||typeof A.expiresAt!="number"||!Number.isFinite(A.expiresAt)||A.expiresAt<=Date.now()+6e4)throw new Error("面板续期响应无效。");o=A.expiresAt,m=o-6e4,p=0,R(),oe()}catch(A){if(d)return;if(H(A)){_(A);return}p++,m=Date.now()+Math.min(5e3*2**(p-1),3e4),oe()}finally{g=void 0,d||W()}})())}}async function F(){try{const A=await ce(`/events?after=${y}`);if(d)return;if(!A||typeof A!="object"||!("cursor"in A)||!("events"in A))throw new Error("面板事件响应无效。");if(!Number.isSafeInteger(A.cursor)||A.cursor<y||!Array.isArray(A.events)||A.events.length>2048)throw new Error("面板事件响应无效。");const G=[];let V=y;for(const se of A.events){if(!se||typeof se!="object"||!Number.isSafeInteger(se.id)||se.id<=V||se.id>A.cursor||typeof se.event!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,100}$/.test(se.event))throw new Error("面板事件响应无效。");V=se.id,G.push(se)}n.onEvents(G),y=A.cursor,b=0,oe()}catch(A){if(d)return;if(H(A)){_(A);return}b++,oe()}finally{d||N(()=>{F()},Math.min(1e3*2**b,5e3))}}return R(),W(),F(),{stop:z,refresh:ie}}const Zi="/api/v1/panels/runtime";function Hn(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function y0(n){try{if(typeof n!="string"||n.length>2048)return;const i=new URL(n);if(i.protocol==="https:"&&!i.username&&!i.password)return i.href}catch{}}function b0(n,i){const r=`${Zi}/${i}/directory/`;return typeof n=="string"&&n.startsWith(r)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n.slice(r.length))}function x0(n){if(typeof n!="string"||!/^\/api\/v1\/panel-assets\/[A-Za-z0-9_-]{20,128}\/[A-Za-z0-9_%./-]+$/.test(n))return!1;try{return n.split("/").slice(5).every(i=>{const r=decodeURIComponent(i);return!!r&&!r.startsWith(".")&&!/[\\/:\u0000-\u001f\u007f]/.test(r)})}catch{return!1}}function v0(n){return Hn(n)?typeof n.instanceId=="string"&&/^[A-Za-z0-9_-]{20,128}$/.test(n.instanceId)&&x0(n.src)&&typeof n.expiresAt=="number"&&Number.isFinite(n.expiresAt)&&Hn(n.context)&&Array.isArray(n.limitations)&&n.limitations.every(i=>typeof i=="string"):!1}function S0({panel:n,sessionId:i,busy:r,onClose:s,onAuthLost:f,onDirtyChange:d,onSubmitPrompt:o}){const m=w.useRef(null),[g,p]=w.useState(),[b,y]=w.useState(!0),[v,S]=w.useState(""),[N,D]=w.useState(""),[z,_]=w.useState(),[M,H]=w.useState(""),[oe,ce]=w.useState(""),[R,W]=w.useState(),[ie,F]=w.useState(!1),[A,G]=w.useState(0),V=w.useRef({onClose:s,onAuthLost:f,onDirtyChange:d,onSubmitPrompt:o,busy:r});V.current={onClose:s,onAuthLost:f,onDirtyChange:d,onSubmitPrompt:o,busy:r};const se=w.useRef(!1),ae=w.useRef(void 0),P=w.useRef(void 0),E=w.useRef(null);return w.useEffect(()=>{V.current.onDirtyChange?.(!!R||ie),R&&(E.current?.focus(),E.current?.scrollIntoView?.({block:"nearest"}))},[R,ie]),w.useEffect(()=>{const U=Jc()??"",te=Us(),he={grant:void 0},k=new AbortController,T=new Set,K=new Set;let C=!1,re;const ve=[],Q=[],pe=new Set,je=new Set;let Y,xe=!1,J=!1,ye=!1,Ae=!1;const we=()=>{const ge=m.current?.contentWindow;if(!(C||!he.grant||!ge||!Ae))for(const ke of ve.splice(0))ke.event==="tools.invoke"&&Hn(ke.payload)&&typeof ke.payload.requestId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(ke.payload.requestId)&&je.add(ke.payload.requestId),ge.postMessage({type:"codeshell-panel:event",instanceId:he.grant.instanceId,event:ke.event,payload:ke.payload},"*")},Ye=()=>{C||!ye||!Ae||!he.grant||(Y&&clearTimeout(Y),y(!1),we())},nt={loaded:()=>{ye=!0,Ye()}};P.current=nt,p(void 0),y(!0),S(""),D(""),_(void 0),H(""),ce(""),W(void 0),F(!1);const jt=ge=>{xe||(xe=!0,Ve(Rt(`${Zi}/${encodeURIComponent(ge.instanceId)}`,U,te),{method:"DELETE",keepalive:!0}).catch(()=>{}))},Yt=ge=>{C||(ge instanceof We&&ge.status===401&&!se.current&&(se.current=!0,V.current.onAuthLost()),S(ge instanceof Error?ge.message:"面板连接失败,请重新打开。"))},at=ge=>{if(C||!he.grant)return;const ke=he.grant;he.grant=void 0,re?.stop(),ae.current?.cancel(),Q.length=0,ve.length=0,jt(ke);for(const Ce of T)Ce.abort();Y&&clearTimeout(Y),p(void 0),_(void 0),y(!1),F(!1),H(""),Yt(ge)},mt=ge=>({...ge,...typeof ge.sessionId=="string"?{busy:V.current.busy}:{}}),ut=(ge,ke,Ce,B,Se)=>{C||!he.grant||ge!==m.current?.contentWindow||ge.postMessage({type:"codeshell-panel:response",instanceId:he.grant.instanceId,requestId:ke,...B?{error:B,...Se?.code?{code:Se.code}:{},...Se?.retryAfterMs!==void 0?{retryAfterMs:Se.retryAfterMs}:{}}:{result:Ce}},"*")},ot=()=>{if(C||!he.grant||ae.current||J)return;const ge=Q.shift();if(!ge)return;if(ge.expiresAt<=Date.now()){ot();return}let ke=!1;const Ce={effect:ge,cancel:()=>{ae.current===Ce&&(clearTimeout(B),ae.current=void 0,C||(W(void 0),ce(""),F(!1)))},finish:Se=>{if(C||!he.grant||ae.current!==Ce||ke)return;ke=!0,F(!0),ce("");const Ke=new AbortController;T.add(Ke);const lt=setTimeout(()=>Ke.abort(),8e3);Ve(Rt(`${Zi}/${he.grant.instanceId}/confirm`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({requestId:ge.requestId,allowed:Se}),signal:Ke.signal}).then(Be=>{if(!(C||ae.current!==Ce)){if(typeof Be.allowed!="boolean")throw new Error("确认响应无效。");Se&&Be.allowed===!1&&D("此确认已超时或被取消,操作未获准执行,请在面板中重新发起。"),!Se&&Be.allowed===!0&&D("该操作此前已获准执行,请在面板中查看进度或停止。"),Ce.cancel(),ot()}}).catch(Be=>{if(!(C||ae.current!==Ce)){if(Be instanceof We&&[401,403,410].includes(Be.status)){at(Be);return}if(Be instanceof We&&Be.status===409){Ce.cancel(),D("面板操作确认已失效,请在面板中重新发起。"),ot();return}ce("暂未收到确认结果。可以重试本次确认,或取消尚未执行的请求。")}}).finally(()=>{clearTimeout(lt),T.delete(Ke),ke=!1,!C&&ae.current===Ce&&F(!1)})}},B=setTimeout(()=>{Ce.cancel(),!C&&he.grant&&(D("面板操作确认已超时,请在面板中重新发起。"),ot())},ge.expiresAt-Date.now());ae.current=Ce,W(Ce),ce("")},Gt=ge=>{for(const ke of ge){if(ke.event!=="host.confirm"){ve.push(ke);continue}const Ce=ke.payload;if(!Hn(Ce)||typeof Ce.requestId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(Ce.requestId)||typeof Ce.title!="string"||Ce.title.length>500||typeof Ce.body!="string"||Ce.body.length>3e4)throw new Error("面板操作确认格式无效。");pe.has(Ce.requestId)||(pe.add(Ce.requestId),Q.push({effect:"host.confirm",requestId:Ce.requestId,title:Ce.title,body:Ce.body,expiresAt:Date.now()+5e4}))}if(ve.length>2048||Q.length>32){at(new Error("面板状态积压过多,请重新打开面板。"));return}ot(),we()},vt=ge=>new Promise(ke=>{if(ae.current||J){ke(!1);return}const Ce={effect:ge,finish:Se=>{ae.current===Ce&&(clearTimeout(B),ae.current=void 0,C||W(void 0),ke(Se),queueMicrotask(ot))},cancel:()=>Ce.finish(!1)},B=setTimeout(()=>Ce.finish(!1),55e3);ae.current=Ce,W(Ce)}),qt=async ge=>{const ke=m.current?.contentWindow,Ce=he.grant,B=ge.data;if(C||!ke||ge.source!==ke||ge.origin!=="null"||!Ce||!Hn(B)||B.instanceId!==Ce.instanceId)return;if(B.type==="codeshell-panel:ready"){Ae=!0,Ye();return}if(B.type==="codeshell-panel:tool-result"){if(typeof B.requestId!="string"||!je.has(B.requestId)||T.size>=32)return;let q;try{if(q=JSON.stringify({requestId:B.requestId,...typeof B.error=="string"?{error:B.error}:{result:B.result}}),new TextEncoder().encode(q).length>512*1024)return}catch{return}je.delete(B.requestId);const ze=new AbortController;T.add(ze);const St=setTimeout(()=>ze.abort(),8e3);try{await Ve(Rt(`${Zi}/${Ce.instanceId}/tool-results`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:q,signal:ze.signal})}catch(de){!C&&he.grant&&(de instanceof We&&[401,410].includes(de.status)?at(de):D("面板工具结果未能送达,请在对话中重新发起操作。"))}finally{clearTimeout(St),T.delete(ze)}return}if(B.type!=="codeshell-panel:call"||typeof B.requestId!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(B.requestId))return;const Se=B.requestId;if(K.has(Se)){ut(ke,Se,void 0,"此请求已经处理,请重新发起。");return}if(K.size>=8192||T.size>=32){ut(ke,Se,void 0,"面板请求过于频繁,请稍后重试。");return}if(K.add(Se),typeof B.method!="string"||!/^[A-Za-z][A-Za-z0-9.]{0,63}$/.test(B.method)){ut(ke,Se,void 0,"面板方法无效。");return}let Ke;try{if(Ke=JSON.stringify({method:B.method,params:B.params}),new TextEncoder().encode(Ke).length>3*1024*1024)throw new Error("too large")}catch{ut(ke,Se,void 0,"面板请求内容过大或格式无效。");return}const lt=new AbortController;let Be=!1;T.add(lt);try{const q=await Ve(Rt(`${Zi}/${Ce.instanceId}/call`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:Ke,signal:lt.signal});if(C||lt.signal.aborted)return;if(B.method==="context.get"&&(Ae=!0,Ye()),B.method==="external.open"){const ze=Hn(q)&&q.effect===B.method?y0(q.url):void 0;if(!ze)throw new Error("面板返回的外部链接无效。");if(!await vt({effect:"external.open",url:ze}))throw new Error("你取消了打开链接,或确认已超时。");ut(ke,Se,{opened:!0})}else if(B.method==="agent.submitPrompt"){if(!Hn(q)||q.effect!==B.method||typeof q.prompt!="string"||!q.prompt.trim()||q.prompt.length>2e4||q.sessionId!==i)throw new Error("面板任务与当前对话不匹配,请重新打开面板。");if(!await vt({effect:"agent.submitPrompt",prompt:q.prompt,sessionId:i}))throw new Error("你取消了发送任务,或确认已超时。");if(C||lt.signal.aborted)return;Be=!0,J=!0,F(!0);const ze=await V.current.onSubmitPrompt({prompt:q.prompt,sessionId:i});if(C||lt.signal.aborted)return;D("面板任务已提交到当前对话,可切换到对话查看进度。"),ut(ke,Se,ze)}else if(B.method==="filesystem.openDirectory"){if(_(void 0),!Hn(q)||q.effect!==B.method||typeof q.path!="string")throw new Error("面板目录信息无效。");if(q.url!==void 0&&!b0(q.url,Ce.instanceId))throw new Error("面板目录链接无效,请重新打开目录。");_({path:q.path,...typeof q.url=="string"?{url:Rt(q.url,U,te)}:{}}),ut(ke,Se,{opened:!1,path:q.path})}else if(B.method==="notifications.send"){if(!Hn(q)||q.effect!==B.method||typeof q.title!="string"||q.title.length>160||typeof q.body!="string"||q.body.length>2e3)throw new Error("面板通知格式无效。");D(`${q.title}${q.body?`:${q.body}`:""}`),ut(ke,Se,{sent:!0})}else ut(ke,Se,B.method==="context.get"&&Hn(q)?mt(q):q)}catch(q){!C&&!lt.signal.aborted&&(q instanceof We&&[401,410].includes(q.status)&&at(q),(B.method==="agent.submitPrompt"||B.method==="external.open")&&D(q instanceof Error?q.message:"面板操作未完成。"),ut(ke,Se,void 0,q instanceof Error?q.message:"面板请求失败。",q instanceof We?{code:q.code,retryAfterMs:q.retryAfterMs}:void 0))}finally{T.delete(lt),Be&&(J=!1,C||F(!1),ot())}},ne=ge=>{qt(ge)};window.addEventListener("message",ne);const me=()=>re?.refresh(),Te=()=>{document.visibilityState==="visible"&&me()};return window.addEventListener("focus",me),window.addEventListener("online",me),document.addEventListener("visibilitychange",Te),Ve(Rt(`${Zi}/prepare`,U,te),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:n.id,revision:n.revision,...i?{sessionId:i}:{},theme:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",locale:"zh-CN"}),signal:k.signal}).then(ge=>{if(!v0(ge))throw new Error("面板启动信息无效,请刷新面板列表后重试。");if(C||k.signal.aborted){jt(ge);return}if(ge.expiresAt<=Date.now())throw jt(ge),new Error("面板授权已过期,请重新打开。");he.grant=ge,p({...ge,src:Rt(ge.src,U,te)}),Y=setTimeout(()=>{at(new Error("面板未能完成加载,请重新打开。若仍无法加载,可检查面板文件或使用桌面客户端。"))},45e3),re=g0({instanceId:ge.instanceId,expiresAt:ge.expiresAt,workspace:U,projectId:te,onEvents:Gt,onTerminal:at,onStatus:H})}).catch(ge=>{!C&&!k.signal.aborted&&(y(!1),Yt(ge))}),()=>{C=!0,ae.current?.cancel(),window.removeEventListener("message",ne),window.removeEventListener("focus",me),window.removeEventListener("online",me),document.removeEventListener("visibilitychange",Te),re?.stop(),k.abort();for(const ge of T)ge.abort();Y&&clearTimeout(Y),he.grant&&jt(he.grant),V.current.onDirtyChange?.(!1),P.current===nt&&(P.current=void 0)}},[n.id,n.revision,i,A]),w.useEffect(()=>{!g||!m.current?.contentWindow||m.current.contentWindow.postMessage({type:"codeshell-panel:event",instanceId:g.instanceId,event:"context.changed",payload:{...g.context,...typeof g.context.sessionId=="string"?{busy:r}:{}}},"*")},[r,g]),u.jsxs("section",{className:"panel-host",children:[u.jsxs("header",{className:"panel-host-heading",children:[u.jsxs("div",{children:[u.jsx("h1",{children:n.title["zh-CN"]||n.title.default}),u.jsxs("p",{children:["v",n.version," · 运行于当前工作区"]})]}),u.jsx("button",{onClick:s,children:"返回面板"})]}),(g?.limitations??n.compatibility.reasons).length>0&&u.jsxs("details",{className:"panel-host-limitations",open:!0,children:[u.jsx("summary",{children:"部分功能可用"}),u.jsx("p",{children:"面板界面可以使用;以下功能尚未接入网页,使用时会显示具体限制。"}),u.jsx("ul",{children:(g?.limitations??n.compatibility.reasons).map(U=>u.jsx("li",{children:U},U))})]}),N&&u.jsx("p",{className:"panel-host-notice",role:"status",children:N}),z&&u.jsxs("div",{className:"panel-host-notice panel-host-directory",role:"status",children:[u.jsxs("p",{children:["文件保存在服务器目录:",z.path]}),z.url&&u.jsx("a",{href:z.url,target:"_blank",rel:"noopener noreferrer",children:"查看并下载文件"})]}),M&&u.jsx("p",{className:"panel-host-notice",role:"status",children:M}),v&&u.jsxs("div",{className:"panel-host-error",role:"alert",children:[u.jsx("p",{children:v}),u.jsx("button",{disabled:b,onClick:()=>G(U=>U+1),children:"重新打开面板"})]}),b&&u.jsx("p",{className:"panel-host-loading",role:"status",children:"正在打开面板…"}),R&&u.jsxs("section",{className:"panel-host-confirm",ref:E,tabIndex:-1,onKeyDown:U=>{U.key==="Escape"&&!ie&&(U.preventDefault(),R.finish(!1))},"aria-label":R.effect.effect==="external.open"?"确认打开外部链接":R.effect.effect==="host.confirm"?"确认面板操作":"确认发送面板任务",children:[u.jsx("h2",{children:R.effect.effect==="external.open"?"面板请求打开网页":R.effect.effect==="host.confirm"?R.effect.title:"面板请求向当前对话发送任务"}),R.effect.effect==="external.open"?u.jsx("p",{className:"panel-host-url",children:R.effect.url}):R.effect.effect==="host.confirm"?u.jsx("pre",{children:R.effect.body}):u.jsx("pre",{children:R.effect.prompt}),oe&&u.jsx("p",{role:"alert",children:oe}),u.jsxs("div",{className:"panel-host-actions",children:[u.jsx("button",{disabled:ie,onClick:()=>R.finish(!1),children:"取消"}),R.effect.effect==="external.open"?u.jsx("a",{href:R.effect.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>R.finish(!0),children:"确认打开网页"}):u.jsx("button",{className:"panel-host-primary",disabled:ie,onClick:()=>R.finish(!0),children:ie?"正在确认…":R.effect.effect==="host.confirm"?"确认执行":"确认发送任务"})]})]}),g&&u.jsx("iframe",{ref:m,src:g.src,title:`${n.title["zh-CN"]||n.title.default}面板`,sandbox:"allow-scripts",referrerPolicy:"no-referrer",inert:!!R||ie,onLoad:()=>P.current?.loaded(),allow:"camera 'none'; microphone 'none'; geolocation 'none'; display-capture 'none'; clipboard-read 'none'; clipboard-write 'none'",className:"panel-host-frame"})]})}function j0(n,i){const r={};return(n[n.length-1]===""?[...n,""]:n).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const k0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,w0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,C0={};function Lm(n,i){return(C0.jsx?w0:k0).test(n)}const E0=/[ \t\n\f\r]/g;function N0(n){return typeof n=="object"?n.type==="text"?Um(n.value):!1:Um(n)}function Um(n){return n.replace(E0,"")===""}class ia{constructor(i,r,s){this.normal=r,this.property=i,s&&(this.space=s)}}ia.prototype.normal={};ia.prototype.property={};ia.prototype.space=void 0;function Gg(n,i){const r={},s={};for(const f of n)Object.assign(r,f.property),Object.assign(s,f.normal);return new ia(r,s,i)}function Oc(n){return n.toLowerCase()}class cn{constructor(i,r){this.attribute=r,this.property=i}}cn.prototype.attribute="";cn.prototype.booleanish=!1;cn.prototype.boolean=!1;cn.prototype.commaOrSpaceSeparated=!1;cn.prototype.commaSeparated=!1;cn.prototype.defined=!1;cn.prototype.mustUseProperty=!1;cn.prototype.number=!1;cn.prototype.overloadedBoolean=!1;cn.prototype.property="";cn.prototype.spaceSeparated=!1;cn.prototype.space=void 0;let T0=0;const qe=ri(),Ut=ri(),Mc=ri(),be=ri(),bt=ri(),ni=ri(),bn=ri();function ri(){return 2**++T0}const Lc=Object.freeze(Object.defineProperty({__proto__:null,boolean:qe,booleanish:Ut,commaOrSpaceSeparated:bn,commaSeparated:ni,number:be,overloadedBoolean:Mc,spaceSeparated:bt},Symbol.toStringTag,{value:"Module"})),pc=Object.keys(Lc);class tf extends cn{constructor(i,r,s,f){let d=-1;if(super(i,r),Bm(this,"space",f),typeof s=="number")for(;++d<pc.length;){const o=pc[d];Bm(this,pc[d],(s&Lc[o])===Lc[o])}}}tf.prototype.defined=!0;function Bm(n,i,r){r&&(n[i]=r)}function Ji(n){const i={},r={};for(const[s,f]of Object.entries(n.properties)){const d=new tf(s,n.transform(n.attributes||{},s),f,n.space);n.mustUseProperty&&n.mustUseProperty.includes(s)&&(d.mustUseProperty=!0),i[s]=d,r[Oc(s)]=s,r[Oc(d.attribute)]=s}return new ia(i,r,n.space)}const Vg=Ji({properties:{ariaActiveDescendant:null,ariaAtomic:Ut,ariaAutoComplete:null,ariaBusy:Ut,ariaChecked:Ut,ariaColCount:be,ariaColIndex:be,ariaColSpan:be,ariaControls:bt,ariaCurrent:null,ariaDescribedBy:bt,ariaDetails:null,ariaDisabled:Ut,ariaDropEffect:bt,ariaErrorMessage:null,ariaExpanded:Ut,ariaFlowTo:bt,ariaGrabbed:Ut,ariaHasPopup:null,ariaHidden:Ut,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:bt,ariaLevel:be,ariaLive:null,ariaModal:Ut,ariaMultiLine:Ut,ariaMultiSelectable:Ut,ariaOrientation:null,ariaOwns:bt,ariaPlaceholder:null,ariaPosInSet:be,ariaPressed:Ut,ariaReadOnly:Ut,ariaRelevant:null,ariaRequired:Ut,ariaRoleDescription:bt,ariaRowCount:be,ariaRowIndex:be,ariaRowSpan:be,ariaSelected:Ut,ariaSetSize:be,ariaSort:null,ariaValueMax:be,ariaValueMin:be,ariaValueNow:be,ariaValueText:null,role:null},transform(n,i){return i==="role"?i:"aria-"+i.slice(4).toLowerCase()}});function Qg(n,i){return i in n?n[i]:i}function Xg(n,i){return Qg(n,i.toLowerCase())}const A0=Ji({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ni,acceptCharset:bt,accessKey:bt,action:null,allow:null,allowFullScreen:qe,allowPaymentRequest:qe,allowUserMedia:qe,alpha:qe,alt:null,as:null,async:qe,autoCapitalize:null,autoComplete:bt,autoFocus:qe,autoPlay:qe,blocking:bt,capture:null,charSet:null,checked:qe,cite:null,className:bt,closedBy:null,colorSpace:null,cols:be,colSpan:be,command:null,commandFor:null,content:null,contentEditable:Ut,controls:qe,controlsList:bt,coords:be|ni,crossOrigin:null,data:null,dateTime:null,decoding:null,default:qe,defer:qe,dir:null,dirName:null,disabled:qe,download:Mc,draggable:Ut,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:qe,formTarget:null,headers:bt,height:be,hidden:Mc,high:be,href:null,hrefLang:null,htmlFor:bt,httpEquiv:bt,id:null,imageSizes:null,imageSrcSet:null,inert:qe,inputMode:null,integrity:null,is:null,isMap:qe,itemId:null,itemProp:bt,itemRef:bt,itemScope:qe,itemType:bt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:qe,low:be,manifest:null,max:null,maxLength:be,media:null,method:null,min:null,minLength:be,multiple:qe,muted:qe,name:null,nonce:null,noModule:qe,noValidate:qe,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:qe,optimum:be,pattern:null,ping:bt,placeholder:null,playsInline:qe,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:qe,referrerPolicy:null,rel:bt,required:qe,reversed:qe,rows:be,rowSpan:be,sandbox:bt,scope:null,scoped:qe,seamless:qe,selected:qe,shadowRootClonable:qe,shadowRootCustomElementRegistry:qe,shadowRootDelegatesFocus:qe,shadowRootMode:null,shadowRootSerializable:qe,shape:null,size:be,sizes:null,slot:null,span:be,spellCheck:Ut,src:null,srcDoc:null,srcLang:null,srcSet:null,start:be,step:null,style:null,tabIndex:be,target:null,title:null,translate:null,type:null,typeMustMatch:qe,useMap:null,value:Ut,width:be,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:bt,axis:null,background:null,bgColor:null,border:be,borderColor:null,bottomMargin:be,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:qe,declare:qe,event:null,face:null,frame:null,frameBorder:null,hSpace:be,leftMargin:be,link:null,longDesc:null,lowSrc:null,marginHeight:be,marginWidth:be,noResize:qe,noHref:qe,noShade:qe,noWrap:qe,object:null,profile:null,prompt:null,rev:null,rightMargin:be,rules:null,scheme:null,scrolling:Ut,standby:null,summary:null,text:null,topMargin:be,valueType:null,version:null,vAlign:null,vLink:null,vSpace:be,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:qe,disablePictureInPicture:qe,disableRemotePlayback:qe,exportParts:ni,part:bt,prefix:null,property:null,results:be,security:null,unselectable:null},space:"html",transform:Xg}),z0=Ji({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",maskType:"mask-type",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:bn,accentHeight:be,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:be,amplitude:be,arabicForm:null,ascent:be,attributeName:null,attributeType:null,azimuth:be,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:be,by:null,calcMode:null,capHeight:be,className:bt,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:be,diffuseConstant:be,direction:null,display:null,dur:null,divisor:be,dominantBaseline:null,download:qe,dx:null,dy:null,edgeMode:null,editable:null,elevation:be,enableBackground:null,end:null,event:null,exponent:be,externalResourcesRequired:null,fill:null,fillOpacity:be,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:ni,g2:ni,glyphName:ni,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:be,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:be,horizOriginX:be,horizOriginY:be,id:null,ideographic:be,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:be,k:be,k1:be,k2:be,k3:be,k4:be,kernelMatrix:bn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:be,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:be,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:be,overlineThickness:be,paintOrder:null,panose1:null,path:null,pathLength:be,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:bt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:be,pointsAtY:be,pointsAtZ:be,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:bn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:bn,rev:bn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:bn,requiredFeatures:bn,requiredFonts:bn,requiredFormats:bn,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:be,specularExponent:be,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:be,strikethroughThickness:be,string:null,stroke:null,strokeDashArray:bn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:be,strokeOpacity:be,strokeWidth:null,style:null,surfaceScale:be,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:bn,tabIndex:be,tableValues:null,target:null,targetX:be,targetY:be,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:bn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:be,underlineThickness:be,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:be,values:null,vAlphabetic:be,vMathematical:be,vectorEffect:null,vHanging:be,vIdeographic:be,version:null,vertAdvY:be,vertOriginX:be,vertOriginY:be,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:be,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Qg}),Zg=Ji({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(n,i){return"xlink:"+i.slice(5).toLowerCase()}}),Kg=Ji({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Xg}),Fg=Ji({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(n,i){return"xml:"+i.slice(3).toLowerCase()}}),R0={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"},_0=/[A-Z]/g,qm=/-[a-z]/g,D0=/^data[-\w.:]+$/i;function O0(n,i){const r=Oc(i);let s=i,f=cn;if(r in n.normal)return n.property[n.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&D0.test(i)){if(i.charAt(4)==="-"){const d=i.slice(5).replace(qm,L0);s="data"+d.charAt(0).toUpperCase()+d.slice(1)}else{const d=i.slice(4);if(!qm.test(d)){let o=d.replace(_0,M0);o.charAt(0)!=="-"&&(o="-"+o),i="data"+o}}f=tf}return new f(s,i)}function M0(n){return"-"+n.toLowerCase()}function L0(n){return n.charAt(1).toUpperCase()}const U0=Gg([Vg,A0,Zg,Kg,Fg],"html"),nf=Gg([Vg,z0,Zg,Kg,Fg],"svg");function B0(n){return n.join(" ").trim()}var Qi={},mc,Hm;function q0(){if(Hm)return mc;Hm=1;var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,i=/\n/g,r=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,f=/^:\s*/,d=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,m=/^\s+|\s+$/g,g=`
21
21
  `,p="/",b="*",y="",v="comment",S="declaration";function N(z,_){if(typeof z!="string")throw new TypeError("First argument must be a string");if(!z)return[];_=_||{};var M=1,H=1;function oe(ae){var P=ae.match(i);P&&(M+=P.length);var E=ae.lastIndexOf(g);H=~E?ae.length-E:H+ae.length}function ce(){var ae={line:M,column:H};return function(P){return P.position=new R(ae),F(),P}}function R(ae){this.start=ae,this.end={line:M,column:H},this.source=_.source}R.prototype.content=z;function W(ae){var P=new Error(_.source+":"+M+":"+H+": "+ae);if(P.reason=ae,P.filename=_.source,P.line=M,P.column=H,P.source=z,!_.silent)throw P}function ie(ae){var P=ae.exec(z);if(P){var E=P[0];return oe(E),z=z.slice(E.length),P}}function F(){ie(r)}function A(ae){var P;for(ae=ae||[];P=G();)P!==!1&&ae.push(P);return ae}function G(){var ae=ce();if(!(p!=z.charAt(0)||b!=z.charAt(1))){for(var P=2;y!=z.charAt(P)&&(b!=z.charAt(P)||p!=z.charAt(P+1));)++P;if(P+=2,y===z.charAt(P-1))return W("End of comment missing");var E=z.slice(2,P-2);return H+=2,oe(E),z=z.slice(P),H+=2,ae({type:v,comment:E})}}function V(){var ae=ce(),P=ie(s);if(P){if(G(),!ie(f))return W("property missing ':'");var E=ie(d),U=ae({type:S,property:D(P[0].replace(n,y)),value:E?D(E[0].replace(n,y)):y});return ie(o),U}}function se(){var ae=[];A(ae);for(var P;P=V();)P!==!1&&(ae.push(P),A(ae));return ae}return F(),se()}function D(z){return z?z.replace(m,y):y}return mc=N,mc}var Im;function H0(){if(Im)return Qi;Im=1;var n=Qi&&Qi.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qi,"__esModule",{value:!0}),Qi.default=r;const i=n(q0());function r(s,f){let d=null;if(!s||typeof s!="string")return d;const o=(0,i.default)(s),m=typeof f=="function";return o.forEach(g=>{if(g.type!=="declaration")return;const{property:p,value:b}=g;m?f(p,b,g):b&&(d=d||{},d[p]=b)}),d}return Qi}var Vr={},Ym;function I0(){if(Ym)return Vr;Ym=1,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.camelCase=void 0;var n=/^--[a-zA-Z0-9_-]+$/,i=/-([a-z])/g,r=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,f=/^-(ms)-/,d=function(p){return!p||r.test(p)||n.test(p)},o=function(p,b){return b.toUpperCase()},m=function(p,b){return"".concat(b,"-")},g=function(p,b){return b===void 0&&(b={}),d(p)?p:(p=p.toLowerCase(),b.reactCompat?p=p.replace(f,m):p=p.replace(s,m),p.replace(i,o))};return Vr.camelCase=g,Vr}var Qr,Gm;function Y0(){if(Gm)return Qr;Gm=1;var n=Qr&&Qr.__importDefault||function(f){return f&&f.__esModule?f:{default:f}},i=n(H0()),r=I0();function s(f,d){var o={};return!f||typeof f!="string"||(0,i.default)(f,function(m,g){m&&g&&(o[(0,r.camelCase)(m,d)]=g)}),o}return s.default=s,Qr=s,Qr}var G0=Y0();const V0=Fc(G0),$g=Jg("end"),lf=Jg("start");function Jg(n){return i;function i(r){const s=r&&r.position&&r.position[n]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function Q0(n){const i=lf(n),r=$g(n);if(i&&r)return{start:i,end:r}}function $r(n){return!n||typeof n!="object"?"":"position"in n||"type"in n?Vm(n.position):"start"in n||"end"in n?Vm(n):"line"in n||"column"in n?Uc(n):""}function Uc(n){return Qm(n&&n.line)+":"+Qm(n&&n.column)}function Vm(n){return Uc(n&&n.start)+"-"+Uc(n&&n.end)}function Qm(n){return n&&typeof n=="number"?n:1}class Pt extends Error{constructor(i,r,s){super(),typeof r=="string"&&(s=r,r=void 0);let f="",d={},o=!1;if(r&&("line"in r&&"column"in r?d={place:r}:"start"in r&&"end"in r?d={place:r}:"type"in r?d={ancestors:[r],place:r.position}:d={...r}),typeof i=="string"?f=i:!d.cause&&i&&(o=!0,f=i.message,d.cause=i),!d.ruleId&&!d.source&&typeof s=="string"){const g=s.indexOf(":");g===-1?d.ruleId=s:(d.source=s.slice(0,g),d.ruleId=s.slice(g+1))}if(!d.place&&d.ancestors&&d.ancestors){const g=d.ancestors[d.ancestors.length-1];g&&(d.place=g.position)}const m=d.place&&"start"in d.place?d.place.start:d.place;this.ancestors=d.ancestors||void 0,this.cause=d.cause||void 0,this.column=m?m.column:void 0,this.fatal=void 0,this.file="",this.message=f,this.line=m?m.line:void 0,this.name=$r(d.place)||"1:1",this.place=d.place||void 0,this.reason=this.message,this.ruleId=d.ruleId||void 0,this.source=d.source||void 0,this.stack=o&&d.cause&&typeof d.cause.stack=="string"?d.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Pt.prototype.file="";Pt.prototype.name="";Pt.prototype.reason="";Pt.prototype.message="";Pt.prototype.stack="";Pt.prototype.column=void 0;Pt.prototype.line=void 0;Pt.prototype.ancestors=void 0;Pt.prototype.cause=void 0;Pt.prototype.fatal=void 0;Pt.prototype.place=void 0;Pt.prototype.ruleId=void 0;Pt.prototype.source=void 0;const rf={}.hasOwnProperty,X0=new Map,Z0=/[A-Z]/g,K0=new Set(["table","tbody","thead","tfoot","tr"]),F0=new Set(["td","th"]),Pg="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function $0(n,i){if(!i||i.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=i.filePath||void 0;let s;if(i.development){if(typeof i.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=i1(r,i.jsxDEV)}else{if(typeof i.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof i.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=l1(r,i.jsx,i.jsxs)}const f={Fragment:i.Fragment,ancestors:[],components:i.components||{},create:s,elementAttributeNameCase:i.elementAttributeNameCase||"react",evaluater:i.createEvaluater?i.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:i.ignoreInvalidStyle||!1,passKeys:i.passKeys!==!1,passNode:i.passNode||!1,schema:i.space==="svg"?nf:U0,stylePropertyNameCase:i.stylePropertyNameCase||"dom",tableCellAlignToStyle:i.tableCellAlignToStyle!==!1},d=Wg(f,n,void 0);return d&&typeof d!="string"?d:f.create(n,f.Fragment,{children:d||void 0},void 0)}function Wg(n,i,r){if(i.type==="element")return J0(n,i,r);if(i.type==="mdxFlowExpression"||i.type==="mdxTextExpression")return P0(n,i);if(i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement")return e1(n,i,r);if(i.type==="mdxjsEsm")return W0(n,i);if(i.type==="root")return t1(n,i,r);if(i.type==="text")return n1(n,i)}function J0(n,i,r){const s=n.schema;let f=s;i.tagName.toLowerCase()==="svg"&&s.space==="html"&&(f=nf,n.schema=f),n.ancestors.push(i);const d=ty(n,i.tagName,!1),o=r1(n,i);let m=sf(n,i);return K0.has(i.tagName)&&(m=m.filter(function(g){return typeof g=="string"?!N0(g):!0})),ey(n,o,d,i),af(o,m),n.ancestors.pop(),n.schema=s,n.create(i,d,o,r)}function P0(n,i){if(i.data&&i.data.estree&&n.evaluater){const s=i.data.estree.body[0];return s.type,n.evaluater.evaluateExpression(s.expression)}ea(n,i.position)}function W0(n,i){if(i.data&&i.data.estree&&n.evaluater)return n.evaluater.evaluateProgram(i.data.estree);ea(n,i.position)}function e1(n,i,r){const s=n.schema;let f=s;i.name==="svg"&&s.space==="html"&&(f=nf,n.schema=f),n.ancestors.push(i);const d=i.name===null?n.Fragment:ty(n,i.name,!0),o=a1(n,i),m=sf(n,i);return ey(n,o,d,i),af(o,m),n.ancestors.pop(),n.schema=s,n.create(i,d,o,r)}function t1(n,i,r){const s={};return af(s,sf(n,i)),n.create(i,n.Fragment,s,r)}function n1(n,i){return i.value}function ey(n,i,r,s){typeof r!="string"&&r!==n.Fragment&&n.passNode&&(i.node=s)}function af(n,i){if(i.length>0){const r=i.length>1?i:i[0];r&&(n.children=r)}}function l1(n,i,r){return s;function s(f,d,o,m){const p=Array.isArray(o.children)?r:i;return m?p(d,o,m):p(d,o)}}function i1(n,i){return r;function r(s,f,d,o){const m=Array.isArray(d.children),g=lf(s);return i(f,d,o,m,{columnNumber:g?g.column-1:void 0,fileName:n,lineNumber:g?g.line:void 0},void 0)}}function r1(n,i){const r={};let s,f;for(f in i.properties)if(f!=="children"&&rf.call(i.properties,f)){const d=s1(n,f,i.properties[f]);if(d){const[o,m]=d;n.tableCellAlignToStyle&&o==="align"&&typeof m=="string"&&F0.has(i.tagName)?s=m:r[o]=m}}if(s){const d=r.style||(r.style={});d[n.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return r}function a1(n,i){const r={};for(const s of i.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&n.evaluater){const d=s.data.estree.body[0];d.type;const o=d.expression;o.type;const m=o.properties[0];m.type,Object.assign(r,n.evaluater.evaluateExpression(m.argument))}else ea(n,i.position);else{const f=s.name;let d;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&n.evaluater){const m=s.value.data.estree.body[0];m.type,d=n.evaluater.evaluateExpression(m.expression)}else ea(n,i.position);else d=s.value===null?!0:s.value;r[f]=d}return r}function sf(n,i){const r=[];let s=-1;const f=n.passKeys?new Map:X0;for(;++s<i.children.length;){const d=i.children[s];let o;if(n.passKeys){const g=d.type==="element"?d.tagName:d.type==="mdxJsxFlowElement"||d.type==="mdxJsxTextElement"?d.name:void 0;if(g){const p=f.get(g)||0;o=g+"-"+p,f.set(g,p+1)}}const m=Wg(n,d,o);m!==void 0&&r.push(m)}return r}function s1(n,i,r){const s=O0(n.schema,i);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=s.commaSeparated?j0(r):B0(r)),s.property==="style"){let f=typeof r=="object"?r:u1(n,String(r));return n.stylePropertyNameCase==="css"&&(f=o1(f)),["style",f]}return[n.elementAttributeNameCase==="react"&&s.space?R0[s.property]||s.property:s.attribute,r]}}function u1(n,i){try{return V0(i,{reactCompat:!0})}catch(r){if(n.ignoreInvalidStyle)return{};const s=r,f=new Pt("Cannot parse `style` attribute",{ancestors:n.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw f.file=n.filePath||void 0,f.url=Pg+"#cannot-parse-style-attribute",f}}function ty(n,i,r){let s;if(!r)s={type:"Literal",value:i};else if(i.includes(".")){const f=i.split(".");let d=-1,o;for(;++d<f.length;){const m=Lm(f[d])?{type:"Identifier",name:f[d]}:{type:"Literal",value:f[d]};o=o?{type:"MemberExpression",object:o,property:m,computed:!!(d&&m.type==="Literal"),optional:!1}:m}s=o}else s=Lm(i)&&!/^[a-z]/.test(i)?{type:"Identifier",name:i}:{type:"Literal",value:i};if(s.type==="Literal"){const f=s.value;return rf.call(n.components,f)?n.components[f]:f}if(n.evaluater)return n.evaluater.evaluateExpression(s);ea(n)}function ea(n,i){const r=new Pt("Cannot handle MDX estrees without `createEvaluater`",{ancestors:n.ancestors,place:i,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=n.filePath||void 0,r.url=Pg+"#cannot-handle-mdx-estrees-without-createevaluater",r}function o1(n){const i={};let r;for(r in n)rf.call(n,r)&&(i[c1(r)]=n[r]);return i}function c1(n){let i=n.replace(Z0,f1);return i.slice(0,3)==="ms-"&&(i="-"+i),i}function f1(n){return"-"+n.toLowerCase()}const gc={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"]},d1={};function uf(n,i){const r=d1,s=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,f=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return ny(n,s,f)}function ny(n,i,r){if(h1(n)){if("value"in n)return n.type==="html"&&!r?"":n.value;if(i&&"alt"in n&&n.alt)return n.alt;if("children"in n)return Xm(n.children,i,r)}return Array.isArray(n)?Xm(n,i,r):""}function Xm(n,i,r){const s=[];let f=-1;for(;++f<n.length;)s[f]=ny(n[f],i,r);return s.join("")}function h1(n){return!!(n&&typeof n=="object")}const Zm=document.createElement("i");function of(n){const i="&"+n+";";Zm.innerHTML=i;const r=Zm.textContent;return r.charCodeAt(r.length-1)===59&&n!=="semi"||r===i?!1:r}function xn(n,i,r,s){const f=n.length;let d=0,o;if(i<0?i=-i>f?0:f+i:i=i>f?f:i,r=r>0?r:0,s.length<1e4)o=Array.from(s),o.unshift(i,r),n.splice(...o);else for(r&&n.splice(i,r);d<s.length;)o=s.slice(d,d+1e4),o.unshift(i,0),n.splice(...o),d+=1e4,i+=1e4}function zn(n,i){return n.length>0?(xn(n,n.length,0,i),n):i}const Km={}.hasOwnProperty;function ly(n){const i={};let r=-1;for(;++r<n.length;)p1(i,n[r]);return i}function p1(n,i){let r;for(r in i){const f=(Km.call(n,r)?n[r]:void 0)||(n[r]={}),d=i[r];let o;if(d)for(o in d){Km.call(f,o)||(f[o]=[]);const m=d[o];m1(f[o],Array.isArray(m)?m:m?[m]:[])}}}function m1(n,i){let r=-1;const s=[];for(;++r<i.length;)(i[r].add==="after"?n:s).push(i[r]);xn(n,0,0,s)}function iy(n,i){const r=Number.parseInt(n,i);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Mn(n){return n.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const en=Ul(/[A-Za-z]/),Jt=Ul(/[\dA-Za-z]/),g1=Ul(/[#-'*+\--9=?A-Z^-~]/);function zs(n){return n!==null&&(n<32||n===127)}const Bc=Ul(/\d/),y1=Ul(/[\dA-Fa-f]/),b1=Ul(/[!-/:-@[-`{-~]/);function Me(n){return n!==null&&n<-2}function xt(n){return n!==null&&(n<0||n===32)}function Ze(n){return n===-2||n===-1||n===32}const qs=Ul(new RegExp("\\p{P}|\\p{S}","u")),li=Ul(/\s/);function Ul(n){return i;function i(r){return r!==null&&r>-1&&n.test(String.fromCharCode(r))}}function Pi(n){const i=[];let r=-1,s=0,f=0;for(;++r<n.length;){const d=n.charCodeAt(r);let o="";if(d===37&&Jt(n.charCodeAt(r+1))&&Jt(n.charCodeAt(r+2)))f=2;else if(d<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(d))||(o=String.fromCharCode(d));else if(d>55295&&d<57344){const m=n.charCodeAt(r+1);d<56320&&m>56319&&m<57344?(o=String.fromCharCode(d,m),f=1):o="�"}else o=String.fromCharCode(d);o&&(i.push(n.slice(s,r),encodeURIComponent(o)),s=r+f+1,o=""),f&&(r+=f,f=0)}return i.join("")+n.slice(s)}function tt(n,i,r,s){const f=s?s-1:Number.POSITIVE_INFINITY;let d=0;return o;function o(g){return Ze(g)?(n.enter(r),m(g)):i(g)}function m(g){return Ze(g)&&d++<f?(n.consume(g),m):(n.exit(r),i(g))}}const x1={tokenize:v1};function v1(n){const i=n.attempt(this.parser.constructs.contentInitial,s,f);let r;return i;function s(m){if(m===null){n.consume(m);return}return n.enter("lineEnding"),n.consume(m),n.exit("lineEnding"),tt(n,i,"linePrefix")}function f(m){return n.enter("paragraph"),d(m)}function d(m){const g=n.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=g),r=g,o(m)}function o(m){if(m===null){n.exit("chunkText"),n.exit("paragraph"),n.consume(m);return}return Me(m)?(n.consume(m),n.exit("chunkText"),d):(n.consume(m),o)}}const S1={tokenize:j1},Fm={tokenize:k1};function j1(n){const i=this,r=[];let s=0,f,d,o;return m;function m(H){if(s<r.length){const oe=r[s];return i.containerState=oe[1],n.attempt(oe[0].continuation,g,p)(H)}return p(H)}function g(H){if(s++,i.containerState._closeFlow){i.containerState._closeFlow=void 0,f&&M();const oe=i.events.length;let ce=oe,R;for(;ce--;)if(i.events[ce][0]==="exit"&&i.events[ce][1].type==="chunkFlow"){R=i.events[ce][1].end;break}_(s);let W=oe;for(;W<i.events.length;)i.events[W][1].end={...R},W++;return xn(i.events,ce+1,0,i.events.slice(oe)),i.events.length=W,p(H)}return m(H)}function p(H){if(s===r.length){if(!f)return v(H);if(f.currentConstruct&&f.currentConstruct.concrete)return N(H);i.interrupt=!!(f.currentConstruct&&!f._gfmTableDynamicInterruptHack)}return i.containerState={},n.check(Fm,b,y)(H)}function b(H){return f&&M(),_(s),v(H)}function y(H){return i.parser.lazy[i.now().line]=s!==r.length,o=i.now().offset,N(H)}function v(H){return i.containerState={},n.attempt(Fm,S,N)(H)}function S(H){return s++,r.push([i.currentConstruct,i.containerState]),v(H)}function N(H){if(H===null){f&&M(),_(0),n.consume(H);return}return f=f||i.parser.flow(i.now()),n.enter("chunkFlow",{_tokenizer:f,contentType:"flow",previous:d}),D(H)}function D(H){if(H===null){z(n.exit("chunkFlow"),!0),_(0),n.consume(H);return}return Me(H)?(n.consume(H),z(n.exit("chunkFlow")),s=0,i.interrupt=void 0,m):(n.consume(H),D)}function z(H,oe){const ce=i.sliceStream(H);if(oe&&ce.push(null),H.previous=d,d&&(d.next=H),d=H,f.defineSkip(H.start),f.write(ce),i.parser.lazy[H.start.line]){let R=f.events.length;for(;R--;)if(f.events[R][1].start.offset<o&&(!f.events[R][1].end||f.events[R][1].end.offset>o))return;const W=i.events.length;let ie=W,F,A;for(;ie--;)if(i.events[ie][0]==="exit"&&i.events[ie][1].type==="chunkFlow"){if(F){A=i.events[ie][1].end;break}F=!0}for(_(s),R=W;R<i.events.length;)i.events[R][1].end={...A},R++;xn(i.events,ie+1,0,i.events.slice(W)),i.events.length=R}}function _(H){let oe=r.length;for(;oe-- >H;){const ce=r[oe];i.containerState=ce[1],ce[0].exit.call(i,n)}r.length=H}function M(){f.write([null]),d=void 0,f=void 0,i.containerState._closeFlow=void 0}}function k1(n,i,r){return tt(n,n.attempt(this.parser.constructs.document,i,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Fi(n){if(n===null||xt(n)||li(n))return 1;if(qs(n))return 2}function Hs(n,i,r){const s=[];let f=-1;for(;++f<n.length;){const d=n[f].resolveAll;d&&!s.includes(d)&&(i=d(i,r),s.push(d))}return i}const qc={name:"attention",resolveAll:w1,tokenize:C1};function w1(n,i){let r=-1,s,f,d,o,m,g,p,b;for(;++r<n.length;)if(n[r][0]==="enter"&&n[r][1].type==="attentionSequence"&&n[r][1]._close){for(s=r;s--;)if(n[s][0]==="exit"&&n[s][1].type==="attentionSequence"&&n[s][1]._open&&i.sliceSerialize(n[s][1]).charCodeAt(0)===i.sliceSerialize(n[r][1]).charCodeAt(0)){if((n[s][1]._close||n[r][1]._open)&&(n[r][1].end.offset-n[r][1].start.offset)%3&&!((n[s][1].end.offset-n[s][1].start.offset+n[r][1].end.offset-n[r][1].start.offset)%3))continue;g=n[s][1].end.offset-n[s][1].start.offset>1&&n[r][1].end.offset-n[r][1].start.offset>1?2:1;const y={...n[s][1].end},v={...n[r][1].start};$m(y,-g),$m(v,g),o={type:g>1?"strongSequence":"emphasisSequence",start:y,end:{...n[s][1].end}},m={type:g>1?"strongSequence":"emphasisSequence",start:{...n[r][1].start},end:v},d={type:g>1?"strongText":"emphasisText",start:{...n[s][1].end},end:{...n[r][1].start}},f={type:g>1?"strong":"emphasis",start:{...o.start},end:{...m.end}},n[s][1].end={...o.start},n[r][1].start={...m.end},p=[],n[s][1].end.offset-n[s][1].start.offset&&(p=zn(p,[["enter",n[s][1],i],["exit",n[s][1],i]])),p=zn(p,[["enter",f,i],["enter",o,i],["exit",o,i],["enter",d,i]]),p=zn(p,Hs(i.parser.constructs.insideSpan.null,n.slice(s+1,r),i)),p=zn(p,[["exit",d,i],["enter",m,i],["exit",m,i],["exit",f,i]]),n[r][1].end.offset-n[r][1].start.offset?(b=2,p=zn(p,[["enter",n[r][1],i],["exit",n[r][1],i]])):b=0,xn(n,s-1,r-s+3,p),r=s+p.length-b-2;break}}for(r=-1;++r<n.length;)n[r][1].type==="attentionSequence"&&(n[r][1].type="data");return n}function C1(n,i){const r=this.parser.constructs.attentionMarkers.null,s=this.previous,f=Fi(s);let d;return o;function o(g){return d=g,n.enter("attentionSequence"),m(g)}function m(g){if(g===d)return n.consume(g),m;const p=n.exit("attentionSequence"),b=Fi(g),y=!b||b===2&&f||r.includes(g),v=!f||f===2&&b||r.includes(s);return p._open=!!(d===42?y:y&&(f||!v)),p._close=!!(d===42?v:v&&(b||!y)),i(g)}}function $m(n,i){n.column+=i,n.offset+=i,n._bufferIndex+=i}const E1={name:"autolink",tokenize:N1};function N1(n,i,r){let s=0;return f;function f(S){return n.enter("autolink"),n.enter("autolinkMarker"),n.consume(S),n.exit("autolinkMarker"),n.enter("autolinkProtocol"),d}function d(S){return en(S)?(n.consume(S),o):S===64?r(S):p(S)}function o(S){return S===43||S===45||S===46||Jt(S)?(s=1,m(S)):p(S)}function m(S){return S===58?(n.consume(S),s=0,g):(S===43||S===45||S===46||Jt(S))&&s++<32?(n.consume(S),m):(s=0,p(S))}function g(S){return S===62?(n.exit("autolinkProtocol"),n.enter("autolinkMarker"),n.consume(S),n.exit("autolinkMarker"),n.exit("autolink"),i):S===null||S===32||S===60||zs(S)?r(S):(n.consume(S),g)}function p(S){return S===64?(n.consume(S),b):g1(S)?(n.consume(S),p):r(S)}function b(S){return Jt(S)?y(S):r(S)}function y(S){return S===46?(n.consume(S),s=0,b):S===62?(n.exit("autolinkProtocol").type="autolinkEmail",n.enter("autolinkMarker"),n.consume(S),n.exit("autolinkMarker"),n.exit("autolink"),i):v(S)}function v(S){if((S===45||Jt(S))&&s++<63){const N=S===45?v:y;return n.consume(S),N}return r(S)}}const ra={partial:!0,tokenize:T1};function T1(n,i,r){return s;function s(d){return Ze(d)?tt(n,f,"linePrefix")(d):f(d)}function f(d){return d===null||Me(d)?i(d):r(d)}}const ry={continuation:{tokenize:z1},exit:R1,name:"blockQuote",tokenize:A1};function A1(n,i,r){const s=this;return f;function f(o){if(o===62){const m=s.containerState;return m.open||(n.enter("blockQuote",{_container:!0}),m.open=!0),n.enter("blockQuotePrefix"),n.enter("blockQuoteMarker"),n.consume(o),n.exit("blockQuoteMarker"),d}return r(o)}function d(o){return Ze(o)?(n.enter("blockQuotePrefixWhitespace"),n.consume(o),n.exit("blockQuotePrefixWhitespace"),n.exit("blockQuotePrefix"),i):(n.exit("blockQuotePrefix"),i(o))}}function z1(n,i,r){const s=this;return f;function f(o){return Ze(o)?tt(n,d,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):d(o)}function d(o){return n.attempt(ry,i,r)(o)}}function R1(n){n.exit("blockQuote")}const ay={name:"characterEscape",tokenize:_1};function _1(n,i,r){return s;function s(d){return n.enter("characterEscape"),n.enter("escapeMarker"),n.consume(d),n.exit("escapeMarker"),f}function f(d){return b1(d)?(n.enter("characterEscapeValue"),n.consume(d),n.exit("characterEscapeValue"),n.exit("characterEscape"),i):r(d)}}const sy={name:"characterReference",tokenize:D1};function D1(n,i,r){const s=this;let f=0,d,o;return m;function m(y){return n.enter("characterReference"),n.enter("characterReferenceMarker"),n.consume(y),n.exit("characterReferenceMarker"),g}function g(y){return y===35?(n.enter("characterReferenceMarkerNumeric"),n.consume(y),n.exit("characterReferenceMarkerNumeric"),p):(n.enter("characterReferenceValue"),d=31,o=Jt,b(y))}function p(y){return y===88||y===120?(n.enter("characterReferenceMarkerHexadecimal"),n.consume(y),n.exit("characterReferenceMarkerHexadecimal"),n.enter("characterReferenceValue"),d=6,o=y1,b):(n.enter("characterReferenceValue"),d=7,o=Bc,b(y))}function b(y){if(y===59&&f){const v=n.exit("characterReferenceValue");return o===Jt&&!of(s.sliceSerialize(v))?r(y):(n.enter("characterReferenceMarker"),n.consume(y),n.exit("characterReferenceMarker"),n.exit("characterReference"),i)}return o(y)&&f++<d?(n.consume(y),b):r(y)}}const Jm={partial:!0,tokenize:M1},Pm={concrete:!0,name:"codeFenced",tokenize:O1};function O1(n,i,r){const s=this,f={partial:!0,tokenize:ce};let d=0,o=0,m;return g;function g(R){return p(R)}function p(R){const W=s.events[s.events.length-1];return d=W&&W[1].type==="linePrefix"?W[2].sliceSerialize(W[1],!0).length:0,m=R,n.enter("codeFenced"),n.enter("codeFencedFence"),n.enter("codeFencedFenceSequence"),b(R)}function b(R){return R===m?(o++,n.consume(R),b):o<3?r(R):(n.exit("codeFencedFenceSequence"),Ze(R)?tt(n,y,"whitespace")(R):y(R))}function y(R){return R===null||Me(R)?(n.exit("codeFencedFence"),s.interrupt?i(R):n.check(Jm,D,oe)(R)):(n.enter("codeFencedFenceInfo"),n.enter("chunkString",{contentType:"string"}),v(R))}function v(R){return R===null||Me(R)?(n.exit("chunkString"),n.exit("codeFencedFenceInfo"),y(R)):Ze(R)?(n.exit("chunkString"),n.exit("codeFencedFenceInfo"),tt(n,S,"whitespace")(R)):R===96&&R===m?r(R):(n.consume(R),v)}function S(R){return R===null||Me(R)?y(R):(n.enter("codeFencedFenceMeta"),n.enter("chunkString",{contentType:"string"}),N(R))}function N(R){return R===null||Me(R)?(n.exit("chunkString"),n.exit("codeFencedFenceMeta"),y(R)):R===96&&R===m?r(R):(n.consume(R),N)}function D(R){return n.attempt(f,oe,z)(R)}function z(R){return n.enter("lineEnding"),n.consume(R),n.exit("lineEnding"),_}function _(R){return d>0&&Ze(R)?tt(n,M,"linePrefix",d+1)(R):M(R)}function M(R){return R===null||Me(R)?n.check(Jm,D,oe)(R):(n.enter("codeFlowValue"),H(R))}function H(R){return R===null||Me(R)?(n.exit("codeFlowValue"),M(R)):(n.consume(R),H)}function oe(R){return n.exit("codeFenced"),i(R)}function ce(R,W,ie){let F=0;return A;function A(P){return R.enter("lineEnding"),R.consume(P),R.exit("lineEnding"),G}function G(P){return R.enter("codeFencedFence"),Ze(P)?tt(R,V,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):V(P)}function V(P){return P===m?(R.enter("codeFencedFenceSequence"),se(P)):ie(P)}function se(P){return P===m?(F++,R.consume(P),se):F>=o?(R.exit("codeFencedFenceSequence"),Ze(P)?tt(R,ae,"whitespace")(P):ae(P)):ie(P)}function ae(P){return P===null||Me(P)?(R.exit("codeFencedFence"),W(P)):ie(P)}}}function M1(n,i,r){const s=this;return f;function f(o){return o===null?r(o):(n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),d)}function d(o){return s.parser.lazy[s.now().line]?r(o):i(o)}}const yc={name:"codeIndented",tokenize:U1},L1={partial:!0,tokenize:B1};function U1(n,i,r){const s=this;return f;function f(p){return n.enter("codeIndented"),tt(n,d,"linePrefix",5)(p)}function d(p){const b=s.events[s.events.length-1];return b&&b[1].type==="linePrefix"&&b[2].sliceSerialize(b[1],!0).length>=4?o(p):r(p)}function o(p){return p===null?g(p):Me(p)?n.attempt(L1,o,g)(p):(n.enter("codeFlowValue"),m(p))}function m(p){return p===null||Me(p)?(n.exit("codeFlowValue"),o(p)):(n.consume(p),m)}function g(p){return n.exit("codeIndented"),i(p)}}function B1(n,i,r){const s=this;return f;function f(o){return s.parser.lazy[s.now().line]?r(o):Me(o)?(n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),f):tt(n,d,"linePrefix",5)(o)}function d(o){const m=s.events[s.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?i(o):Me(o)?f(o):r(o)}}const q1={name:"codeText",previous:I1,resolve:H1,tokenize:Y1};function H1(n){let i=n.length-4,r=3,s,f;if((n[r][1].type==="lineEnding"||n[r][1].type==="space")&&(n[i][1].type==="lineEnding"||n[i][1].type==="space")){for(s=r;++s<i;)if(n[s][1].type==="codeTextData"){n[r][1].type="codeTextPadding",n[i][1].type="codeTextPadding",r+=2,i-=2;break}}for(s=r-1,i++;++s<=i;)f===void 0?s!==i&&n[s][1].type!=="lineEnding"&&(f=s):(s===i||n[s][1].type==="lineEnding")&&(n[f][1].type="codeTextData",s!==f+2&&(n[f][1].end=n[s-1][1].end,n.splice(f+2,s-f-2),i-=s-f-2,s=f+2),f=void 0);return n}function I1(n){return n!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Y1(n,i,r){let s=0,f,d;return o;function o(y){return n.enter("codeText"),n.enter("codeTextSequence"),m(y)}function m(y){return y===96?(n.consume(y),s++,m):(n.exit("codeTextSequence"),g(y))}function g(y){return y===null?r(y):y===32?(n.enter("space"),n.consume(y),n.exit("space"),g):y===96?(d=n.enter("codeTextSequence"),f=0,b(y)):Me(y)?(n.enter("lineEnding"),n.consume(y),n.exit("lineEnding"),g):(n.enter("codeTextData"),p(y))}function p(y){return y===null||y===32||y===96||Me(y)?(n.exit("codeTextData"),g(y)):(n.consume(y),p)}function b(y){return y===96?(n.consume(y),f++,b):f===s?(n.exit("codeTextSequence"),n.exit("codeText"),i(y)):(d.type="codeTextData",p(y))}}class G1{constructor(i){this.left=i?[...i]:[],this.right=[]}get(i){if(i<0||i>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+i+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return i<this.left.length?this.left[i]:this.right[this.right.length-i+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(i,r){const s=r??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(i,s):i>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-i+this.left.length).reverse():this.left.slice(i).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(i,r,s){const f=r||0;this.setCursor(Math.trunc(i));const d=this.right.splice(this.right.length-f,Number.POSITIVE_INFINITY);return s&&Xr(this.left,s),d.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(i){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(i)}pushMany(i){this.setCursor(Number.POSITIVE_INFINITY),Xr(this.left,i)}unshift(i){this.setCursor(0),this.right.push(i)}unshiftMany(i){this.setCursor(0),Xr(this.right,i.reverse())}setCursor(i){if(!(i===this.left.length||i>this.left.length&&this.right.length===0||i<0&&this.left.length===0))if(i<this.left.length){const r=this.left.splice(i,Number.POSITIVE_INFINITY);Xr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-i,Number.POSITIVE_INFINITY);Xr(this.left,r.reverse())}}}function Xr(n,i){let r=0;if(i.length<1e4)n.push(...i);else for(;r<i.length;)n.push(...i.slice(r,r+1e4)),r+=1e4}function uy(n){const i={};let r=-1,s,f,d,o,m,g,p;const b=new G1(n);for(;++r<b.length;){for(;r in i;)r=i[r];if(s=b.get(r),r&&s[1].type==="chunkFlow"&&b.get(r-1)[1].type==="listItemPrefix"&&(g=s[1]._tokenizer.events,d=0,d<g.length&&g[d][1].type==="lineEndingBlank"&&(d+=2),d<g.length&&g[d][1].type==="content"))for(;++d<g.length&&g[d][1].type!=="content";)g[d][1].type==="chunkText"&&(g[d][1]._isInFirstContentOfListItem=!0,d++);if(s[0]==="enter")s[1].contentType&&(Object.assign(i,V1(b,r)),r=i[r],p=!0);else if(s[1]._container){for(d=r,f=void 0;d--;)if(o=b.get(d),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(f&&(b.get(f)[1].type="lineEndingBlank"),o[1].type="lineEnding",f=d);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;f&&(s[1].end={...b.get(f)[1].start},m=b.slice(f,r),m.unshift(s),b.splice(f,r-f+1,m))}}return xn(n,0,Number.POSITIVE_INFINITY,b.slice(0)),!p}function V1(n,i){const r=n.get(i)[1],s=n.get(i)[2];let f=i-1;const d=[];let o=r._tokenizer;o||(o=s.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const m=o.events,g=[],p={};let b,y,v=-1,S=r,N=0,D=0;const z=[D];for(;S;){for(;n.get(++f)[1]!==S;);d.push(f),S._tokenizer||(b=s.sliceStream(S),S.next||b.push(null),y&&o.defineSkip(S.start),S._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(b),S._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),y=S,S=S.next}for(S=r;++v<m.length;)m[v][0]==="exit"&&m[v-1][0]==="enter"&&m[v][1].type===m[v-1][1].type&&m[v][1].start.line!==m[v][1].end.line&&(D=v+1,z.push(D),S._tokenizer=void 0,S.previous=void 0,S=S.next);for(o.events=[],S?(S._tokenizer=void 0,S.previous=void 0):z.pop(),v=z.length;v--;){const _=m.slice(z[v],z[v+1]),M=d.pop();g.push([M,M+_.length-1]),n.splice(M,2,_)}for(g.reverse(),v=-1;++v<g.length;)p[N+g[v][0]]=N+g[v][1],N+=g[v][1]-g[v][0]-1;return p}const Q1={resolve:Z1,tokenize:K1},X1={partial:!0,tokenize:F1};function Z1(n){return uy(n),n}function K1(n,i){let r;return s;function s(m){return n.enter("content"),r=n.enter("chunkContent",{contentType:"content"}),f(m)}function f(m){return m===null?d(m):Me(m)?n.check(X1,o,d)(m):(n.consume(m),f)}function d(m){return n.exit("chunkContent"),n.exit("content"),i(m)}function o(m){return n.consume(m),n.exit("chunkContent"),r.next=n.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,f}}function F1(n,i,r){const s=this;return f;function f(o){return n.exit("chunkContent"),n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),tt(n,d,"linePrefix")}function d(o){if(o===null||Me(o))return r(o);const m=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?i(o):n.interrupt(s.parser.constructs.flow,r,i)(o)}}function oy(n,i,r,s,f,d,o,m,g){const p=g||Number.POSITIVE_INFINITY;let b=0;return y;function y(_){return _===60?(n.enter(s),n.enter(f),n.enter(d),n.consume(_),n.exit(d),v):_===null||_===32||_===41||zs(_)?r(_):(n.enter(s),n.enter(o),n.enter(m),n.enter("chunkString",{contentType:"string"}),D(_))}function v(_){return _===62?(n.enter(d),n.consume(_),n.exit(d),n.exit(f),n.exit(s),i):(n.enter(m),n.enter("chunkString",{contentType:"string"}),S(_))}function S(_){return _===62?(n.exit("chunkString"),n.exit(m),v(_)):_===null||_===60||Me(_)?r(_):(n.consume(_),_===92?N:S)}function N(_){return _===60||_===62||_===92?(n.consume(_),S):S(_)}function D(_){return!b&&(_===null||_===41||xt(_))?(n.exit("chunkString"),n.exit(m),n.exit(o),n.exit(s),i(_)):b<p&&_===40?(n.consume(_),b++,D):_===41?(n.consume(_),b--,D):_===null||_===32||_===40||zs(_)?r(_):(n.consume(_),_===92?z:D)}function z(_){return _===40||_===41||_===92?(n.consume(_),D):D(_)}}function cy(n,i,r,s,f,d){const o=this;let m=0,g;return p;function p(S){return n.enter(s),n.enter(f),n.consume(S),n.exit(f),n.enter(d),b}function b(S){return m>999||S===null||S===91||S===93&&!g||S===94&&!m&&"_hiddenFootnoteSupport"in o.parser.constructs?r(S):S===93?(n.exit(d),n.enter(f),n.consume(S),n.exit(f),n.exit(s),i):Me(S)?(n.enter("lineEnding"),n.consume(S),n.exit("lineEnding"),b):(n.enter("chunkString",{contentType:"string"}),y(S))}function y(S){return S===null||S===91||S===93||Me(S)||m++>999?(n.exit("chunkString"),b(S)):(n.consume(S),g||(g=!Ze(S)),S===92?v:y)}function v(S){return S===91||S===92||S===93?(n.consume(S),m++,y):y(S)}}function fy(n,i,r,s,f,d){let o;return m;function m(v){return v===34||v===39||v===40?(n.enter(s),n.enter(f),n.consume(v),n.exit(f),o=v===40?41:v,g):r(v)}function g(v){return v===o?(n.enter(f),n.consume(v),n.exit(f),n.exit(s),i):(n.enter(d),p(v))}function p(v){return v===o?(n.exit(d),g(o)):v===null?r(v):Me(v)?(n.enter("lineEnding"),n.consume(v),n.exit("lineEnding"),tt(n,p,"linePrefix")):(n.enter("chunkString",{contentType:"string"}),b(v))}function b(v){return v===o||v===null||Me(v)?(n.exit("chunkString"),p(v)):(n.consume(v),v===92?y:b)}function y(v){return v===o||v===92?(n.consume(v),b):b(v)}}function Jr(n,i){let r;return s;function s(f){return Me(f)?(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),r=!0,s):Ze(f)?tt(n,s,r?"linePrefix":"lineSuffix")(f):i(f)}}const $1={name:"definition",tokenize:P1},J1={partial:!0,tokenize:W1};function P1(n,i,r){const s=this;let f;return d;function d(S){return n.enter("definition"),o(S)}function o(S){return cy.call(s,n,m,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(S)}function m(S){return f=Mn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),S===58?(n.enter("definitionMarker"),n.consume(S),n.exit("definitionMarker"),g):r(S)}function g(S){return xt(S)?Jr(n,p)(S):p(S)}function p(S){return oy(n,b,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(S)}function b(S){return n.attempt(J1,y,y)(S)}function y(S){return Ze(S)?tt(n,v,"whitespace")(S):v(S)}function v(S){return S===null||Me(S)?(n.exit("definition"),s.parser.defined.push(f),i(S)):r(S)}}function W1(n,i,r){return s;function s(m){return xt(m)?Jr(n,f)(m):r(m)}function f(m){return fy(n,d,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(m)}function d(m){return Ze(m)?tt(n,o,"whitespace")(m):o(m)}function o(m){return m===null||Me(m)?i(m):r(m)}}const eS={name:"hardBreakEscape",tokenize:tS};function tS(n,i,r){return s;function s(d){return n.enter("hardBreakEscape"),n.consume(d),f}function f(d){return Me(d)?(n.exit("hardBreakEscape"),i(d)):r(d)}}const nS={name:"headingAtx",resolve:lS,tokenize:iS};function lS(n,i){let r=n.length-2,s=3,f,d;return n[s][1].type==="whitespace"&&(s+=2),r-2>s&&n[r][1].type==="whitespace"&&(r-=2),n[r][1].type==="atxHeadingSequence"&&(s===r-1||r-4>s&&n[r-2][1].type==="whitespace")&&(r-=s+1===r?2:4),r>s&&(f={type:"atxHeadingText",start:n[s][1].start,end:n[r][1].end},d={type:"chunkText",start:n[s][1].start,end:n[r][1].end,contentType:"text"},xn(n,s,r-s+1,[["enter",f,i],["enter",d,i],["exit",d,i],["exit",f,i]])),n}function iS(n,i,r){let s=0;return f;function f(b){return n.enter("atxHeading"),d(b)}function d(b){return n.enter("atxHeadingSequence"),o(b)}function o(b){return b===35&&s++<6?(n.consume(b),o):b===null||xt(b)?(n.exit("atxHeadingSequence"),m(b)):r(b)}function m(b){return b===35?(n.enter("atxHeadingSequence"),g(b)):b===null||Me(b)?(n.exit("atxHeading"),i(b)):Ze(b)?tt(n,m,"whitespace")(b):(n.enter("atxHeadingText"),p(b))}function g(b){return b===35?(n.consume(b),g):(n.exit("atxHeadingSequence"),m(b))}function p(b){return b===null||b===35||xt(b)?(n.exit("atxHeadingText"),m(b)):(n.consume(b),p)}}const rS=["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"],Wm=["pre","script","style","textarea"],aS={concrete:!0,name:"htmlFlow",resolveTo:oS,tokenize:cS},sS={partial:!0,tokenize:dS},uS={partial:!0,tokenize:fS};function oS(n){let i=n.length;for(;i--&&!(n[i][0]==="enter"&&n[i][1].type==="htmlFlow"););return i>1&&n[i-2][1].type==="linePrefix"&&(n[i][1].start=n[i-2][1].start,n[i+1][1].start=n[i-2][1].start,n.splice(i-2,2)),n}function cS(n,i,r){const s=this;let f,d,o,m,g;return p;function p(C){return b(C)}function b(C){return n.enter("htmlFlow"),n.enter("htmlFlowData"),n.consume(C),y}function y(C){return C===33?(n.consume(C),v):C===47?(n.consume(C),d=!0,D):C===63?(n.consume(C),f=3,s.interrupt?i:k):en(C)?(n.consume(C),o=String.fromCharCode(C),z):r(C)}function v(C){return C===45?(n.consume(C),f=2,S):C===91?(n.consume(C),f=5,m=0,N):en(C)?(n.consume(C),f=4,s.interrupt?i:k):r(C)}function S(C){return C===45?(n.consume(C),s.interrupt?i:k):r(C)}function N(C){const re="CDATA[";return C===re.charCodeAt(m++)?(n.consume(C),m===re.length?s.interrupt?i:V:N):r(C)}function D(C){return en(C)?(n.consume(C),o=String.fromCharCode(C),z):r(C)}function z(C){if(C===null||C===47||C===62||xt(C)){const re=C===47,ve=o.toLowerCase();return!re&&!d&&Wm.includes(ve)?(f=1,s.interrupt?i(C):V(C)):rS.includes(o.toLowerCase())?(f=6,re?(n.consume(C),_):s.interrupt?i(C):V(C)):(f=7,s.interrupt&&!s.parser.lazy[s.now().line]?r(C):d?M(C):H(C))}return C===45||Jt(C)?(n.consume(C),o+=String.fromCharCode(C),z):r(C)}function _(C){return C===62?(n.consume(C),s.interrupt?i:V):r(C)}function M(C){return Ze(C)?(n.consume(C),M):A(C)}function H(C){return C===47?(n.consume(C),A):C===58||C===95||en(C)?(n.consume(C),oe):Ze(C)?(n.consume(C),H):A(C)}function oe(C){return C===45||C===46||C===58||C===95||Jt(C)?(n.consume(C),oe):ce(C)}function ce(C){return C===61?(n.consume(C),R):Ze(C)?(n.consume(C),ce):H(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?r(C):C===34||C===39?(n.consume(C),g=C,W):Ze(C)?(n.consume(C),R):ie(C)}function W(C){return C===g?(n.consume(C),g=null,F):C===null||Me(C)?r(C):(n.consume(C),W)}function ie(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||xt(C)?ce(C):(n.consume(C),ie)}function F(C){return C===47||C===62||Ze(C)?H(C):r(C)}function A(C){return C===62?(n.consume(C),G):r(C)}function G(C){return C===null||Me(C)?V(C):Ze(C)?(n.consume(C),G):r(C)}function V(C){return C===45&&f===2?(n.consume(C),E):C===60&&f===1?(n.consume(C),U):C===62&&f===4?(n.consume(C),T):C===63&&f===3?(n.consume(C),k):C===93&&f===5?(n.consume(C),he):Me(C)&&(f===6||f===7)?(n.exit("htmlFlowData"),n.check(sS,K,se)(C)):C===null||Me(C)?(n.exit("htmlFlowData"),se(C)):(n.consume(C),V)}function se(C){return n.check(uS,ae,K)(C)}function ae(C){return n.enter("lineEnding"),n.consume(C),n.exit("lineEnding"),P}function P(C){return C===null||Me(C)?se(C):(n.enter("htmlFlowData"),V(C))}function E(C){return C===45?(n.consume(C),k):V(C)}function U(C){return C===47?(n.consume(C),o="",te):V(C)}function te(C){if(C===62){const re=o.toLowerCase();return Wm.includes(re)?(n.consume(C),T):V(C)}return en(C)&&o.length<8?(n.consume(C),o+=String.fromCharCode(C),te):V(C)}function he(C){return C===93?(n.consume(C),k):V(C)}function k(C){return C===62?(n.consume(C),T):C===45&&f===2?(n.consume(C),k):V(C)}function T(C){return C===null||Me(C)?(n.exit("htmlFlowData"),K(C)):(n.consume(C),T)}function K(C){return n.exit("htmlFlow"),i(C)}}function fS(n,i,r){const s=this;return f;function f(o){return Me(o)?(n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),d):r(o)}function d(o){return s.parser.lazy[s.now().line]?r(o):i(o)}}function dS(n,i,r){return s;function s(f){return n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),n.attempt(ra,i,r)}}const hS={name:"htmlText",tokenize:pS};function pS(n,i,r){const s=this;let f,d,o;return m;function m(k){return n.enter("htmlText"),n.enter("htmlTextData"),n.consume(k),g}function g(k){return k===33?(n.consume(k),p):k===47?(n.consume(k),ce):k===63?(n.consume(k),H):en(k)?(n.consume(k),ie):r(k)}function p(k){return k===45?(n.consume(k),b):k===91?(n.consume(k),d=0,N):en(k)?(n.consume(k),M):r(k)}function b(k){return k===45?(n.consume(k),S):r(k)}function y(k){return k===null?r(k):k===45?(n.consume(k),v):Me(k)?(o=y,U(k)):(n.consume(k),y)}function v(k){return k===45?(n.consume(k),S):y(k)}function S(k){return k===62?E(k):k===45?v(k):y(k)}function N(k){const T="CDATA[";return k===T.charCodeAt(d++)?(n.consume(k),d===T.length?D:N):r(k)}function D(k){return k===null?r(k):k===93?(n.consume(k),z):Me(k)?(o=D,U(k)):(n.consume(k),D)}function z(k){return k===93?(n.consume(k),_):D(k)}function _(k){return k===62?E(k):k===93?(n.consume(k),_):D(k)}function M(k){return k===null||k===62?E(k):Me(k)?(o=M,U(k)):(n.consume(k),M)}function H(k){return k===null?r(k):k===63?(n.consume(k),oe):Me(k)?(o=H,U(k)):(n.consume(k),H)}function oe(k){return k===62?E(k):H(k)}function ce(k){return en(k)?(n.consume(k),R):r(k)}function R(k){return k===45||Jt(k)?(n.consume(k),R):W(k)}function W(k){return Me(k)?(o=W,U(k)):Ze(k)?(n.consume(k),W):E(k)}function ie(k){return k===45||Jt(k)?(n.consume(k),ie):k===47||k===62||xt(k)?F(k):r(k)}function F(k){return k===47?(n.consume(k),E):k===58||k===95||en(k)?(n.consume(k),A):Me(k)?(o=F,U(k)):Ze(k)?(n.consume(k),F):E(k)}function A(k){return k===45||k===46||k===58||k===95||Jt(k)?(n.consume(k),A):G(k)}function G(k){return k===61?(n.consume(k),V):Me(k)?(o=G,U(k)):Ze(k)?(n.consume(k),G):F(k)}function V(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(n.consume(k),f=k,se):Me(k)?(o=V,U(k)):Ze(k)?(n.consume(k),V):(n.consume(k),ae)}function se(k){return k===f?(n.consume(k),f=void 0,P):k===null?r(k):Me(k)?(o=se,U(k)):(n.consume(k),se)}function ae(k){return k===null||k===34||k===39||k===60||k===61||k===96?r(k):k===47||k===62||xt(k)?F(k):(n.consume(k),ae)}function P(k){return k===47||k===62||xt(k)?F(k):r(k)}function E(k){return k===62?(n.consume(k),n.exit("htmlTextData"),n.exit("htmlText"),i):r(k)}function U(k){return n.exit("htmlTextData"),n.enter("lineEnding"),n.consume(k),n.exit("lineEnding"),te}function te(k){return Ze(k)?tt(n,he,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):he(k)}function he(k){return n.enter("htmlTextData"),o(k)}}const cf={name:"labelEnd",resolveAll:bS,resolveTo:xS,tokenize:vS},mS={tokenize:SS},gS={tokenize:jS},yS={tokenize:kS};function bS(n){let i=-1;const r=[];for(;++i<n.length;){const s=n[i][1];if(r.push(n[i]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const f=s.type==="labelImage"?4:2;s.type="data",i+=f}}return n.length!==r.length&&xn(n,0,n.length,r),n}function xS(n,i){let r=n.length,s=0,f,d,o,m;for(;r--;)if(f=n[r][1],d){if(f.type==="link"||f.type==="labelLink"&&f._inactive)break;n[r][0]==="enter"&&f.type==="labelLink"&&(f._inactive=!0)}else if(o){if(n[r][0]==="enter"&&(f.type==="labelImage"||f.type==="labelLink")&&!f._balanced&&(d=r,f.type!=="labelLink")){s=2;break}}else f.type==="labelEnd"&&(o=r);const g={type:n[d][1].type==="labelLink"?"link":"image",start:{...n[d][1].start},end:{...n[n.length-1][1].end}},p={type:"label",start:{...n[d][1].start},end:{...n[o][1].end}},b={type:"labelText",start:{...n[d+s+2][1].end},end:{...n[o-2][1].start}};return m=[["enter",g,i],["enter",p,i]],m=zn(m,n.slice(d+1,d+s+3)),m=zn(m,[["enter",b,i]]),m=zn(m,Hs(i.parser.constructs.insideSpan.null,n.slice(d+s+4,o-3),i)),m=zn(m,[["exit",b,i],n[o-2],n[o-1],["exit",p,i]]),m=zn(m,n.slice(o+1)),m=zn(m,[["exit",g,i]]),xn(n,d,n.length,m),n}function vS(n,i,r){const s=this;let f=s.events.length,d,o;for(;f--;)if((s.events[f][1].type==="labelImage"||s.events[f][1].type==="labelLink")&&!s.events[f][1]._balanced){d=s.events[f][1];break}return m;function m(v){return d?d._inactive?y(v):(o=s.parser.defined.includes(Mn(s.sliceSerialize({start:d.end,end:s.now()}))),n.enter("labelEnd"),n.enter("labelMarker"),n.consume(v),n.exit("labelMarker"),n.exit("labelEnd"),g):r(v)}function g(v){return v===40?n.attempt(mS,b,o?b:y)(v):v===91?n.attempt(gS,b,o?p:y)(v):o?b(v):y(v)}function p(v){return n.attempt(yS,b,y)(v)}function b(v){return i(v)}function y(v){return d._balanced=!0,r(v)}}function SS(n,i,r){return s;function s(y){return n.enter("resource"),n.enter("resourceMarker"),n.consume(y),n.exit("resourceMarker"),f}function f(y){return xt(y)?Jr(n,d)(y):d(y)}function d(y){return y===41?b(y):oy(n,o,m,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(y)}function o(y){return xt(y)?Jr(n,g)(y):b(y)}function m(y){return r(y)}function g(y){return y===34||y===39||y===40?fy(n,p,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(y):b(y)}function p(y){return xt(y)?Jr(n,b)(y):b(y)}function b(y){return y===41?(n.enter("resourceMarker"),n.consume(y),n.exit("resourceMarker"),n.exit("resource"),i):r(y)}}function jS(n,i,r){const s=this;return f;function f(m){return cy.call(s,n,d,o,"reference","referenceMarker","referenceString")(m)}function d(m){return s.parser.defined.includes(Mn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?i(m):r(m)}function o(m){return r(m)}}function kS(n,i,r){return s;function s(d){return n.enter("reference"),n.enter("referenceMarker"),n.consume(d),n.exit("referenceMarker"),f}function f(d){return d===93?(n.enter("referenceMarker"),n.consume(d),n.exit("referenceMarker"),n.exit("reference"),i):r(d)}}const wS={name:"labelStartImage",resolveAll:cf.resolveAll,tokenize:CS};function CS(n,i,r){const s=this;return f;function f(m){return n.enter("labelImage"),n.enter("labelImageMarker"),n.consume(m),n.exit("labelImageMarker"),d}function d(m){return m===91?(n.enter("labelMarker"),n.consume(m),n.exit("labelMarker"),n.exit("labelImage"),o):r(m)}function o(m){return m===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(m):i(m)}}const ES={name:"labelStartLink",resolveAll:cf.resolveAll,tokenize:NS};function NS(n,i,r){const s=this;return f;function f(o){return n.enter("labelLink"),n.enter("labelMarker"),n.consume(o),n.exit("labelMarker"),n.exit("labelLink"),d}function d(o){return o===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(o):i(o)}}const bc={name:"lineEnding",tokenize:TS};function TS(n,i){return r;function r(s){return n.enter("lineEnding"),n.consume(s),n.exit("lineEnding"),tt(n,i,"linePrefix")}}const Ts={name:"thematicBreak",tokenize:AS};function AS(n,i,r){let s=0,f;return d;function d(p){return n.enter("thematicBreak"),o(p)}function o(p){return f=p,m(p)}function m(p){return p===f?(n.enter("thematicBreakSequence"),g(p)):s>=3&&(p===null||Me(p))?(n.exit("thematicBreak"),i(p)):r(p)}function g(p){return p===f?(n.consume(p),s++,g):(n.exit("thematicBreakSequence"),Ze(p)?tt(n,m,"whitespace")(p):m(p))}}const on={continuation:{tokenize:DS},exit:MS,name:"list",tokenize:_S},zS={partial:!0,tokenize:LS},RS={partial:!0,tokenize:OS};function _S(n,i,r){const s=this,f=s.events[s.events.length-1];let d=f&&f[1].type==="linePrefix"?f[2].sliceSerialize(f[1],!0).length:0,o=0;return m;function m(S){const N=s.containerState.type||(S===42||S===43||S===45?"listUnordered":"listOrdered");if(N==="listUnordered"?!s.containerState.marker||S===s.containerState.marker:Bc(S)){if(s.containerState.type||(s.containerState.type=N,n.enter(N,{_container:!0})),N==="listUnordered")return n.enter("listItemPrefix"),S===42||S===45?n.check(Ts,r,p)(S):p(S);if(!s.interrupt||S===49)return n.enter("listItemPrefix"),n.enter("listItemValue"),g(S)}return r(S)}function g(S){return Bc(S)&&++o<10?(n.consume(S),g):(!s.interrupt||o<2)&&(s.containerState.marker?S===s.containerState.marker:S===41||S===46)?(n.exit("listItemValue"),p(S)):r(S)}function p(S){return n.enter("listItemMarker"),n.consume(S),n.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||S,n.check(ra,s.interrupt?r:b,n.attempt(zS,v,y))}function b(S){return s.containerState.initialBlankLine=!0,d++,v(S)}function y(S){return Ze(S)?(n.enter("listItemPrefixWhitespace"),n.consume(S),n.exit("listItemPrefixWhitespace"),v):r(S)}function v(S){return s.containerState.size=d+s.sliceSerialize(n.exit("listItemPrefix"),!0).length,i(S)}}function DS(n,i,r){const s=this;return s.containerState._closeFlow=void 0,n.check(ra,f,d);function f(m){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,tt(n,i,"listItemIndent",s.containerState.size+1)(m)}function d(m){return s.containerState.furtherBlankLines||!Ze(m)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,o(m)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,n.attempt(RS,i,o)(m))}function o(m){return s.containerState._closeFlow=!0,s.interrupt=void 0,tt(n,n.attempt(on,i,r),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m)}}function OS(n,i,r){const s=this;return tt(n,f,"listItemIndent",s.containerState.size+1);function f(d){const o=s.events[s.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===s.containerState.size?i(d):r(d)}}function MS(n){n.exit(this.containerState.type)}function LS(n,i,r){const s=this;return tt(n,f,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function f(d){const o=s.events[s.events.length-1];return!Ze(d)&&o&&o[1].type==="listItemPrefixWhitespace"?i(d):r(d)}}const eg={name:"setextUnderline",resolveTo:US,tokenize:BS};function US(n,i){let r=n.length,s,f,d;for(;r--;)if(n[r][0]==="enter"){if(n[r][1].type==="content"){s=r;break}n[r][1].type==="paragraph"&&(f=r)}else n[r][1].type==="content"&&n.splice(r,1),!d&&n[r][1].type==="definition"&&(d=r);const o={type:"setextHeading",start:{...n[s][1].start},end:{...n[n.length-1][1].end}};return n[f][1].type="setextHeadingText",d?(n.splice(f,0,["enter",o,i]),n.splice(d+1,0,["exit",n[s][1],i]),n[s][1].end={...n[d][1].end}):n[s][1]=o,n.push(["exit",o,i]),n}function BS(n,i,r){const s=this;let f;return d;function d(p){let b=s.events.length,y;for(;b--;)if(s.events[b][1].type!=="lineEnding"&&s.events[b][1].type!=="linePrefix"&&s.events[b][1].type!=="content"){y=s.events[b][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||y)?(n.enter("setextHeadingLine"),f=p,o(p)):r(p)}function o(p){return n.enter("setextHeadingLineSequence"),m(p)}function m(p){return p===f?(n.consume(p),m):(n.exit("setextHeadingLineSequence"),Ze(p)?tt(n,g,"lineSuffix")(p):g(p))}function g(p){return p===null||Me(p)?(n.exit("setextHeadingLine"),i(p)):r(p)}}const qS={tokenize:HS};function HS(n){const i=this,r=n.attempt(ra,s,n.attempt(this.parser.constructs.flowInitial,f,tt(n,n.attempt(this.parser.constructs.flow,f,n.attempt(Q1,f)),"linePrefix")));return r;function s(d){if(d===null){n.consume(d);return}return n.enter("lineEndingBlank"),n.consume(d),n.exit("lineEndingBlank"),i.currentConstruct=void 0,r}function f(d){if(d===null){n.consume(d);return}return n.enter("lineEnding"),n.consume(d),n.exit("lineEnding"),i.currentConstruct=void 0,r}}const IS={resolveAll:hy()},YS=dy("string"),GS=dy("text");function dy(n){return{resolveAll:hy(n==="text"?VS:void 0),tokenize:i};function i(r){const s=this,f=this.parser.constructs[n],d=r.attempt(f,o,m);return o;function o(b){return p(b)?d(b):m(b)}function m(b){if(b===null){r.consume(b);return}return r.enter("data"),r.consume(b),g}function g(b){return p(b)?(r.exit("data"),d(b)):(r.consume(b),g)}function p(b){if(b===null)return!0;const y=f[b];let v=-1;if(y)for(;++v<y.length;){const S=y[v];if(!S.previous||S.previous.call(s,s.previous))return!0}return!1}}}function hy(n){return i;function i(r,s){let f=-1,d;for(;++f<=r.length;)d===void 0?r[f]&&r[f][1].type==="data"&&(d=f,f++):(!r[f]||r[f][1].type!=="data")&&(f!==d+2&&(r[d][1].end=r[f-1][1].end,r.splice(d+2,f-d-2),f=d+2),d=void 0);return n?n(r,s):r}}function VS(n,i){let r=0;for(;++r<=n.length;)if((r===n.length||n[r][1].type==="lineEnding")&&n[r-1][1].type==="data"){const s=n[r-1][1],f=i.sliceStream(s);let d=f.length,o=-1,m=0,g;for(;d--;){const p=f[d];if(typeof p=="string"){for(o=p.length;p.charCodeAt(o-1)===32;)m++,o--;if(o)break;o=-1}else if(p===-2)g=!0,m++;else if(p!==-1){d++;break}}if(i._contentTypeTextTrailing&&r===n.length&&(m=0),m){const p={type:r===n.length||g||m<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:d?o:s.start._bufferIndex+o,_index:s.start._index+d,line:s.end.line,column:s.end.column-m,offset:s.end.offset-m},end:{...s.end}};s.end={...p.start},s.start.offset===s.end.offset?Object.assign(s,p):(n.splice(r,0,["enter",p,i],["exit",p,i]),r+=2)}r++}return n}const QS={42:on,43:on,45:on,48:on,49:on,50:on,51:on,52:on,53:on,54:on,55:on,56:on,57:on,62:ry},XS={91:$1},ZS={[-2]:yc,[-1]:yc,32:yc},KS={35:nS,42:Ts,45:[eg,Ts],60:aS,61:eg,95:Ts,96:Pm,126:Pm},FS={38:sy,92:ay},$S={[-5]:bc,[-4]:bc,[-3]:bc,33:wS,38:sy,42:qc,60:[E1,hS],91:ES,92:[eS,ay],93:cf,95:qc,96:q1},JS={null:[qc,IS]},PS={null:[42,95]},WS={null:[]},ej=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:PS,contentInitial:XS,disable:WS,document:QS,flow:KS,flowInitial:ZS,insideSpan:JS,string:FS,text:$S},Symbol.toStringTag,{value:"Module"}));function tj(n,i,r){let s={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const f={},d=[];let o=[],m=[];const g={attempt:W(ce),check:W(R),consume:M,enter:H,exit:oe,interrupt:W(R,{interrupt:!0})},p={code:null,containerState:{},defineSkip:D,events:[],now:N,parser:n,previous:null,sliceSerialize:v,sliceStream:S,write:y};let b=i.tokenize.call(p,g);return i.resolveAll&&d.push(i),p;function y(G){return o=zn(o,G),z(),o[o.length-1]!==null?[]:(ie(i,0),p.events=Hs(d,p.events,p),p.events)}function v(G,V){return lj(S(G),V)}function S(G){return nj(o,G)}function N(){const{_bufferIndex:G,_index:V,line:se,column:ae,offset:P}=s;return{_bufferIndex:G,_index:V,line:se,column:ae,offset:P}}function D(G){f[G.line]=G.column,A()}function z(){let G;for(;s._index<o.length;){const V=o[s._index];if(typeof V=="string")for(G=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===G&&s._bufferIndex<V.length;)_(V.charCodeAt(s._bufferIndex));else _(V)}}function _(G){b=b(G)}function M(G){Me(G)?(s.line++,s.column=1,s.offset+=G===-3?2:1,A()):G!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===o[s._index].length&&(s._bufferIndex=-1,s._index++)),p.previous=G}function H(G,V){const se=V||{};return se.type=G,se.start=N(),p.events.push(["enter",se,p]),m.push(se),se}function oe(G){const V=m.pop();return V.end=N(),p.events.push(["exit",V,p]),V}function ce(G,V){ie(G,V.from)}function R(G,V){V.restore()}function W(G,V){return se;function se(ae,P,E){let U,te,he,k;return Array.isArray(ae)?K(ae):"tokenize"in ae?K([ae]):T(ae);function T(Q){return pe;function pe(je){const Y=je!==null&&Q[je],xe=je!==null&&Q.null,J=[...Array.isArray(Y)?Y:Y?[Y]:[],...Array.isArray(xe)?xe:xe?[xe]:[]];return K(J)(je)}}function K(Q){return U=Q,te=0,Q.length===0?E:C(Q[te])}function C(Q){return pe;function pe(je){return k=F(),he=Q,Q.partial||(p.currentConstruct=Q),Q.name&&p.parser.constructs.disable.null.includes(Q.name)?ve():Q.tokenize.call(V?Object.assign(Object.create(p),V):p,g,re,ve)(je)}}function re(Q){return G(he,k),P}function ve(Q){return k.restore(),++te<U.length?C(U[te]):E}}}function ie(G,V){G.resolveAll&&!d.includes(G)&&d.push(G),G.resolve&&xn(p.events,V,p.events.length-V,G.resolve(p.events.slice(V),p)),G.resolveTo&&(p.events=G.resolveTo(p.events,p))}function F(){const G=N(),V=p.previous,se=p.currentConstruct,ae=p.events.length,P=Array.from(m);return{from:ae,restore:E};function E(){s=G,p.previous=V,p.currentConstruct=se,p.events.length=ae,m=P,A()}}function A(){s.line in f&&s.column<2&&(s.column=f[s.line],s.offset+=f[s.line]-1)}}function nj(n,i){const r=i.start._index,s=i.start._bufferIndex,f=i.end._index,d=i.end._bufferIndex;let o;if(r===f)o=[n[r].slice(s,d)];else{if(o=n.slice(r,f),s>-1){const m=o[0];typeof m=="string"?o[0]=m.slice(s):o.shift()}d>0&&o.push(n[f].slice(0,d))}return o}function lj(n,i){let r=-1;const s=[];let f;for(;++r<n.length;){const d=n[r];let o;if(typeof d=="string")o=d;else switch(d){case-5:{o="\r";break}case-4:{o=`
22
22
  `;break}case-3:{o=`\r
23
23
  `;break}case-2:{o=i?" ":" ";break}case-1:{if(!i&&f)continue;o=" ";break}default:o=String.fromCharCode(d)}f=d===-2,s.push(o)}return s.join("")}function ij(n){const s={constructs:ly([ej,...(n||{}).extensions||[]]),content:f(x1),defined:[],document:f(S1),flow:f(qS),lazy:{},string:f(YS),text:f(GS)};return s;function f(d){return o;function o(m){return tj(s,d,m)}}}function rj(n){for(;!uy(n););return n}const tg=/[\0\t\n\r]/g;function aj(){let n=1,i="",r=!0,s;return f;function f(d,o,m){const g=[];let p,b,y,v,S;for(d=i+(typeof d=="string"?d.toString():new TextDecoder(o||void 0).decode(d)),y=0,i="",r&&(d.charCodeAt(0)===65279&&y++,r=void 0);y<d.length;){if(tg.lastIndex=y,p=tg.exec(d),v=p&&p.index!==void 0?p.index:d.length,S=d.charCodeAt(v),!p){i=d.slice(y);break}if(S===10&&y===v&&s)g.push(-3),s=void 0;else switch(s&&(g.push(-5),s=void 0),y<v&&(g.push(d.slice(y,v)),n+=v-y),S){case 0:{g.push(65533),n++;break}case 9:{for(b=Math.ceil(n/4)*4,g.push(-2);n++<b;)g.push(-1);break}case 10:{g.push(-4),n=1;break}default:s=!0,n=1}y=v+1}return m&&(s&&g.push(-5),i&&g.push(i),g.push(null)),g}}const sj=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function uj(n){return n.replace(sj,oj)}function oj(n,i,r){if(i)return i;if(r.charCodeAt(0)===35){const f=r.charCodeAt(1),d=f===120||f===88;return iy(r.slice(d?2:1),d?16:10)}return of(r)||n}const py={}.hasOwnProperty;function cj(n,i,r){return i&&typeof i=="object"&&(r=i,i=void 0),fj(r)(rj(ij(r).document().write(aj()(n,i,!0))))}function fj(n){const i={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:d(at),autolinkProtocol:F,autolinkEmail:F,atxHeading:d(Ye),blockQuote:d(xe),characterEscape:F,characterReference:F,codeFenced:d(J),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:d(J,o),codeText:d(ye,o),codeTextData:F,data:F,codeFlowValue:F,definition:d(Ae),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:d(we),hardBreakEscape:d(nt),hardBreakTrailing:d(nt),htmlFlow:d(jt,o),htmlFlowData:F,htmlText:d(jt,o),htmlTextData:F,image:d(Yt),label:o,link:d(at),listItem:d(ut),listItemValue:v,listOrdered:d(mt,y),listUnordered:d(mt),paragraph:d(ot),reference:C,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:d(Ye),strong:d(Gt),thematicBreak:d(qt)},exit:{atxHeading:g(),atxHeadingSequence:ce,autolink:g(),autolinkEmail:Y,autolinkProtocol:je,blockQuote:g(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:ve,characterReferenceMarkerNumeric:ve,characterReferenceValue:Q,characterReference:pe,codeFenced:g(z),codeFencedFence:D,codeFencedFenceInfo:S,codeFencedFenceMeta:N,codeFlowValue:A,codeIndented:g(_),codeText:g(P),codeTextData:A,data:A,definition:g(),definitionDestinationString:oe,definitionLabelString:M,definitionTitleString:H,emphasis:g(),hardBreakEscape:g(V),hardBreakTrailing:g(V),htmlFlow:g(se),htmlFlowData:A,htmlText:g(ae),htmlTextData:A,image:g(U),label:he,labelText:te,lineEnding:G,link:g(E),listItem:g(),listOrdered:g(),listUnordered:g(),paragraph:g(),referenceString:re,resourceDestinationString:k,resourceTitleString:T,resource:K,setextHeading:g(ie),setextHeadingLineSequence:W,setextHeadingText:R,strong:g(),thematicBreak:g()}};my(i,(n||{}).mdastExtensions||[]);const r={};return s;function s(ne){let me={type:"root",children:[]};const Te={stack:[me],tokenStack:[],config:i,enter:m,exit:p,buffer:o,resume:b,data:r},ge=[];let ke=-1;for(;++ke<ne.length;)if(ne[ke][1].type==="listOrdered"||ne[ke][1].type==="listUnordered")if(ne[ke][0]==="enter")ge.push(ke);else{const Ce=ge.pop();ke=f(ne,Ce,ke)}for(ke=-1;++ke<ne.length;){const Ce=i[ne[ke][0]];py.call(Ce,ne[ke][1].type)&&Ce[ne[ke][1].type].call(Object.assign({sliceSerialize:ne[ke][2].sliceSerialize},Te),ne[ke][1])}if(Te.tokenStack.length>0){const Ce=Te.tokenStack[Te.tokenStack.length-1];(Ce[1]||ng).call(Te,void 0,Ce[0])}for(me.position={start:Ml(ne.length>0?ne[0][1].start:{line:1,column:1,offset:0}),end:Ml(ne.length>0?ne[ne.length-2][1].end:{line:1,column:1,offset:0})},ke=-1;++ke<i.transforms.length;)me=i.transforms[ke](me)||me;return me}function f(ne,me,Te){let ge=me-1,ke=-1,Ce=!1,B,Se,Ke,lt;for(;++ge<=Te;){const Be=ne[ge];switch(Be[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Be[0]==="enter"?ke++:ke--,lt=void 0;break}case"lineEndingBlank":{Be[0]==="enter"&&(B&&!lt&&!ke&&!Ke&&(Ke=ge),lt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:lt=void 0}if(!ke&&Be[0]==="enter"&&Be[1].type==="listItemPrefix"||ke===-1&&Be[0]==="exit"&&(Be[1].type==="listUnordered"||Be[1].type==="listOrdered")){if(B){let q=ge;for(Se=void 0;q--;){const ze=ne[q];if(ze[1].type==="lineEnding"||ze[1].type==="lineEndingBlank"){if(ze[0]==="exit")continue;Se&&(ne[Se][1].type="lineEndingBlank",Ce=!0),ze[1].type="lineEnding",Se=q}else if(!(ze[1].type==="linePrefix"||ze[1].type==="blockQuotePrefix"||ze[1].type==="blockQuotePrefixWhitespace"||ze[1].type==="blockQuoteMarker"||ze[1].type==="listItemIndent"))break}Ke&&(!Se||Ke<Se)&&(B._spread=!0),B.end=Object.assign({},Se?ne[Se][1].start:Be[1].end),ne.splice(Se||ge,0,["exit",B,Be[2]]),ge++,Te++}if(Be[1].type==="listItemPrefix"){const q={type:"listItem",_spread:!1,start:Object.assign({},Be[1].start),end:void 0};B=q,ne.splice(ge,0,["enter",q,Be[2]]),ge++,Te++,Ke=void 0,lt=!0}}}return ne[me][1]._spread=Ce,Te}function d(ne,me){return Te;function Te(ge){m.call(this,ne(ge),ge),me&&me.call(this,ge)}}function o(){this.stack.push({type:"fragment",children:[]})}function m(ne,me,Te){this.stack[this.stack.length-1].children.push(ne),this.stack.push(ne),this.tokenStack.push([me,Te||void 0]),ne.position={start:Ml(me.start),end:void 0}}function g(ne){return me;function me(Te){ne&&ne.call(this,Te),p.call(this,Te)}}function p(ne,me){const Te=this.stack.pop(),ge=this.tokenStack.pop();if(ge)ge[0].type!==ne.type&&(me?me.call(this,ne,ge[0]):(ge[1]||ng).call(this,ne,ge[0]));else throw new Error("Cannot close `"+ne.type+"` ("+$r({start:ne.start,end:ne.end})+"): it’s not open");Te.position.end=Ml(ne.end)}function b(){return uf(this.stack.pop())}function y(){this.data.expectingFirstListItemValue=!0}function v(ne){if(this.data.expectingFirstListItemValue){const me=this.stack[this.stack.length-2];me.start=Number.parseInt(this.sliceSerialize(ne),10),this.data.expectingFirstListItemValue=void 0}}function S(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.lang=ne}function N(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.meta=ne}function D(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function z(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.value=ne.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function _(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.value=ne.replace(/(\r?\n|\r)$/g,"")}function M(ne){const me=this.resume(),Te=this.stack[this.stack.length-1];Te.label=me,Te.identifier=Mn(this.sliceSerialize(ne)).toLowerCase()}function H(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.title=ne}function oe(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.url=ne}function ce(ne){const me=this.stack[this.stack.length-1];if(!me.depth){const Te=this.sliceSerialize(ne).length;me.depth=Te}}function R(){this.data.setextHeadingSlurpLineEnding=!0}function W(ne){const me=this.stack[this.stack.length-1];me.depth=this.sliceSerialize(ne).codePointAt(0)===61?1:2}function ie(){this.data.setextHeadingSlurpLineEnding=void 0}function F(ne){const Te=this.stack[this.stack.length-1].children;let ge=Te[Te.length-1];(!ge||ge.type!=="text")&&(ge=vt(),ge.position={start:Ml(ne.start),end:void 0},Te.push(ge)),this.stack.push(ge)}function A(ne){const me=this.stack.pop();me.value+=this.sliceSerialize(ne),me.position.end=Ml(ne.end)}function G(ne){const me=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Te=me.children[me.children.length-1];Te.position.end=Ml(ne.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&i.canContainEols.includes(me.type)&&(F.call(this,ne),A.call(this,ne))}function V(){this.data.atHardBreak=!0}function se(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.value=ne}function ae(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.value=ne}function P(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.value=ne}function E(){const ne=this.stack[this.stack.length-1];if(this.data.inReference){const me=this.data.referenceType||"shortcut";ne.type+="Reference",ne.referenceType=me,delete ne.url,delete ne.title}else delete ne.identifier,delete ne.label;this.data.referenceType=void 0}function U(){const ne=this.stack[this.stack.length-1];if(this.data.inReference){const me=this.data.referenceType||"shortcut";ne.type+="Reference",ne.referenceType=me,delete ne.url,delete ne.title}else delete ne.identifier,delete ne.label;this.data.referenceType=void 0}function te(ne){const me=this.sliceSerialize(ne),Te=this.stack[this.stack.length-2];Te.label=uj(me),Te.identifier=Mn(me).toLowerCase()}function he(){const ne=this.stack[this.stack.length-1],me=this.resume(),Te=this.stack[this.stack.length-1];if(this.data.inReference=!0,Te.type==="link"){const ge=ne.children;Te.children=ge}else Te.alt=me}function k(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.url=ne}function T(){const ne=this.resume(),me=this.stack[this.stack.length-1];me.title=ne}function K(){this.data.inReference=void 0}function C(){this.data.referenceType="collapsed"}function re(ne){const me=this.resume(),Te=this.stack[this.stack.length-1];Te.label=me,Te.identifier=Mn(this.sliceSerialize(ne)).toLowerCase(),this.data.referenceType="full"}function ve(ne){this.data.characterReferenceType=ne.type}function Q(ne){const me=this.sliceSerialize(ne),Te=this.data.characterReferenceType;let ge;Te?(ge=iy(me,Te==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ge=of(me);const ke=this.stack[this.stack.length-1];ke.value+=ge}function pe(ne){const me=this.stack.pop();me.position.end=Ml(ne.end)}function je(ne){A.call(this,ne);const me=this.stack[this.stack.length-1];me.url=this.sliceSerialize(ne)}function Y(ne){A.call(this,ne);const me=this.stack[this.stack.length-1];me.url="mailto:"+this.sliceSerialize(ne)}function xe(){return{type:"blockquote",children:[]}}function J(){return{type:"code",lang:null,meta:null,value:""}}function ye(){return{type:"inlineCode",value:""}}function Ae(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function we(){return{type:"emphasis",children:[]}}function Ye(){return{type:"heading",depth:0,children:[]}}function nt(){return{type:"break"}}function jt(){return{type:"html",value:""}}function Yt(){return{type:"image",title:null,url:"",alt:null}}function at(){return{type:"link",title:null,url:"",children:[]}}function mt(ne){return{type:"list",ordered:ne.type==="listOrdered",start:null,spread:ne._spread,children:[]}}function ut(ne){return{type:"listItem",spread:ne._spread,checked:null,children:[]}}function ot(){return{type:"paragraph",children:[]}}function Gt(){return{type:"strong",children:[]}}function vt(){return{type:"text",value:""}}function qt(){return{type:"thematicBreak"}}}function Ml(n){return{line:n.line,column:n.column,offset:n.offset}}function my(n,i){let r=-1;for(;++r<i.length;){const s=i[r];Array.isArray(s)?my(n,s):dj(n,s)}}function dj(n,i){let r;for(r in i)if(py.call(i,r))switch(r){case"canContainEols":{const s=i[r];s&&n[r].push(...s);break}case"transforms":{const s=i[r];s&&n[r].push(...s);break}case"enter":case"exit":{const s=i[r];s&&Object.assign(n[r],s);break}}}function ng(n,i){throw n?new Error("Cannot close `"+n.type+"` ("+$r({start:n.start,end:n.end})+"): a different token (`"+i.type+"`, "+$r({start:i.start,end:i.end})+") is open"):new Error("Cannot close document, a token (`"+i.type+"`, "+$r({start:i.start,end:i.end})+") is still open")}function hj(n){const i=this;i.parser=r;function r(s){return cj(s,{...i.data("settings"),...n,extensions:i.data("micromarkExtensions")||[],mdastExtensions:i.data("fromMarkdownExtensions")||[]})}}function pj(n,i){const r={type:"element",tagName:"blockquote",properties:{},children:n.wrap(n.all(i),!0)};return n.patch(i,r),n.applyData(i,r)}function mj(n,i){const r={type:"element",tagName:"br",properties:{},children:[]};return n.patch(i,r),[n.applyData(i,r),{type:"text",value:`
@@ -7,7 +7,7 @@
7
7
  <link rel="manifest" href="/manifest.webmanifest" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icon.svg" />
9
9
  <title>CodeShell Hub</title>
10
- <script type="module" crossorigin src="/assets/index-Bshhn7qV.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-D4xno_7a.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-Dz4kCU3p.css">
12
12
  </head>
13
13
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cjhyy/code-shell-web",
3
- "version": "0.9.19",
3
+ "version": "0.9.21",
4
4
  "description": "CodeShell web client logic layer — remote-app state (chatReducer + server-event fold), reconnecting WebSocket hook, pairing/device-credential/risk helpers, and the mobile i18n namespace. Browser-only (no Electron, no Node); seed of the standalone browser client.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,8 +24,8 @@
24
24
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true});require('node:fs').rmSync('dist-app',{recursive:true,force:true})\""
25
25
  },
26
26
  "dependencies": {
27
- "@cjhyy/code-shell-core": "0.9.19",
28
- "@cjhyy/code-shell-link": "0.9.19"
27
+ "@cjhyy/code-shell-core": "0.9.21",
28
+ "@cjhyy/code-shell-link": "0.9.21"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "react": "19.2.6"