@cjhyy/code-shell-web 0.9.18 → 0.9.20

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:`
@@ -45,6 +45,6 @@ description: 描述这个 Skill 适合处理什么任务
45
45
  `))+1))}const o="#".repeat(f),m=r.enter("headingAtx"),g=r.enter("phrasing");d.move(o+" ");let p=r.containerPhrasing(n,{before:"# ",after:`
46
46
  `,...d.current()});return/^[\t ]/.test(p)&&(p=ta(p.charCodeAt(0))+p.slice(1)),p=p?o+" "+p:o,r.options.closeAtx&&(p+=" "+o),g(),m(),p}Ay.peek=Mw;function Ay(n){return n.value||""}function Mw(){return"<"}zy.peek=Lw;function zy(n,i,r,s){const f=yf(r),d=f==='"'?"Quote":"Apostrophe",o=r.enter("image");let m=r.enter("label");const g=r.createTracker(s);let p=g.move("![");return p+=g.move(r.safe(n.alt,{before:p,after:"]",...g.current()})),p+=g.move("]("),m(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(m=r.enter("destinationLiteral"),p+=g.move("<"),p+=g.move(r.safe(n.url,{before:p,after:">",...g.current()})),p+=g.move(">")):(m=r.enter("destinationRaw"),p+=g.move(r.safe(n.url,{before:p,after:n.title?" ":")",...g.current()}))),m(),n.title&&(m=r.enter(`title${d}`),p+=g.move(" "+f),p+=g.move(r.safe(n.title,{before:p,after:f,...g.current()})),p+=g.move(f),m()),p+=g.move(")"),o(),p}function Lw(){return"!"}Ry.peek=Uw;function Ry(n,i,r,s){const f=n.referenceType,d=r.enter("imageReference");let o=r.enter("label");const m=r.createTracker(s);let g=m.move("![");const p=r.safe(n.alt,{before:g,after:"]",...m.current()});g+=m.move(p+"]["),o();const b=r.stack;r.stack=[],o=r.enter("reference");const y=r.safe(r.associationId(n),{before:g,after:"]",...m.current()});return o(),r.stack=b,d(),f==="full"||!p||p!==y?g+=m.move(y+"]"):f==="shortcut"?g=g.slice(0,-1):g+=m.move("]"),g}function Uw(){return"!"}_y.peek=Bw;function _y(n,i,r){let s=n.value||"",f="`",d=-1;for(;new RegExp("(^|[^`])"+f+"([^`]|$)").test(s);)f+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++d<r.unsafe.length;){const o=r.unsafe[d],m=r.compilePattern(o);let g;if(o.atBreak)for(;g=m.exec(s);){let p=g.index;s.charCodeAt(p)===10&&s.charCodeAt(p-1)===13&&p--,s=s.slice(0,p)+" "+s.slice(g.index+1)}}return f+s+f}function Bw(){return"`"}function Dy(n,i){const r=uf(n);return!!(!i.options.resourceLink&&n.url&&!n.title&&n.children&&n.children.length===1&&n.children[0].type==="text"&&(r===n.url||"mailto:"+r===n.url)&&/^[a-z][a-z+.-]+:/i.test(n.url)&&!/[\0- <>\u007F]/.test(n.url))}Oy.peek=qw;function Oy(n,i,r,s){const f=yf(r),d=f==='"'?"Quote":"Apostrophe",o=r.createTracker(s);let m,g;if(Dy(n,r)){const b=r.stack;r.stack=[],m=r.enter("autolink");let y=o.move("<");return y+=o.move(r.containerPhrasing(n,{before:y,after:">",...o.current()})),y+=o.move(">"),m(),r.stack=b,y}m=r.enter("link"),g=r.enter("label");let p=o.move("[");return p+=o.move(r.containerPhrasing(n,{before:p,after:"](",...o.current()})),p+=o.move("]("),g(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(g=r.enter("destinationLiteral"),p+=o.move("<"),p+=o.move(r.safe(n.url,{before:p,after:">",...o.current()})),p+=o.move(">")):(g=r.enter("destinationRaw"),p+=o.move(r.safe(n.url,{before:p,after:n.title?" ":")",...o.current()}))),g(),n.title&&(g=r.enter(`title${d}`),p+=o.move(" "+f),p+=o.move(r.safe(n.title,{before:p,after:f,...o.current()})),p+=o.move(f),g()),p+=o.move(")"),m(),p}function qw(n,i,r){return Dy(n,r)?"<":"["}My.peek=Hw;function My(n,i,r,s){const f=n.referenceType,d=r.enter("linkReference");let o=r.enter("label");const m=r.createTracker(s);let g=m.move("[");const p=r.containerPhrasing(n,{before:g,after:"]",...m.current()});g+=m.move(p+"]["),o();const b=r.stack;r.stack=[],o=r.enter("reference");const y=r.safe(r.associationId(n),{before:g,after:"]",...m.current()});return o(),r.stack=b,d(),f==="full"||!p||p!==y?g+=m.move(y+"]"):f==="shortcut"?g=g.slice(0,-1):g+=m.move("]"),g}function Hw(){return"["}function bf(n){const i=n.options.bullet||"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bullet`, expected `*`, `+`, or `-`");return i}function Iw(n){const i=bf(n),r=n.options.bulletOther;if(!r)return i==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===i)throw new Error("Expected `bullet` (`"+i+"`) and `bulletOther` (`"+r+"`) to be different");return r}function Yw(n){const i=n.options.bulletOrdered||".";if(i!=="."&&i!==")")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOrdered`, expected `.` or `)`");return i}function Ly(n){const i=n.options.rule||"*";if(i!=="*"&&i!=="-"&&i!=="_")throw new Error("Cannot serialize rules with `"+i+"` for `options.rule`, expected `*`, `-`, or `_`");return i}function Gw(n,i,r,s){const f=r.enter("list"),d=r.bulletCurrent;let o=n.ordered?Yw(r):bf(r);const m=n.ordered?o==="."?")":".":Iw(r);let g=i&&r.bulletLastUsed?o===r.bulletLastUsed:!1;if(!n.ordered){const b=n.children?n.children[0]:void 0;if((o==="*"||o==="-")&&b&&(!b.children||!b.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(g=!0),Ly(r)===o&&b){let y=-1;for(;++y<n.children.length;){const v=n.children[y];if(v&&v.type==="listItem"&&v.children&&v.children[0]&&v.children[0].type==="thematicBreak"){g=!0;break}}}}g&&(o=m),r.bulletCurrent=o;const p=r.containerFlow(n,s);return r.bulletLastUsed=o,r.bulletCurrent=d,f(),p}function Vw(n){const i=n.options.listItemIndent||"one";if(i!=="tab"&&i!=="one"&&i!=="mixed")throw new Error("Cannot serialize items with `"+i+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return i}function Qw(n,i,r,s){const f=Vw(r);let d=r.bulletCurrent||bf(r);i&&i.type==="list"&&i.ordered&&(d=(typeof i.start=="number"&&i.start>-1?i.start:1)+(r.options.incrementListMarker===!1?0:i.children.indexOf(n))+d);let o=d.length+1;(f==="tab"||f==="mixed"&&(i&&i.type==="list"&&i.spread||n.spread))&&(o=Math.ceil(o/4)*4);const m=r.createTracker(s);m.move(d+" ".repeat(o-d.length)),m.shift(o);const g=r.enter("listItem"),p=r.indentLines(r.containerFlow(n,m.current()),b);return g(),p;function b(y,v,S){return v?(S?"":" ".repeat(o))+y:(S?d:d+" ".repeat(o-d.length))+y}}function Xw(n,i,r,s){const f=r.enter("paragraph"),d=r.enter("phrasing"),o=r.containerPhrasing(n,s);return d(),f(),o}const Zw=Ys(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Kw(n,i,r,s){return(n.children.some(function(o){return Zw(o)})?r.containerPhrasing:r.containerFlow).call(r,n,s)}function Fw(n){const i=n.options.strong||"*";if(i!=="*"&&i!=="_")throw new Error("Cannot serialize strong with `"+i+"` for `options.strong`, expected `*`, or `_`");return i}Uy.peek=$w;function Uy(n,i,r,s){const f=Fw(r),d=r.enter("strong"),o=r.createTracker(s),m=o.move(f+f);let g=o.move(r.containerPhrasing(n,{after:f,before:m,...o.current()}));const p=g.charCodeAt(0),b=Ds(s.before.charCodeAt(s.before.length-1),p,f);b.inside&&(g=ta(p)+g.slice(1));const y=g.charCodeAt(g.length-1),v=Ds(s.after.charCodeAt(0),y,f);v.inside&&(g=g.slice(0,-1)+ta(y));const S=o.move(f+f);return d(),r.attentionEncodeSurroundingInfo={after:v.outside,before:b.outside},m+g+S}function $w(n,i,r){return r.options.strong||"*"}function Jw(n,i,r,s){return r.safe(n.value,s)}function Pw(n){const i=n.options.ruleRepetition||3;if(i<3)throw new Error("Cannot serialize rules with repetition `"+i+"` for `options.ruleRepetition`, expected `3` or more");return i}function Ww(n,i,r){const s=(Ly(r)+(r.options.ruleSpaces?" ":"")).repeat(Pw(r));return r.options.ruleSpaces?s.slice(0,-1):s}const By={blockquote:jw,break:Sg,code:Tw,definition:zw,emphasis:Ty,hardBreak:Sg,heading:Ow,html:Ay,image:zy,imageReference:Ry,inlineCode:_y,link:Oy,linkReference:My,list:Gw,listItem:Qw,paragraph:Xw,root:Kw,strong:Uy,text:Jw,thematicBreak:Ww};function eC(){return{enter:{table:tC,tableData:jg,tableHeader:jg,tableRow:lC},exit:{codeText:iC,table:nC,tableData:zc,tableHeader:zc,tableRow:zc}}}function tC(n){const i=n._align;this.enter({type:"table",align:i.map(function(r){return r==="none"?null:r}),children:[]},n),this.data.inTable=!0}function nC(n){this.exit(n),this.data.inTable=void 0}function lC(n){this.enter({type:"tableRow",children:[]},n)}function zc(n){this.exit(n)}function jg(n){this.enter({type:"tableCell",children:[]},n)}function iC(n){let i=this.resume();this.data.inTable&&(i=i.replace(/\\([\\|])/g,rC));const r=this.stack[this.stack.length-1];r.type,r.value=i,this.exit(n)}function rC(n,i){return i==="|"?i:n}function aC(n){const i=n||{},r=i.tableCellPadding,s=i.tablePipeAlign,f=i.stringLength,d=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
47
47
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:v,table:o,tableCell:g,tableRow:m}};function o(S,N,D,z){return p(b(S,D,z),S.align)}function m(S,N,D,z){const _=y(S,D,z),M=p([_]);return M.slice(0,M.indexOf(`
48
- `))}function g(S,N,D,z){const _=D.enter("tableCell"),M=D.enter("phrasing"),H=D.containerPhrasing(S,{...z,before:d,after:d});return M(),_(),H}function p(S,N){return vw(S,{align:N,alignDelimiters:s,padding:r,stringLength:f})}function b(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("table");for(;++_<z.length;)M[_]=y(z[_],N,D);return H(),M}function y(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("tableRow");for(;++_<z.length;)M[_]=g(z[_],S,N,D);return H(),M}function v(S,N,D){let z=By.inlineCode(S,N,D);return D.stack.includes("tableCell")&&(z=z.replace(/\|/g,"\\$&")),z}}function sC(){return{exit:{taskListCheckValueChecked:kg,taskListCheckValueUnchecked:kg,paragraph:oC}}}function uC(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:cC}}}function kg(n){const i=this.stack[this.stack.length-2];i.type,i.checked=n.type==="taskListCheckValueChecked"}function oC(n){const i=this.stack[this.stack.length-2];if(i&&i.type==="listItem"&&typeof i.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const f=i.children;let d=-1,o;for(;++d<f.length;){const m=f[d];if(m.type==="paragraph"){o=m;break}}o===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(n)}function cC(n,i,r,s){const f=n.children[0],d=typeof n.checked=="boolean"&&f&&f.type==="paragraph",o="["+(n.checked?"x":" ")+"] ",m=r.createTracker(s);d&&m.move(o);let g=By.listItem(n,i,r,{...s,...m.current()});return d&&(g=g.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,p)),g;function p(b){return b+o}}function fC(){return[Gk(),cw(),pw(),eC(),sC()]}function dC(n){return{extensions:[Vk(),fw(n),mw(),aC(n),uC()]}}const hC={tokenize:xC,partial:!0},qy={tokenize:vC,partial:!0},Hy={tokenize:SC,partial:!0},Iy={tokenize:jC,partial:!0},pC={tokenize:kC,partial:!0},Yy={name:"wwwAutolink",tokenize:yC,previous:Vy},Gy={name:"protocolAutolink",tokenize:bC,previous:Qy},ul={name:"emailAutolink",tokenize:gC,previous:Xy},Yn={};function mC(){return{text:Yn}}let ti=48;for(;ti<123;)Yn[ti]=ul,ti++,ti===58?ti=65:ti===91&&(ti=97);Yn[43]=ul;Yn[45]=ul;Yn[46]=ul;Yn[95]=ul;Yn[72]=[ul,Gy];Yn[104]=[ul,Gy];Yn[87]=[ul,Yy];Yn[119]=[ul,Yy];function gC(n,i,r){const s=this;let f,d;return o;function o(y){return!Vc(y)||!Xy.call(s,s.previous)||xf(s.events)?r(y):(n.enter("literalAutolink"),n.enter("literalAutolinkEmail"),m(y))}function m(y){return Vc(y)?(n.consume(y),m):y===64?(n.consume(y),g):r(y)}function g(y){return y===46?n.check(pC,b,p)(y):y===45||y===95||Jt(y)?(d=!0,n.consume(y),g):b(y)}function p(y){return n.consume(y),f=!0,g}function b(y){return d&&f&&en(s.previous)?(n.exit("literalAutolinkEmail"),n.exit("literalAutolink"),i(y)):r(y)}}function yC(n,i,r){const s=this;return f;function f(o){return o!==87&&o!==119||!Vy.call(s,s.previous)||xf(s.events)?r(o):(n.enter("literalAutolink"),n.enter("literalAutolinkWww"),n.check(hC,n.attempt(qy,n.attempt(Hy,d),r),r)(o))}function d(o){return n.exit("literalAutolinkWww"),n.exit("literalAutolink"),i(o)}}function bC(n,i,r){const s=this;let f="",d=!1;return o;function o(y){return(y===72||y===104)&&Qy.call(s,s.previous)&&!xf(s.events)?(n.enter("literalAutolink"),n.enter("literalAutolinkHttp"),f+=String.fromCodePoint(y),n.consume(y),m):r(y)}function m(y){if(en(y)&&f.length<5)return f+=String.fromCodePoint(y),n.consume(y),m;if(y===58){const v=f.toLowerCase();if(v==="http"||v==="https")return n.consume(y),g}return r(y)}function g(y){return y===47?(n.consume(y),d?p:(d=!0,g)):r(y)}function p(y){return y===null||zs(y)||xt(y)||li(y)||qs(y)?r(y):n.attempt(qy,n.attempt(Hy,b),r)(y)}function b(y){return n.exit("literalAutolinkHttp"),n.exit("literalAutolink"),i(y)}}function xC(n,i,r){let s=0;return f;function f(o){return(o===87||o===119)&&s<3?(s++,n.consume(o),f):o===46&&s===3?(n.consume(o),d):r(o)}function d(o){return o===null?r(o):i(o)}}function vC(n,i,r){let s,f,d;return o;function o(p){return p===46||p===95?n.check(Iy,g,m)(p):p===null||xt(p)||li(p)||p!==45&&qs(p)?g(p):(d=!0,n.consume(p),o)}function m(p){return p===95?s=!0:(f=s,s=void 0),n.consume(p),o}function g(p){return f||s||!d?r(p):i(p)}}function SC(n,i){let r=0,s=0;return f;function f(o){return o===40?(r++,n.consume(o),f):o===41&&s<r?d(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?n.check(Iy,i,d)(o):o===null||xt(o)||li(o)?i(o):(n.consume(o),f)}function d(o){return o===41&&s++,n.consume(o),f}}function jC(n,i,r){return s;function s(m){return m===33||m===34||m===39||m===41||m===42||m===44||m===46||m===58||m===59||m===63||m===95||m===126?(n.consume(m),s):m===38?(n.consume(m),d):m===93?(n.consume(m),f):m===60||m===null||xt(m)||li(m)?i(m):r(m)}function f(m){return m===null||m===40||m===91||xt(m)||li(m)?i(m):s(m)}function d(m){return en(m)?o(m):r(m)}function o(m){return m===59?(n.consume(m),s):en(m)?(n.consume(m),o):r(m)}}function kC(n,i,r){return s;function s(d){return n.consume(d),f}function f(d){return Jt(d)?r(d):i(d)}}function Vy(n){return n===null||n===40||n===42||n===95||n===91||n===93||n===126||xt(n)}function Qy(n){return!en(n)}function Xy(n){return!(n===47||Vc(n))}function Vc(n){return n===43||n===45||n===46||n===95||Jt(n)}function xf(n){let i=n.length,r=!1;for(;i--;){const s=n[i][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return n.length>0&&!r&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const wC={tokenize:_C,partial:!0};function CC(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:AC,continuation:{tokenize:zC},exit:RC}},text:{91:{name:"gfmFootnoteCall",tokenize:TC},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:EC,resolveTo:NC}}}}function EC(n,i,r){const s=this;let f=s.events.length;const d=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o;for(;f--;){const g=s.events[f][1];if(g.type==="labelImage"){o=g;break}if(g.type==="gfmFootnoteCall"||g.type==="labelLink"||g.type==="label"||g.type==="image"||g.type==="link")break}return m;function m(g){if(!o||!o._balanced)return r(g);const p=Mn(s.sliceSerialize({start:o.end,end:s.now()}));return p.codePointAt(0)!==94||!d.includes(p.slice(1))?r(g):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),i(g))}}function NC(n,i){let r=n.length;for(;r--;)if(n[r][1].type==="labelImage"&&n[r][0]==="enter"){n[r][1];break}n[r+1][1].type="data",n[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},n[r+3][1].start),end:Object.assign({},n[n.length-1][1].end)},f={type:"gfmFootnoteCallMarker",start:Object.assign({},n[r+3][1].end),end:Object.assign({},n[r+3][1].end)};f.end.column++,f.end.offset++,f.end._bufferIndex++;const d={type:"gfmFootnoteCallString",start:Object.assign({},f.end),end:Object.assign({},n[n.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},d.start),end:Object.assign({},d.end)},m=[n[r+1],n[r+2],["enter",s,i],n[r+3],n[r+4],["enter",f,i],["exit",f,i],["enter",d,i],["enter",o,i],["exit",o,i],["exit",d,i],n[n.length-2],n[n.length-1],["exit",s,i]];return n.splice(r,n.length-r+1,...m),n}function TC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d=0,o;return m;function m(y){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),g}function g(y){return y!==94?r(y):(n.enter("gfmFootnoteCallMarker"),n.consume(y),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",p)}function p(y){if(d>999||y===93&&!o||y===null||y===91||xt(y))return r(y);if(y===93){n.exit("chunkString");const v=n.exit("gfmFootnoteCallString");return f.includes(Mn(s.sliceSerialize(v)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),i):r(y)}return xt(y)||(o=!0),d++,n.consume(y),y===92?b:p}function b(y){return y===91||y===92||y===93?(n.consume(y),d++,p):p(y)}}function AC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d,o=0,m;return g;function g(N){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(N){return N===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",b):r(N)}function b(N){if(o>999||N===93&&!m||N===null||N===91||xt(N))return r(N);if(N===93){n.exit("chunkString");const D=n.exit("gfmFootnoteDefinitionLabelString");return d=Mn(s.sliceSerialize(D)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),v}return xt(N)||(m=!0),o++,n.consume(N),N===92?y:b}function y(N){return N===91||N===92||N===93?(n.consume(N),o++,b):b(N)}function v(N){return N===58?(n.enter("definitionMarker"),n.consume(N),n.exit("definitionMarker"),f.includes(d)||f.push(d),tt(n,S,"gfmFootnoteDefinitionWhitespace")):r(N)}function S(N){return i(N)}}function zC(n,i,r){return n.check(ra,i,n.attempt(wC,i,r))}function RC(n){n.exit("gfmFootnoteDefinition")}function _C(n,i,r){const s=this;return tt(n,f,"gfmFootnoteDefinitionIndent",5);function f(d){const o=s.events[s.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?i(d):r(d)}}function DC(n){let r=(n||{}).singleTilde;const s={name:"strikethrough",tokenize:d,resolveAll:f};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function f(o,m){let g=-1;for(;++g<o.length;)if(o[g][0]==="enter"&&o[g][1].type==="strikethroughSequenceTemporary"&&o[g][1]._close){let p=g;for(;p--;)if(o[p][0]==="exit"&&o[p][1].type==="strikethroughSequenceTemporary"&&o[p][1]._open&&o[g][1].end.offset-o[g][1].start.offset===o[p][1].end.offset-o[p][1].start.offset){o[g][1].type="strikethroughSequence",o[p][1].type="strikethroughSequence";const b={type:"strikethrough",start:Object.assign({},o[p][1].start),end:Object.assign({},o[g][1].end)},y={type:"strikethroughText",start:Object.assign({},o[p][1].end),end:Object.assign({},o[g][1].start)},v=[["enter",b,m],["enter",o[p][1],m],["exit",o[p][1],m],["enter",y,m]],S=m.parser.constructs.insideSpan.null;S&&xn(v,v.length,0,Hs(S,o.slice(p+1,g),m)),xn(v,v.length,0,[["exit",y,m],["enter",o[g][1],m],["exit",o[g][1],m],["exit",b,m]]),xn(o,p-1,g-p+3,v),g=p+v.length-2;break}}for(g=-1;++g<o.length;)o[g][1].type==="strikethroughSequenceTemporary"&&(o[g][1].type="data");return o}function d(o,m,g){const p=this.previous,b=this.events;let y=0;return v;function v(N){return p===126&&b[b.length-1][1].type!=="characterEscape"?g(N):(o.enter("strikethroughSequenceTemporary"),S(N))}function S(N){const D=Fi(p);if(N===126)return y>1?g(N):(o.consume(N),y++,S);if(y<2&&!r)return g(N);const z=o.exit("strikethroughSequenceTemporary"),_=Fi(N);return z._open=!_||_===2&&!!D,z._close=!D||D===2&&!!_,m(N)}}}class OC{constructor(){this.map=[]}add(i,r,s){MC(this,i,r,s)}consume(i){if(this.map.sort(function(d,o){return d[0]-o[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(i.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),i.length=this.map[r][0];s.push(i.slice()),i.length=0;let f=s.pop();for(;f;){for(const d of f)i.push(d);f=s.pop()}this.map.length=0}}function MC(n,i,r,s){let f=0;if(!(r===0&&s.length===0)){for(;f<n.map.length;){if(n.map[f][0]===i){n.map[f][1]+=r,n.map[f][2].push(...s);return}f+=1}n.map.push([i,r,s])}}function LC(n,i){let r=!1;const s=[];for(;i<n.length;){const f=n[i];if(r){if(f[0]==="enter")f[1].type==="tableContent"&&s.push(n[i+1][1].type==="tableDelimiterMarker"?"left":"none");else if(f[1].type==="tableContent"){if(n[i-1][1].type==="tableDelimiterMarker"){const d=s.length-1;s[d]=s[d]==="left"?"center":"right"}}else if(f[1].type==="tableDelimiterRow")break}else f[0]==="enter"&&f[1].type==="tableDelimiterRow"&&(r=!0);i+=1}return s}function UC(){return{flow:{null:{name:"table",tokenize:BC,resolveAll:qC}}}}function BC(n,i,r){const s=this;let f=0,d=0,o;return m;function m(A){let G=s.events.length-1;for(;G>-1;){const ae=s.events[G][1].type;if(ae==="lineEnding"||ae==="linePrefix")G--;else break}const V=G>-1?s.events[G][1].type:null,se=V==="tableHead"||V==="tableRow"?R:g;return se===R&&s.parser.lazy[s.now().line]?r(A):se(A)}function g(A){return n.enter("tableHead"),n.enter("tableRow"),p(A)}function p(A){return A===124||(o=!0,d+=1),b(A)}function b(A){return A===null?r(A):Me(A)?d>1?(d=0,s.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(A),n.exit("lineEnding"),S):r(A):Ze(A)?tt(n,b,"whitespace")(A):(d+=1,o&&(o=!1,f+=1),A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),o=!0,b):(n.enter("data"),y(A)))}function y(A){return A===null||A===124||xt(A)?(n.exit("data"),b(A)):(n.consume(A),A===92?v:y)}function v(A){return A===92||A===124?(n.consume(A),y):y(A)}function S(A){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(A):(n.enter("tableDelimiterRow"),o=!1,Ze(A)?tt(n,N,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):N(A))}function N(A){return A===45||A===58?z(A):A===124?(o=!0,n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),D):ce(A)}function D(A){return Ze(A)?tt(n,z,"whitespace")(A):z(A)}function z(A){return A===58?(d+=1,o=!0,n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),_):A===45?(d+=1,_(A)):A===null||Me(A)?oe(A):ce(A)}function _(A){return A===45?(n.enter("tableDelimiterFiller"),M(A)):ce(A)}function M(A){return A===45?(n.consume(A),M):A===58?(o=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),H):(n.exit("tableDelimiterFiller"),H(A))}function H(A){return Ze(A)?tt(n,oe,"whitespace")(A):oe(A)}function oe(A){return A===124?N(A):A===null||Me(A)?!o||f!==d?ce(A):(n.exit("tableDelimiterRow"),n.exit("tableHead"),i(A)):ce(A)}function ce(A){return r(A)}function R(A){return n.enter("tableRow"),W(A)}function W(A){return A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),W):A===null||Me(A)?(n.exit("tableRow"),i(A)):Ze(A)?tt(n,W,"whitespace")(A):(n.enter("data"),ie(A))}function ie(A){return A===null||A===124||xt(A)?(n.exit("data"),W(A)):(n.consume(A),A===92?F:ie)}function F(A){return A===92||A===124?(n.consume(A),ie):ie(A)}}function qC(n,i){let r=-1,s=!0,f=0,d=[0,0,0,0],o=[0,0,0,0],m=!1,g=0,p,b,y;const v=new OC;for(;++r<n.length;){const S=n[r],N=S[1];S[0]==="enter"?N.type==="tableHead"?(m=!1,g!==0&&(wg(v,i,g,p,b),b=void 0,g=0),p={type:"table",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",p,i]])):N.type==="tableRow"||N.type==="tableDelimiterRow"?(s=!0,y=void 0,d=[0,0,0,0],o=[0,r+1,0,0],m&&(m=!1,b={type:"tableBody",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",b,i]])),f=N.type==="tableDelimiterRow"?2:b?3:1):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")?(s=!1,o[2]===0&&(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y),d=[0,0,0,0]),o[2]=r)):N.type==="tableCellDivider"&&(s?s=!1:(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y)),d=o,o=[d[1],r,0,0])):N.type==="tableHead"?(m=!0,g=r):N.type==="tableRow"||N.type==="tableDelimiterRow"?(g=r,d[1]!==0?(o[0]=o[1],y=Cs(v,i,d,f,r,y)):o[1]!==0&&(y=Cs(v,i,o,f,r,y)),f=0):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")&&(o[3]=r)}for(g!==0&&wg(v,i,g,p,b),v.consume(i.events),r=-1;++r<i.events.length;){const S=i.events[r];S[0]==="enter"&&S[1].type==="table"&&(S[1]._align=LC(i.events,r))}return n}function Cs(n,i,r,s,f,d){const o=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",m="tableContent";r[0]!==0&&(d.end=Object.assign({},Ki(i.events,r[0])),n.add(r[0],0,[["exit",d,i]]));const g=Ki(i.events,r[1]);if(d={type:o,start:Object.assign({},g),end:Object.assign({},g)},n.add(r[1],0,[["enter",d,i]]),r[2]!==0){const p=Ki(i.events,r[2]),b=Ki(i.events,r[3]),y={type:m,start:Object.assign({},p),end:Object.assign({},b)};if(n.add(r[2],0,[["enter",y,i]]),s!==2){const v=i.events[r[2]],S=i.events[r[3]];if(v[1].end=Object.assign({},S[1].end),v[1].type="chunkText",v[1].contentType="text",r[3]>r[2]+1){const N=r[2]+1,D=r[3]-r[2]-1;n.add(N,D,[])}}n.add(r[3]+1,0,[["exit",y,i]])}return f!==void 0&&(d.end=Object.assign({},Ki(i.events,f)),n.add(f,0,[["exit",d,i]]),d=void 0),d}function wg(n,i,r,s,f){const d=[],o=Ki(i.events,r);f&&(f.end=Object.assign({},o),d.push(["exit",f,i])),s.end=Object.assign({},o),d.push(["exit",s,i]),n.add(r+1,0,d)}function Ki(n,i){const r=n[i],s=r[0]==="enter"?"start":"end";return r[1][s]}const HC={name:"tasklistCheck",tokenize:YC};function IC(){return{text:{91:HC}}}function YC(n,i,r){const s=this;return f;function f(g){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(g):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),d)}function d(g){return xt(g)?(n.enter("taskListCheckValueUnchecked"),n.consume(g),n.exit("taskListCheckValueUnchecked"),o):g===88||g===120?(n.enter("taskListCheckValueChecked"),n.consume(g),n.exit("taskListCheckValueChecked"),o):r(g)}function o(g){return g===93?(n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),m):r(g)}function m(g){return Me(g)?i(g):Ze(g)?n.check({tokenize:GC},i,r)(g):r(g)}}function GC(n,i,r){return tt(n,s,"whitespace");function s(f){return f===null?r(f):i(f)}}function VC(n){return ly([mC(),CC(),DC(n),UC(),IC()])}const QC={};function XC(n){const i=this,r=n||QC,s=i.data(),f=s.micromarkExtensions||(s.micromarkExtensions=[]),d=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),o=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);f.push(VC(r)),d.push(fC()),o.push(dC(r))}function Qc(n){const i=n.trim();if(!(!i||/[\u0000-\u0020\u007f]/.test(i)))try{const r=new URL(i);if(r.protocol==="https:"||r.protocol==="http:"||r.protocol==="mailto:")return i}catch{}}function Xc(n){return!!n&&!/[\u0000-\u001f\u007f]/.test(n)&&!/^[a-z][a-z\d+.-]*:/i.test(n)&&!n.startsWith("//")}function Cg(n){if(!Xc(n))return;const i=n.split(/[?#]/,1)[0];if(i)try{const r=decodeURIComponent(i);return Xc(r)?r:void 0}catch{return}}async function ZC(n){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(n);return}const i=document.activeElement,r=document.createElement("textarea");r.value=n,r.setAttribute("aria-label","复制内容"),r.style.cssText="position:fixed;left:-10000px;top:0",document.body.append(r);try{if(r.select(),!document.execCommand("copy"))throw new Error("复制不可用")}finally{r.remove(),i instanceof HTMLElement&&i.focus({preventScroll:!0})}}function Vs({text:n,label:i="复制"}){const[r,s]=w.useState("idle"),f=w.useRef(!0),d=w.useRef(void 0);w.useEffect(()=>(f.current=!0,()=>{f.current=!1,clearTimeout(d.current)}),[]);const o=async()=>{clearTimeout(d.current);try{await ZC(n),f.current&&s("copied")}catch{f.current&&s("error")}f.current&&(d.current=setTimeout(()=>s("idle"),2500))};return u.jsx("button",{className:"message-copy",onClick:()=>{o()},"aria-label":i,title:i,children:r==="copied"?"已复制":r==="error"?"复制失败":i})}function Zc(n){return typeof n=="string"||typeof n=="number"?String(n):Array.isArray(n)?n.map(Zc).join(""):w.isValidElement(n)?Zc(n.props.children):""}function KC({children:n}){const i=w.Children.toArray(n).find(d=>w.isValidElement(d)),s=(w.isValidElement(i)?i.props.className??"":"").match(/(?:^|\s)language-([\w+-]+)/)?.[1]??"代码",f=Zc(n).replace(/\n$/,"");return u.jsxs("div",{className:"message-code-block",children:[u.jsxs("div",{className:"message-code-heading",children:[u.jsx("span",{children:s}),u.jsx(Vs,{text:f,label:"复制代码"})]}),u.jsx("pre",{tabIndex:0,children:n})]})}function FC(n){return{a:({href:i,children:r,title:s})=>{const f=Qc(i??"");if(f)return u.jsx("a",{href:f,title:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:r});const d=i?Cg(i):void 0;return d?u.jsxs("span",{className:"message-file-reference",title:d,children:[n?u.jsx("button",{className:"message-file-open",onClick:()=>n(d),children:r}):r,u.jsx(Vs,{text:d,label:"复制路径"})]}):u.jsx("span",{children:r})},img:({src:i,alt:r})=>{const s=Qc(typeof i=="string"?i:""),f=typeof i=="string"?Cg(i):void 0;return s?u.jsxs("a",{className:"message-image-reference",href:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:[r||"图片",u.jsx("span",{children:"打开图片 ↗"})]}):f&&n?u.jsxs("button",{className:"message-image-reference",title:f,onClick:()=>n(f),children:[r||"图片",u.jsx("span",{children:"查看图片"})]}):u.jsxs("span",{className:"message-image-reference",children:[r||"图片",u.jsx("span",{children:"图片路径不可直接访问"})]})},pre:({children:i})=>u.jsx(KC,{children:i}),table:({children:i})=>u.jsx("div",{className:"message-table-scroll",role:"region","aria-label":"表格",tabIndex:0,children:u.jsx("table",{children:i})})}}const $C=w.memo(function({text:i,reasoning:r="",streaming:s=!1,onOpenFile:f}){const d=w.useMemo(()=>FC(f),[f]);return u.jsxs("div",{className:"message-content",children:[r?u.jsxs("details",{className:"message-reasoning",children:[u.jsx("summary",{children:s&&!i?"思考中…":"思考过程"}),u.jsx("pre",{children:r})]}):null,s?u.jsxs("div",{className:"message-streaming",children:[i||(r?"":"正在思考…"),u.jsx("span",{className:"cursor","aria-hidden":"true",children:"▍"})]}):i?u.jsx(Dk,{remarkPlugins:[XC],skipHtml:!0,urlTransform:o=>Qc(o)??(Xc(o)?o:""),components:d,children:i}):null,!s&&i?u.jsx("div",{className:"message-actions",children:u.jsx(Vs,{text:i,label:"复制回复"})}):null]})});function JC(n){const i=n.args??{},r=n.summary||[i.description,i.command,i.file_path,i.path,i.query,i.url].find(s=>typeof s=="string"&&s.trim());return typeof r=="string"?r.replace(/\s+/g," ").slice(0,180):""}const PC=w.memo(function({item:i,running:r}){const s=JC(i),f=i.done?i.error?"失败":"已完成":r?"执行中":"未完成";return u.jsxs("details",{className:`message-tool-card${i.error?" message-tool-error":""}`,children:[u.jsxs("summary",{children:[u.jsx("span",{className:"message-tool-indicator","aria-hidden":"true",children:i.done?i.error?"!":"✓":"·"}),u.jsx("span",{className:"message-tool-name",children:i.name}),u.jsx("span",{className:"message-tool-summary",children:s}),u.jsx("span",{className:"message-tool-status",children:f})]}),i.args&&Object.keys(i.args).length?u.jsxs("div",{className:"message-tool-section",children:[u.jsx("strong",{children:"参数"}),u.jsx("pre",{tabIndex:0,children:JSON.stringify(i.args,null,2)})]}):null,u.jsxs("div",{className:"message-tool-section",children:[u.jsxs("div",{className:"message-tool-result-heading",children:[u.jsx("strong",{children:"结果"}),i.result?u.jsx(Vs,{text:i.result,label:"复制结果"}):null]}),u.jsx("pre",{tabIndex:0,children:i.result??(i.done?"工具没有返回文本内容。":r?"等待工具返回结果…":"这次工具调用没有保存结果。")})]})]})});function WC(n){return{running:"运行中",completed:"已完成",error:"失败",recorded:"历史记录"}[n]??n}function Eg(n){return n.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"")}function As(){return{items:[],run:"idle",seq:0,liveByAgent:{}}}function Kr(n){return n.agentId??""}function Es(n,i,r=!1){const s=i.goalId;if(n.goalId!==s&&!(r&&n.goalId===void 0&&s!==void 0))return!0;const f=i.revision;return n.goalRevision!==void 0&&(f===void 0||f<n.goalRevision)}function eE(n){switch(n){case"aborted_streaming":case"aborted_tools":return"idle";case"prompt_too_long":case"model_error":case"image_error":return"error";default:return"completed"}}function tE(n){if(!n||typeof n!="object")return null;const i=n;if(i.method==="agent/streamEvent"&&i.params&&typeof i.params=="object"){const r=i.params;if(r.event&&typeof r.event=="object")return{event:r.event,sessionId:typeof r.sessionId=="string"?r.sessionId:void 0}}return typeof i.type=="string"?{event:i}:null}function Os(n,i){const r=tE(i);if(!r)return n;const{event:s,sessionId:f}=r,d=s.type;let o=n;f&&f!==o.sessionId&&(o={...o,sessionId:f});const m=g=>{const p=o.seq+1;return[`${g}-${p}`,{...o,seq:p}]};switch(d){case"stream_request_start":{const g=Kr(s),[p,b]=m("a"),y={kind:"assistant",id:p,text:"",reasoning:"",done:!1,agentId:s.agentId,...typeof s.messageId=="string"?{messageId:s.messageId}:{}};return{...b,items:[...b.items,y],liveByAgent:{...b.liveByAgent,[g]:p},run:"running"}}case"text_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.find(D=>D.id===b&&D.kind==="assistant"))return{...o,run:"running",items:o.items.map(D=>D.id===b&&D.kind==="assistant"?{...D,text:D.text+g}:D)};const[v,S]=m("a"),N={kind:"assistant",id:v,text:g,reasoning:"",done:!1,agentId:s.agentId};return{...S,items:[...S.items,N],liveByAgent:{...S.liveByAgent,[p]:v},run:"running"}}case"thinking_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.some(N=>N.id===b&&N.kind==="assistant"))return{...o,run:"running",items:o.items.map(N=>N.id===b&&N.kind==="assistant"?{...N,reasoning:N.reasoning+g}:N)};const[y,v]=m("a"),S={kind:"assistant",id:y,text:"",reasoning:g,done:!1,agentId:s.agentId};return{...v,items:[...v.items,S],liveByAgent:{...v.liveByAgent,[p]:y},run:"running"}}case"tool_use_start":{const g=s.toolCall;if(!g||o.items.some(v=>v.kind==="tool"&&v.id===g.id))return o;const p=o.orphanResults?.[g.id],b={kind:"tool",id:g.id,name:g.toolName,args:g.args,summary:g.summary,done:!!p,result:p?.result,error:p?.error,agentId:s.agentId};let y=o.orphanResults;if(p){const{[g.id]:v,...S}=o.orphanResults;y=Object.keys(S).length>0?S:void 0}return{...o,run:"running",items:[...o.items,b],orphanResults:y}}case"tool_use_args_delta":{const g=s.toolCallId,p=s.args;return!g||!p?o:{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g?{...b,args:{...b.args??{},...p}}:b)}}case"tool_result":{const g=s.result;return g?o.items.some(b=>b.kind==="tool"&&b.id===g.id)?{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g.id?{...b,done:!0,result:Eg(g.result??g.error??""),error:!!(g.isError||g.error)}:b)}:{...o,orphanResults:{...o.orphanResults??{},[g.id]:{result:g.result??g.error??"",error:!!(g.isError||g.error)}}}:o}case"room_tool_result":{const g=s.summary??"",p=Eg(g),b=!!s.isError;let y=-1;for(let N=o.items.length-1;N>=0;N--)if(o.items[N].kind==="tool"&&!o.items[N].done){y=N;break}if(y===-1)return o;const v=o.items.slice(),S=v[y];return v[y]={...S,done:!0,result:p,summary:p||S.summary,error:b},{...o,items:v}}case"tool_summary":{const g=s.summary??"",p=Array.isArray(s.toolCallIds)?s.toolCallIds.filter(D=>typeof D=="string"):[],y=p.length>0?p[p.length-1]:void 0,v=s.agentId;if(y){let D=!1;const z=o.items.map(_=>_.kind!=="tool"||_.id!==y||_.agentId!==v?_:(D=!0,{..._,summary:g}));return D?{...o,items:z}:o}if(v){let D=-1;for(let _=o.items.length-1;_>=0;_--){const M=o.items[_];if(M.kind==="tool"&&M.agentId===v){D=_;break}}if(D===-1)return o;const z=o.items.slice();return z[D]={...z[D],summary:g},{...o,items:z}}let S=-1;for(let D=o.items.length-1;D>=0;D--){const z=o.items[D];if(z.kind==="tool"&&z.agentId===void 0){S=D;break}}if(S===-1)return o;const N=o.items.slice();return N[S]={...N[S],summary:g},{...o,items:N}}case"tombstone":{if(typeof s.messageId!="string")return o;const g=new Set(o.items.filter(p=>p.kind==="assistant"&&p.messageId===s.messageId||p.kind==="tool"&&p.id===s.messageId).map(p=>p.id));return g.size?{...o,items:o.items.filter(p=>!g.has(p.id)),liveByAgent:Object.fromEntries(Object.entries(o.liveByAgent).filter(([,p])=>!g.has(p)))}:o}case"assistant_message":{const g=Kr(s);if(!(g in o.liveByAgent))return o;const{[g]:p,...b}=o.liveByAgent,y=o.items.map(v=>v.kind==="assistant"&&!v.done&&(v.agentId??"")===g?{...v,done:!0}:v);return{...o,liveByAgent:b,items:y}}case"turn_complete":{const g=s.reason??"completed",p=Kr(s),{[p]:b,...y}=o.liveByAgent,v=o.items.map(S=>S.kind==="assistant"&&!S.done&&(S.agentId??"")===p?{...S,done:!0}:S);return s.agentId?{...o,liveByAgent:y,items:v}:{...o,liveByAgent:y,items:v,run:eE(g)}}case"goal_set":{const g=s.objective??"",p=!!s.paused;return o.goal&&o.goalId===s.goalId&&Es(o,s)?o:{...o,goal:g?`◎ ${g}${p?" (已暂停)":""}`:"◎ 目标",goalId:s.goalId,goalPaused:p,goalRevision:s.revision}}case"goal_updated":{if(o.goal&&Es(o,s,!0))return o;const g=s.goalId,p=s.objective??"",b=!!s.paused;return{...o,goal:p?`◎ ${p}${b?" (已暂停)":""}`:o.goal,goalId:g??o.goalId,goalPaused:b,goalRevision:s.revision??o.goalRevision}}case"goal_cleared":return o.goal&&Es(o,s)?o:{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};case"goal_progress":{if(o.goal&&Es(o,s))return o;const g=s.status??"";if(g==="met"||g==="exhausted")return{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};const p=s.round,b=p?`目标 · 第 ${p} 轮 (${g})`:`目标 (${g})`;return{...o,goal:b,goalRevision:s.revision??o.goalRevision}}case"task_update":{const g=s.agentId;if(!g)return o;const p=s.tasks??[],b=p.filter(N=>N.status==="completed").length,y=`任务 ${b}/${p.length}`,v=o.items.findIndex(N=>N.kind==="subagent"&&N.agentId===g),S={kind:"subagent",id:`sub-${g}`,agentId:g,label:y,status:p.length>0&&b===p.length?"completed":"running"};if(v>=0){const N=o.items.slice();return N[v]=S,{...o,items:N}}return{...o,items:[...o.items,S]}}case"agent_start":{const g=s.agentId;if(!g)return o;const p={kind:"subagent",id:`sub-${g}`,agentId:g,label:s.name||s.description||"子代理",status:s.status==="recorded"?"recorded":"running"};return o.items.some(b=>b.kind==="subagent"&&b.agentId===g)?o:{...o,items:[...o.items,p]}}case"agent_end":{const g=s.agentId;return{...o,items:o.items.map(p=>p.kind==="subagent"&&p.agentId===g?{...p,status:s.error?"error":"completed"}:p)}}case"error":{const[g,p]=m("err");return{...p,run:"error",liveByAgent:{},items:[...p.items,{kind:"system_error",id:g,text:s.error||"运行出错"}]}}case"session_title":return{...o,title:s.title};case"session_user_message":case"user_message":{const g=typeof s.clientMessageId=="string"?s.clientMessageId:void 0,p=Array.isArray(s.attachments)?s.attachments.map(v=>v).filter(v=>!!v&&typeof v.name=="string"&&typeof v.size=="number"&&Number.isFinite(v.size)&&v.size>=0).map(v=>({name:v.name,size:v.size,...typeof v.mime=="string"?{mime:v.mime}:{},...typeof v.path=="string"?{path:v.path}:{}})):void 0;if(g&&o.items.some(v=>v.kind==="user"&&v.clientMessageId===g))return p?.length?{...o,items:o.items.map(v=>v.kind==="user"&&v.clientMessageId===g?{...v,attachments:p.map((S,N)=>{const D=v.attachments?.[N];return D?.name===S.name?{...D,...S}:S})}:v)}:o;const[b,y]=m("u");return{...y,items:[...y.items,{kind:"user",id:b,text:s.text??"",...p?.length?{attachments:p}:{},...g?{clientMessageId:g}:{}}]}}case"assistant_text":{const[g,p]=m("a");return{...p,run:"running",items:[...p.items,{kind:"assistant",id:g,text:s.text??"",reasoning:"",done:!0,agentId:s.agentId}]}}default:return o}}function nE(n,i,r,s){const f=`u-${n.seq+1}`;return{...n,seq:n.seq+1,items:[...n.items,{kind:"user",id:f,text:i,...r?.length?{attachments:r}:{},...s?{clientMessageId:s}:{}}]}}function On(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function yt(n){return typeof n=="string"?n:""}function Ms(n){return Array.isArray(n)?n.map(On).filter(i=>i!==void 0):[]}function Kc(n){return typeof n=="string"?n:Ms(n).filter(i=>i.type==="text").map(i=>yt(i.text)).join("")}function Ns(n){return n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Rc(n){const i=n.replace(/\\/g,"/").split("/").filter(Boolean).pop()||"附件";return n.includes(".code-shell/attachments/")?i.replace(/^[a-f0-9]{16}-/,""):i}function Ng(n){const i=typeof n=="number"?n:Number(n);return Number.isSafeInteger(i)&&i>=0?i:0}function lE(n){const i=[],r=[];let s=Kc(n.content);s=s.replace(/<attached-file\s+path="([^"]*)">\s*([\s\S]*?)<\/attached-file>/g,(o,m,g)=>{if(!/^absolutePath:\s*.+$/m.test(g)||!/^origin:\s*.+$/m.test(g))return o;const p=g.match(/^mime:\s*(.+)$/m)?.[1]?.trim();return i.push({name:Rc(Ns(m)),path:Ns(m),size:Ng(g.match(/^size:\s*(\d+)\s*$/m)?.[1]),...p?{mime:p}:{}}),""}),s=s.replace(/<attached-directory\s+path="([^"]*)"[^>]*>[\s\S]*?<\/attached-directory>/g,(o,m)=>(i.push({name:`${Rc(Ns(m))}/`,path:Ns(m),size:0}),"")),s=s.replace(/<attached-image-paths>\s*([\s\S]*?)<\/attached-image-paths>\s*(?:\(上面附带的图片在工作区的真实路径[^\n]*\))?/g,(o,m)=>(r.push(...m.split(`
48
+ `))}function g(S,N,D,z){const _=D.enter("tableCell"),M=D.enter("phrasing"),H=D.containerPhrasing(S,{...z,before:d,after:d});return M(),_(),H}function p(S,N){return vw(S,{align:N,alignDelimiters:s,padding:r,stringLength:f})}function b(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("table");for(;++_<z.length;)M[_]=y(z[_],N,D);return H(),M}function y(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("tableRow");for(;++_<z.length;)M[_]=g(z[_],S,N,D);return H(),M}function v(S,N,D){let z=By.inlineCode(S,N,D);return D.stack.includes("tableCell")&&(z=z.replace(/\|/g,"\\$&")),z}}function sC(){return{exit:{taskListCheckValueChecked:kg,taskListCheckValueUnchecked:kg,paragraph:oC}}}function uC(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:cC}}}function kg(n){const i=this.stack[this.stack.length-2];i.type,i.checked=n.type==="taskListCheckValueChecked"}function oC(n){const i=this.stack[this.stack.length-2];if(i&&i.type==="listItem"&&typeof i.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const f=i.children;let d=-1,o;for(;++d<f.length;){const m=f[d];if(m.type==="paragraph"){o=m;break}}o===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(n)}function cC(n,i,r,s){const f=n.children[0],d=typeof n.checked=="boolean"&&f&&f.type==="paragraph",o="["+(n.checked?"x":" ")+"] ",m=r.createTracker(s);d&&m.move(o);let g=By.listItem(n,i,r,{...s,...m.current()});return d&&(g=g.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,p)),g;function p(b){return b+o}}function fC(){return[Gk(),cw(),pw(),eC(),sC()]}function dC(n){return{extensions:[Vk(),fw(n),mw(),aC(n),uC()]}}const hC={tokenize:xC,partial:!0},qy={tokenize:vC,partial:!0},Hy={tokenize:SC,partial:!0},Iy={tokenize:jC,partial:!0},pC={tokenize:kC,partial:!0},Yy={name:"wwwAutolink",tokenize:yC,previous:Vy},Gy={name:"protocolAutolink",tokenize:bC,previous:Qy},ul={name:"emailAutolink",tokenize:gC,previous:Xy},Yn={};function mC(){return{text:Yn}}let ti=48;for(;ti<123;)Yn[ti]=ul,ti++,ti===58?ti=65:ti===91&&(ti=97);Yn[43]=ul;Yn[45]=ul;Yn[46]=ul;Yn[95]=ul;Yn[72]=[ul,Gy];Yn[104]=[ul,Gy];Yn[87]=[ul,Yy];Yn[119]=[ul,Yy];function gC(n,i,r){const s=this;let f,d;return o;function o(y){return!Vc(y)||!Xy.call(s,s.previous)||xf(s.events)?r(y):(n.enter("literalAutolink"),n.enter("literalAutolinkEmail"),m(y))}function m(y){return Vc(y)?(n.consume(y),m):y===64?(n.consume(y),g):r(y)}function g(y){return y===46?n.check(pC,b,p)(y):y===45||y===95||Jt(y)?(d=!0,n.consume(y),g):b(y)}function p(y){return n.consume(y),f=!0,g}function b(y){return d&&f&&en(s.previous)?(n.exit("literalAutolinkEmail"),n.exit("literalAutolink"),i(y)):r(y)}}function yC(n,i,r){const s=this;return f;function f(o){return o!==87&&o!==119||!Vy.call(s,s.previous)||xf(s.events)?r(o):(n.enter("literalAutolink"),n.enter("literalAutolinkWww"),n.check(hC,n.attempt(qy,n.attempt(Hy,d),r),r)(o))}function d(o){return n.exit("literalAutolinkWww"),n.exit("literalAutolink"),i(o)}}function bC(n,i,r){const s=this;let f="",d=!1;return o;function o(y){return(y===72||y===104)&&Qy.call(s,s.previous)&&!xf(s.events)?(n.enter("literalAutolink"),n.enter("literalAutolinkHttp"),f+=String.fromCodePoint(y),n.consume(y),m):r(y)}function m(y){if(en(y)&&f.length<5)return f+=String.fromCodePoint(y),n.consume(y),m;if(y===58){const v=f.toLowerCase();if(v==="http"||v==="https")return n.consume(y),g}return r(y)}function g(y){return y===47?(n.consume(y),d?p:(d=!0,g)):r(y)}function p(y){return y===null||zs(y)||xt(y)||li(y)||qs(y)?r(y):n.attempt(qy,n.attempt(Hy,b),r)(y)}function b(y){return n.exit("literalAutolinkHttp"),n.exit("literalAutolink"),i(y)}}function xC(n,i,r){let s=0;return f;function f(o){return(o===87||o===119)&&s<3?(s++,n.consume(o),f):o===46&&s===3?(n.consume(o),d):r(o)}function d(o){return o===null?r(o):i(o)}}function vC(n,i,r){let s,f,d;return o;function o(p){return p===46||p===95?n.check(Iy,g,m)(p):p===null||xt(p)||li(p)||p!==45&&qs(p)?g(p):(d=!0,n.consume(p),o)}function m(p){return p===95?s=!0:(f=s,s=void 0),n.consume(p),o}function g(p){return f||s||!d?r(p):i(p)}}function SC(n,i){let r=0,s=0;return f;function f(o){return o===40?(r++,n.consume(o),f):o===41&&s<r?d(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?n.check(Iy,i,d)(o):o===null||xt(o)||li(o)?i(o):(n.consume(o),f)}function d(o){return o===41&&s++,n.consume(o),f}}function jC(n,i,r){return s;function s(m){return m===33||m===34||m===39||m===41||m===42||m===44||m===46||m===58||m===59||m===63||m===95||m===126?(n.consume(m),s):m===38?(n.consume(m),d):m===93?(n.consume(m),f):m===60||m===null||xt(m)||li(m)?i(m):r(m)}function f(m){return m===null||m===40||m===91||xt(m)||li(m)?i(m):s(m)}function d(m){return en(m)?o(m):r(m)}function o(m){return m===59?(n.consume(m),s):en(m)?(n.consume(m),o):r(m)}}function kC(n,i,r){return s;function s(d){return n.consume(d),f}function f(d){return Jt(d)?r(d):i(d)}}function Vy(n){return n===null||n===40||n===42||n===95||n===91||n===93||n===126||xt(n)}function Qy(n){return!en(n)}function Xy(n){return!(n===47||Vc(n))}function Vc(n){return n===43||n===45||n===46||n===95||Jt(n)}function xf(n){let i=n.length,r=!1;for(;i--;){const s=n[i][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return n.length>0&&!r&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const wC={tokenize:_C,partial:!0};function CC(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:AC,continuation:{tokenize:zC},exit:RC}},text:{91:{name:"gfmFootnoteCall",tokenize:TC},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:EC,resolveTo:NC}}}}function EC(n,i,r){const s=this;let f=s.events.length;const d=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o;for(;f--;){const g=s.events[f][1];if(g.type==="labelImage"){o=g;break}if(g.type==="gfmFootnoteCall"||g.type==="labelLink"||g.type==="label"||g.type==="image"||g.type==="link")break}return m;function m(g){if(!o||!o._balanced)return r(g);const p=Mn(s.sliceSerialize({start:o.end,end:s.now()}));return p.codePointAt(0)!==94||!d.includes(p.slice(1))?r(g):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),i(g))}}function NC(n,i){let r=n.length;for(;r--;)if(n[r][1].type==="labelImage"&&n[r][0]==="enter"){n[r][1];break}n[r+1][1].type="data",n[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},n[r+3][1].start),end:Object.assign({},n[n.length-1][1].end)},f={type:"gfmFootnoteCallMarker",start:Object.assign({},n[r+3][1].end),end:Object.assign({},n[r+3][1].end)};f.end.column++,f.end.offset++,f.end._bufferIndex++;const d={type:"gfmFootnoteCallString",start:Object.assign({},f.end),end:Object.assign({},n[n.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},d.start),end:Object.assign({},d.end)},m=[n[r+1],n[r+2],["enter",s,i],n[r+3],n[r+4],["enter",f,i],["exit",f,i],["enter",d,i],["enter",o,i],["exit",o,i],["exit",d,i],n[n.length-2],n[n.length-1],["exit",s,i]];return n.splice(r,n.length-r+1,...m),n}function TC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d=0,o;return m;function m(y){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),g}function g(y){return y!==94?r(y):(n.enter("gfmFootnoteCallMarker"),n.consume(y),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",p)}function p(y){if(d>999||y===93&&!o||y===null||y===91||xt(y))return r(y);if(y===93){n.exit("chunkString");const v=n.exit("gfmFootnoteCallString");return f.includes(Mn(s.sliceSerialize(v)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),i):r(y)}return xt(y)||(o=!0),d++,n.consume(y),y===92?b:p}function b(y){return y===91||y===92||y===93?(n.consume(y),d++,p):p(y)}}function AC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d,o=0,m;return g;function g(N){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(N){return N===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",b):r(N)}function b(N){if(o>999||N===93&&!m||N===null||N===91||xt(N))return r(N);if(N===93){n.exit("chunkString");const D=n.exit("gfmFootnoteDefinitionLabelString");return d=Mn(s.sliceSerialize(D)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),v}return xt(N)||(m=!0),o++,n.consume(N),N===92?y:b}function y(N){return N===91||N===92||N===93?(n.consume(N),o++,b):b(N)}function v(N){return N===58?(n.enter("definitionMarker"),n.consume(N),n.exit("definitionMarker"),f.includes(d)||f.push(d),tt(n,S,"gfmFootnoteDefinitionWhitespace")):r(N)}function S(N){return i(N)}}function zC(n,i,r){return n.check(ra,i,n.attempt(wC,i,r))}function RC(n){n.exit("gfmFootnoteDefinition")}function _C(n,i,r){const s=this;return tt(n,f,"gfmFootnoteDefinitionIndent",5);function f(d){const o=s.events[s.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?i(d):r(d)}}function DC(n){let r=(n||{}).singleTilde;const s={name:"strikethrough",tokenize:d,resolveAll:f};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function f(o,m){let g=-1;for(;++g<o.length;)if(o[g][0]==="enter"&&o[g][1].type==="strikethroughSequenceTemporary"&&o[g][1]._close){let p=g;for(;p--;)if(o[p][0]==="exit"&&o[p][1].type==="strikethroughSequenceTemporary"&&o[p][1]._open&&o[g][1].end.offset-o[g][1].start.offset===o[p][1].end.offset-o[p][1].start.offset){o[g][1].type="strikethroughSequence",o[p][1].type="strikethroughSequence";const b={type:"strikethrough",start:Object.assign({},o[p][1].start),end:Object.assign({},o[g][1].end)},y={type:"strikethroughText",start:Object.assign({},o[p][1].end),end:Object.assign({},o[g][1].start)},v=[["enter",b,m],["enter",o[p][1],m],["exit",o[p][1],m],["enter",y,m]],S=m.parser.constructs.insideSpan.null;S&&xn(v,v.length,0,Hs(S,o.slice(p+1,g),m)),xn(v,v.length,0,[["exit",y,m],["enter",o[g][1],m],["exit",o[g][1],m],["exit",b,m]]),xn(o,p-1,g-p+3,v),g=p+v.length-2;break}}for(g=-1;++g<o.length;)o[g][1].type==="strikethroughSequenceTemporary"&&(o[g][1].type="data");return o}function d(o,m,g){const p=this.previous,b=this.events;let y=0;return v;function v(N){return p===126&&b[b.length-1][1].type!=="characterEscape"?g(N):(o.enter("strikethroughSequenceTemporary"),S(N))}function S(N){const D=Fi(p);if(N===126)return y>1?g(N):(o.consume(N),y++,S);if(y<2&&!r)return g(N);const z=o.exit("strikethroughSequenceTemporary"),_=Fi(N);return z._open=!_||_===2&&!!D,z._close=!D||D===2&&!!_,m(N)}}}class OC{constructor(){this.map=[]}add(i,r,s){MC(this,i,r,s)}consume(i){if(this.map.sort(function(d,o){return d[0]-o[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(i.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),i.length=this.map[r][0];s.push(i.slice()),i.length=0;let f=s.pop();for(;f;){for(const d of f)i.push(d);f=s.pop()}this.map.length=0}}function MC(n,i,r,s){let f=0;if(!(r===0&&s.length===0)){for(;f<n.map.length;){if(n.map[f][0]===i){n.map[f][1]+=r,n.map[f][2].push(...s);return}f+=1}n.map.push([i,r,s])}}function LC(n,i){let r=!1;const s=[];for(;i<n.length;){const f=n[i];if(r){if(f[0]==="enter")f[1].type==="tableContent"&&s.push(n[i+1][1].type==="tableDelimiterMarker"?"left":"none");else if(f[1].type==="tableContent"){if(n[i-1][1].type==="tableDelimiterMarker"){const d=s.length-1;s[d]=s[d]==="left"?"center":"right"}}else if(f[1].type==="tableDelimiterRow")break}else f[0]==="enter"&&f[1].type==="tableDelimiterRow"&&(r=!0);i+=1}return s}function UC(){return{flow:{null:{name:"table",tokenize:BC,resolveAll:qC}}}}function BC(n,i,r){const s=this;let f=0,d=0,o;return m;function m(A){let G=s.events.length-1;for(;G>-1;){const ae=s.events[G][1].type;if(ae==="lineEnding"||ae==="linePrefix")G--;else break}const V=G>-1?s.events[G][1].type:null,se=V==="tableHead"||V==="tableRow"?R:g;return se===R&&s.parser.lazy[s.now().line]?r(A):se(A)}function g(A){return n.enter("tableHead"),n.enter("tableRow"),p(A)}function p(A){return A===124||(o=!0,d+=1),b(A)}function b(A){return A===null?r(A):Me(A)?d>1?(d=0,s.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(A),n.exit("lineEnding"),S):r(A):Ze(A)?tt(n,b,"whitespace")(A):(d+=1,o&&(o=!1,f+=1),A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),o=!0,b):(n.enter("data"),y(A)))}function y(A){return A===null||A===124||xt(A)?(n.exit("data"),b(A)):(n.consume(A),A===92?v:y)}function v(A){return A===92||A===124?(n.consume(A),y):y(A)}function S(A){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(A):(n.enter("tableDelimiterRow"),o=!1,Ze(A)?tt(n,N,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):N(A))}function N(A){return A===45||A===58?z(A):A===124?(o=!0,n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),D):ce(A)}function D(A){return Ze(A)?tt(n,z,"whitespace")(A):z(A)}function z(A){return A===58?(d+=1,o=!0,n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),_):A===45?(d+=1,_(A)):A===null||Me(A)?oe(A):ce(A)}function _(A){return A===45?(n.enter("tableDelimiterFiller"),M(A)):ce(A)}function M(A){return A===45?(n.consume(A),M):A===58?(o=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),H):(n.exit("tableDelimiterFiller"),H(A))}function H(A){return Ze(A)?tt(n,oe,"whitespace")(A):oe(A)}function oe(A){return A===124?N(A):A===null||Me(A)?!o||f!==d?ce(A):(n.exit("tableDelimiterRow"),n.exit("tableHead"),i(A)):ce(A)}function ce(A){return r(A)}function R(A){return n.enter("tableRow"),W(A)}function W(A){return A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),W):A===null||Me(A)?(n.exit("tableRow"),i(A)):Ze(A)?tt(n,W,"whitespace")(A):(n.enter("data"),ie(A))}function ie(A){return A===null||A===124||xt(A)?(n.exit("data"),W(A)):(n.consume(A),A===92?F:ie)}function F(A){return A===92||A===124?(n.consume(A),ie):ie(A)}}function qC(n,i){let r=-1,s=!0,f=0,d=[0,0,0,0],o=[0,0,0,0],m=!1,g=0,p,b,y;const v=new OC;for(;++r<n.length;){const S=n[r],N=S[1];S[0]==="enter"?N.type==="tableHead"?(m=!1,g!==0&&(wg(v,i,g,p,b),b=void 0,g=0),p={type:"table",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",p,i]])):N.type==="tableRow"||N.type==="tableDelimiterRow"?(s=!0,y=void 0,d=[0,0,0,0],o=[0,r+1,0,0],m&&(m=!1,b={type:"tableBody",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",b,i]])),f=N.type==="tableDelimiterRow"?2:b?3:1):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")?(s=!1,o[2]===0&&(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y),d=[0,0,0,0]),o[2]=r)):N.type==="tableCellDivider"&&(s?s=!1:(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y)),d=o,o=[d[1],r,0,0])):N.type==="tableHead"?(m=!0,g=r):N.type==="tableRow"||N.type==="tableDelimiterRow"?(g=r,d[1]!==0?(o[0]=o[1],y=Cs(v,i,d,f,r,y)):o[1]!==0&&(y=Cs(v,i,o,f,r,y)),f=0):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")&&(o[3]=r)}for(g!==0&&wg(v,i,g,p,b),v.consume(i.events),r=-1;++r<i.events.length;){const S=i.events[r];S[0]==="enter"&&S[1].type==="table"&&(S[1]._align=LC(i.events,r))}return n}function Cs(n,i,r,s,f,d){const o=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",m="tableContent";r[0]!==0&&(d.end=Object.assign({},Ki(i.events,r[0])),n.add(r[0],0,[["exit",d,i]]));const g=Ki(i.events,r[1]);if(d={type:o,start:Object.assign({},g),end:Object.assign({},g)},n.add(r[1],0,[["enter",d,i]]),r[2]!==0){const p=Ki(i.events,r[2]),b=Ki(i.events,r[3]),y={type:m,start:Object.assign({},p),end:Object.assign({},b)};if(n.add(r[2],0,[["enter",y,i]]),s!==2){const v=i.events[r[2]],S=i.events[r[3]];if(v[1].end=Object.assign({},S[1].end),v[1].type="chunkText",v[1].contentType="text",r[3]>r[2]+1){const N=r[2]+1,D=r[3]-r[2]-1;n.add(N,D,[])}}n.add(r[3]+1,0,[["exit",y,i]])}return f!==void 0&&(d.end=Object.assign({},Ki(i.events,f)),n.add(f,0,[["exit",d,i]]),d=void 0),d}function wg(n,i,r,s,f){const d=[],o=Ki(i.events,r);f&&(f.end=Object.assign({},o),d.push(["exit",f,i])),s.end=Object.assign({},o),d.push(["exit",s,i]),n.add(r+1,0,d)}function Ki(n,i){const r=n[i],s=r[0]==="enter"?"start":"end";return r[1][s]}const HC={name:"tasklistCheck",tokenize:YC};function IC(){return{text:{91:HC}}}function YC(n,i,r){const s=this;return f;function f(g){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(g):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),d)}function d(g){return xt(g)?(n.enter("taskListCheckValueUnchecked"),n.consume(g),n.exit("taskListCheckValueUnchecked"),o):g===88||g===120?(n.enter("taskListCheckValueChecked"),n.consume(g),n.exit("taskListCheckValueChecked"),o):r(g)}function o(g){return g===93?(n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),m):r(g)}function m(g){return Me(g)?i(g):Ze(g)?n.check({tokenize:GC},i,r)(g):r(g)}}function GC(n,i,r){return tt(n,s,"whitespace");function s(f){return f===null?r(f):i(f)}}function VC(n){return ly([mC(),CC(),DC(n),UC(),IC()])}const QC={};function XC(n){const i=this,r=n||QC,s=i.data(),f=s.micromarkExtensions||(s.micromarkExtensions=[]),d=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),o=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);f.push(VC(r)),d.push(fC()),o.push(dC(r))}function Qc(n){const i=n.trim();if(!(!i||/[\u0000-\u0020\u007f]/.test(i)))try{const r=new URL(i);if(r.protocol==="https:"||r.protocol==="http:"||r.protocol==="mailto:")return i}catch{}}function Xc(n){return!!n&&!/[\u0000-\u001f\u007f]/.test(n)&&!/^[a-z][a-z\d+.-]*:/i.test(n)&&!n.startsWith("//")}function Cg(n){if(!Xc(n))return;const i=n.split(/[?#]/,1)[0];if(i)try{const r=decodeURIComponent(i);return Xc(r)?r:void 0}catch{return}}async function ZC(n){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(n);return}const i=document.activeElement,r=document.createElement("textarea");r.value=n,r.setAttribute("aria-label","复制内容"),r.style.cssText="position:fixed;left:-10000px;top:0",document.body.append(r);try{if(r.select(),!document.execCommand("copy"))throw new Error("复制不可用")}finally{r.remove(),i instanceof HTMLElement&&i.focus({preventScroll:!0})}}function Vs({text:n,label:i="复制"}){const[r,s]=w.useState("idle"),f=w.useRef(!0),d=w.useRef(void 0);w.useEffect(()=>(f.current=!0,()=>{f.current=!1,clearTimeout(d.current)}),[]);const o=async()=>{clearTimeout(d.current);try{await ZC(n),f.current&&s("copied")}catch{f.current&&s("error")}f.current&&(d.current=setTimeout(()=>s("idle"),2500))};return u.jsx("button",{className:"message-copy",onClick:()=>{o()},"aria-label":i,title:i,children:r==="copied"?"已复制":r==="error"?"复制失败":i})}function Zc(n){return typeof n=="string"||typeof n=="number"?String(n):Array.isArray(n)?n.map(Zc).join(""):w.isValidElement(n)?Zc(n.props.children):""}function KC({children:n}){const i=w.Children.toArray(n).find(d=>w.isValidElement(d)),s=(w.isValidElement(i)?i.props.className??"":"").match(/(?:^|\s)language-([\w+-]+)/)?.[1]??"代码",f=Zc(n).replace(/\n$/,"");return u.jsxs("div",{className:"message-code-block",children:[u.jsxs("div",{className:"message-code-heading",children:[u.jsx("span",{children:s}),u.jsx(Vs,{text:f,label:"复制代码"})]}),u.jsx("pre",{tabIndex:0,children:n})]})}function FC(n){return{a:({href:i,children:r,title:s})=>{const f=Qc(i??"");if(f)return u.jsx("a",{href:f,title:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:r});const d=i?Cg(i):void 0;return d?u.jsxs("span",{className:"message-file-reference",title:d,children:[n?u.jsx("button",{className:"message-file-open",onClick:()=>n(d),children:r}):r,u.jsx(Vs,{text:d,label:"复制路径"})]}):u.jsx("span",{children:r})},img:({src:i,alt:r})=>{const s=Qc(typeof i=="string"?i:""),f=typeof i=="string"?Cg(i):void 0;return s?u.jsxs("a",{className:"message-image-reference",href:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:[r||"图片",u.jsx("span",{children:"打开图片 ↗"})]}):f&&n?u.jsxs("button",{className:"message-image-reference",title:f,onClick:()=>n(f),children:[r||"图片",u.jsx("span",{children:"查看图片"})]}):u.jsxs("span",{className:"message-image-reference",children:[r||"图片",u.jsx("span",{children:"图片路径不可直接访问"})]})},pre:({children:i})=>u.jsx(KC,{children:i}),table:({children:i})=>u.jsx("div",{className:"message-table-scroll",role:"region","aria-label":"表格",tabIndex:0,children:u.jsx("table",{children:i})})}}const $C=w.memo(function({text:i,reasoning:r="",streaming:s=!1,onOpenFile:f}){const d=w.useMemo(()=>FC(f),[f]);return u.jsxs("div",{className:"message-content",children:[r?u.jsxs("details",{className:"message-reasoning",children:[u.jsx("summary",{children:s&&!i?"思考中…":"思考过程"}),u.jsx("pre",{children:r})]}):null,s?u.jsxs("div",{className:"message-streaming",children:[i||(r?"":"正在思考…"),u.jsx("span",{className:"cursor","aria-hidden":"true",children:"▍"})]}):i?u.jsx(Dk,{remarkPlugins:[XC],skipHtml:!0,urlTransform:o=>Qc(o)??(Xc(o)?o:""),components:d,children:i}):null,!s&&i?u.jsx("div",{className:"message-actions",children:u.jsx(Vs,{text:i,label:"复制回复"})}):null]})});function JC(n){const i=n.args??{},r=n.summary||[i.description,i.command,i.file_path,i.path,i.query,i.url].find(s=>typeof s=="string"&&s.trim());return typeof r=="string"?r.replace(/\s+/g," ").slice(0,180):""}const PC=w.memo(function({item:i,running:r}){const s=JC(i),f=i.done?i.error?"失败":"已完成":r?"执行中":"未完成";return u.jsxs("details",{className:`message-tool-card${i.error?" message-tool-error":""}`,children:[u.jsxs("summary",{children:[u.jsx("span",{className:"message-tool-indicator","aria-hidden":"true",children:i.done?i.error?"!":"✓":"·"}),u.jsx("span",{className:"message-tool-name",children:i.name}),u.jsx("span",{className:"message-tool-summary",children:s}),u.jsx("span",{className:"message-tool-status",children:f})]}),i.args&&Object.keys(i.args).length?u.jsxs("div",{className:"message-tool-section",children:[u.jsx("strong",{children:"参数"}),u.jsx("pre",{tabIndex:0,children:JSON.stringify(i.args,null,2)})]}):null,u.jsxs("div",{className:"message-tool-section",children:[u.jsxs("div",{className:"message-tool-result-heading",children:[u.jsx("strong",{children:"结果"}),i.result?u.jsx(Vs,{text:i.result,label:"复制结果"}):null]}),u.jsx("pre",{tabIndex:0,children:i.result??(i.done?"工具没有返回文本内容。":r?"等待工具返回结果…":"这次工具调用没有保存结果。")})]})]})});function WC(n){return{running:"运行中",completed:"已完成",error:"失败",recorded:"历史记录"}[n]??n}function Eg(n){return n.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"")}function As(){return{items:[],run:"idle",seq:0,liveByAgent:{}}}function Kr(n){return n.agentId??""}function Es(n,i,r=!1){const s=i.goalId;if(n.goalId!==s&&!(r&&n.goalId===void 0&&s!==void 0))return!0;const f=i.revision;return n.goalRevision!==void 0&&(f===void 0||f<n.goalRevision)}function eE(n){switch(n){case"aborted_streaming":case"aborted_tools":return"idle";case"prompt_too_long":case"model_error":case"image_error":case"replay_incomplete":return"error";default:return"completed"}}function tE(n){if(!n||typeof n!="object")return null;const i=n;if(i.method==="agent/streamEvent"&&i.params&&typeof i.params=="object"){const r=i.params;if(r.event&&typeof r.event=="object")return{event:r.event,sessionId:typeof r.sessionId=="string"?r.sessionId:void 0}}return typeof i.type=="string"?{event:i}:null}function Os(n,i){const r=tE(i);if(!r)return n;const{event:s,sessionId:f}=r,d=s.type;let o=n;f&&f!==o.sessionId&&(o={...o,sessionId:f});const m=g=>{const p=o.seq+1;return[`${g}-${p}`,{...o,seq:p}]};switch(d){case"stream_request_start":{const g=Kr(s),[p,b]=m("a"),y={kind:"assistant",id:p,text:"",reasoning:"",done:!1,agentId:s.agentId,...typeof s.messageId=="string"?{messageId:s.messageId}:{}};return{...b,items:[...b.items,y],liveByAgent:{...b.liveByAgent,[g]:p},run:"running"}}case"text_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.find(D=>D.id===b&&D.kind==="assistant"))return{...o,run:"running",items:o.items.map(D=>D.id===b&&D.kind==="assistant"?{...D,text:D.text+g}:D)};const[v,S]=m("a"),N={kind:"assistant",id:v,text:g,reasoning:"",done:!1,agentId:s.agentId};return{...S,items:[...S.items,N],liveByAgent:{...S.liveByAgent,[p]:v},run:"running"}}case"thinking_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.some(N=>N.id===b&&N.kind==="assistant"))return{...o,run:"running",items:o.items.map(N=>N.id===b&&N.kind==="assistant"?{...N,reasoning:N.reasoning+g}:N)};const[y,v]=m("a"),S={kind:"assistant",id:y,text:"",reasoning:g,done:!1,agentId:s.agentId};return{...v,items:[...v.items,S],liveByAgent:{...v.liveByAgent,[p]:y},run:"running"}}case"tool_use_start":{const g=s.toolCall;if(!g||o.items.some(v=>v.kind==="tool"&&v.id===g.id))return o;const p=o.orphanResults?.[g.id],b={kind:"tool",id:g.id,name:g.toolName,args:g.args,summary:g.summary,done:!!p,result:p?.result,error:p?.error,agentId:s.agentId};let y=o.orphanResults;if(p){const{[g.id]:v,...S}=o.orphanResults;y=Object.keys(S).length>0?S:void 0}return{...o,run:"running",items:[...o.items,b],orphanResults:y}}case"tool_use_args_delta":{const g=s.toolCallId,p=s.args;return!g||!p?o:{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g?{...b,args:{...b.args??{},...p}}:b)}}case"tool_result":{const g=s.result;return g?o.items.some(b=>b.kind==="tool"&&b.id===g.id)?{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g.id?{...b,done:!0,result:Eg(g.result??g.error??""),error:!!(g.isError||g.error)}:b)}:{...o,orphanResults:{...o.orphanResults??{},[g.id]:{result:g.result??g.error??"",error:!!(g.isError||g.error)}}}:o}case"room_tool_result":{const g=s.summary??"",p=Eg(g),b=!!s.isError;let y=-1;for(let N=o.items.length-1;N>=0;N--)if(o.items[N].kind==="tool"&&!o.items[N].done){y=N;break}if(y===-1)return o;const v=o.items.slice(),S=v[y];return v[y]={...S,done:!0,result:p,summary:p||S.summary,error:b},{...o,items:v}}case"tool_summary":{const g=s.summary??"",p=Array.isArray(s.toolCallIds)?s.toolCallIds.filter(D=>typeof D=="string"):[],y=p.length>0?p[p.length-1]:void 0,v=s.agentId;if(y){let D=!1;const z=o.items.map(_=>_.kind!=="tool"||_.id!==y||_.agentId!==v?_:(D=!0,{..._,summary:g}));return D?{...o,items:z}:o}if(v){let D=-1;for(let _=o.items.length-1;_>=0;_--){const M=o.items[_];if(M.kind==="tool"&&M.agentId===v){D=_;break}}if(D===-1)return o;const z=o.items.slice();return z[D]={...z[D],summary:g},{...o,items:z}}let S=-1;for(let D=o.items.length-1;D>=0;D--){const z=o.items[D];if(z.kind==="tool"&&z.agentId===void 0){S=D;break}}if(S===-1)return o;const N=o.items.slice();return N[S]={...N[S],summary:g},{...o,items:N}}case"tombstone":{if(typeof s.messageId!="string")return o;const g=new Set(o.items.filter(p=>p.kind==="assistant"&&p.messageId===s.messageId||p.kind==="tool"&&p.id===s.messageId).map(p=>p.id));return g.size?{...o,items:o.items.filter(p=>!g.has(p.id)),liveByAgent:Object.fromEntries(Object.entries(o.liveByAgent).filter(([,p])=>!g.has(p)))}:o}case"assistant_message":{const g=Kr(s);if(!(g in o.liveByAgent))return o;const{[g]:p,...b}=o.liveByAgent,y=o.items.map(v=>v.kind==="assistant"&&!v.done&&(v.agentId??"")===g?{...v,done:!0}:v);return{...o,liveByAgent:b,items:y}}case"turn_complete":{const g=s.reason??"completed",p=Kr(s),{[p]:b,...y}=o.liveByAgent,v=o.items.map(S=>S.kind==="assistant"&&!S.done&&(S.agentId??"")===p?{...S,done:!0}:S);return s.agentId?{...o,liveByAgent:y,items:v}:{...o,liveByAgent:y,items:v,run:eE(g)}}case"goal_set":{const g=s.objective??"",p=!!s.paused;return o.goal&&o.goalId===s.goalId&&Es(o,s)?o:{...o,goal:g?`◎ ${g}${p?" (已暂停)":""}`:"◎ 目标",goalId:s.goalId,goalPaused:p,goalRevision:s.revision}}case"goal_updated":{if(o.goal&&Es(o,s,!0))return o;const g=s.goalId,p=s.objective??"",b=!!s.paused;return{...o,goal:p?`◎ ${p}${b?" (已暂停)":""}`:o.goal,goalId:g??o.goalId,goalPaused:b,goalRevision:s.revision??o.goalRevision}}case"goal_cleared":return o.goal&&Es(o,s)?o:{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};case"goal_progress":{if(o.goal&&Es(o,s))return o;const g=s.status??"";if(g==="met"||g==="exhausted")return{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};const p=s.round,b=p?`目标 · 第 ${p} 轮 (${g})`:`目标 (${g})`;return{...o,goal:b,goalRevision:s.revision??o.goalRevision}}case"task_update":{const g=s.agentId;if(!g)return o;const p=s.tasks??[],b=p.filter(N=>N.status==="completed").length,y=`任务 ${b}/${p.length}`,v=o.items.findIndex(N=>N.kind==="subagent"&&N.agentId===g),S={kind:"subagent",id:`sub-${g}`,agentId:g,label:y,status:p.length>0&&b===p.length?"completed":"running"};if(v>=0){const N=o.items.slice();return N[v]=S,{...o,items:N}}return{...o,items:[...o.items,S]}}case"agent_start":{const g=s.agentId;if(!g)return o;const p={kind:"subagent",id:`sub-${g}`,agentId:g,label:s.name||s.description||"子代理",status:s.status==="recorded"?"recorded":"running"};return o.items.some(b=>b.kind==="subagent"&&b.agentId===g)?o:{...o,items:[...o.items,p]}}case"agent_end":{const g=s.agentId;return{...o,items:o.items.map(p=>p.kind==="subagent"&&p.agentId===g?{...p,status:s.error?"error":"completed"}:p)}}case"error":{const[g,p]=m("err");return{...p,run:"error",liveByAgent:{},items:[...p.items,{kind:"system_error",id:g,text:s.error||"运行出错"}]}}case"session_title":return{...o,title:s.title};case"session_user_message":case"user_message":{const g=typeof s.clientMessageId=="string"?s.clientMessageId:void 0,p=Array.isArray(s.attachments)?s.attachments.map(v=>v).filter(v=>!!v&&typeof v.name=="string"&&typeof v.size=="number"&&Number.isFinite(v.size)&&v.size>=0).map(v=>({name:v.name,size:v.size,...typeof v.mime=="string"?{mime:v.mime}:{},...typeof v.path=="string"?{path:v.path}:{}})):void 0;if(g&&o.items.some(v=>v.kind==="user"&&v.clientMessageId===g))return p?.length?{...o,items:o.items.map(v=>v.kind==="user"&&v.clientMessageId===g?{...v,attachments:p.map((S,N)=>{const D=v.attachments?.[N];return D?.name===S.name?{...D,...S}:S})}:v)}:o;const[b,y]=m("u");return{...y,items:[...y.items,{kind:"user",id:b,text:s.text??"",...p?.length?{attachments:p}:{},...g?{clientMessageId:g}:{}}]}}case"assistant_text":{const[g,p]=m("a");return{...p,run:"running",items:[...p.items,{kind:"assistant",id:g,text:s.text??"",reasoning:"",done:!0,agentId:s.agentId}]}}default:return o}}function nE(n,i,r,s){const f=`u-${n.seq+1}`;return{...n,seq:n.seq+1,items:[...n.items,{kind:"user",id:f,text:i,...r?.length?{attachments:r}:{},...s?{clientMessageId:s}:{}}]}}function On(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function yt(n){return typeof n=="string"?n:""}function Ms(n){return Array.isArray(n)?n.map(On).filter(i=>i!==void 0):[]}function Kc(n){return typeof n=="string"?n:Ms(n).filter(i=>i.type==="text").map(i=>yt(i.text)).join("")}function Ns(n){return n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Rc(n){const i=n.replace(/\\/g,"/").split("/").filter(Boolean).pop()||"附件";return n.includes(".code-shell/attachments/")?i.replace(/^[a-f0-9]{16}-/,""):i}function Ng(n){const i=typeof n=="number"?n:Number(n);return Number.isSafeInteger(i)&&i>=0?i:0}function lE(n){const i=[],r=[];let s=Kc(n.content);s=s.replace(/<attached-file\s+path="([^"]*)">\s*([\s\S]*?)<\/attached-file>/g,(o,m,g)=>{if(!/^absolutePath:\s*.+$/m.test(g)||!/^origin:\s*.+$/m.test(g))return o;const p=g.match(/^mime:\s*(.+)$/m)?.[1]?.trim();return i.push({name:Rc(Ns(m)),path:Ns(m),size:Ng(g.match(/^size:\s*(\d+)\s*$/m)?.[1]),...p?{mime:p}:{}}),""}),s=s.replace(/<attached-directory\s+path="([^"]*)"[^>]*>[\s\S]*?<\/attached-directory>/g,(o,m)=>(i.push({name:`${Rc(Ns(m))}/`,path:Ns(m),size:0}),"")),s=s.replace(/<attached-image-paths>\s*([\s\S]*?)<\/attached-image-paths>\s*(?:\(上面附带的图片在工作区的真实路径[^\n]*\))?/g,(o,m)=>(r.push(...m.split(`
49
49
  `).map(g=>g.trim()).filter(Boolean)),""));const f=Ms(n.content).filter(o=>o.type==="image");for(let o=0;o<Math.max(f.length,r.length);o++){const m=On(f[o]?.source),g=yt(m?.data).replace(/\s/g,"");i.push({name:r[o]?Rc(r[o]):`图片 ${o+1}`,...r[o]?{path:r[o]}:{},size:g?Math.max(0,Math.floor(g.length*3/4)-(g.match(/=+$/)?.[0].length??0)):0,...typeof m?.media_type=="string"?{mime:m.media_type}:{}})}const d=Array.isArray(n.attachments)?n.attachments.flatMap(o=>{const m=On(o),g=yt(m?.name)||yt(m?.originalName);return g?[{name:g,size:Ng(m?.size),...typeof m?.mime=="string"?{mime:m.mime}:{},...typeof m?.path=="string"?{path:m.path}:{}}]:[]}):[];return{text:typeof n.displayText=="string"?n.displayText:s.trim(),attachments:d.length?d:i}}function Tg(n){return On(n.data)??On(n.message)??n}function iE(n){const i=[],r=new Set,s=new Set,f=new Map;for(const m of n){const g=On(m);if(!g)continue;const p=Tg(g);g.type==="tool_use"&&yt(p.toolCallId)&&f.set(yt(p.toolCallId),{name:yt(p.toolName)||"工具",args:On(p.args)??{}});for(const b of Ms(p.content))b.type==="tool_use"&&yt(b.id)&&f.set(yt(b.id),{name:yt(b.name)||"工具",args:On(b.input)??{}})}const d=(m,g,p,b)=>{m&&(s.has(m)?i.push({type:"tool_use_args_delta",toolCallId:m,args:p,...b?{agentId:b}:{}}):(s.add(m),i.push({type:"tool_use_start",toolCall:{id:m,toolName:g||"工具",args:p},...b?{agentId:b}:{}})))},o=(m,g,p)=>{if(!m)return;const b=f.get(m);s.has(m)||d(m,b?.name||yt(g.toolName)||"工具",b?.args??{},p);const y=typeof g.result=="string"?g.result:Kc(g.content??g.contentBlocks),v=yt(g.error);i.push({type:"tool_result",result:{id:m,result:y||v,...v?{error:v}:{},isError:g.isError===!0||g.is_error===!0||!!v},...p?{agentId:p}:{}})};for(const m of n){const g=On(m);if(!g)continue;const p=yt(g.id);if(p&&r.has(p))continue;p&&r.add(p);const b=Tg(g),y=yt(b.agentId)||void 0;switch(typeof g.type=="string"?g.type:typeof b.role=="string"?"message":""){case"message":{const S=Ms(b.content);if(b.role==="user"){if(b.injected===!0||b.authority==="agent"||b.authority==="system"||b.authority==="policy")break;const N=lE(b);if(N.text.startsWith("<system-reminder>"))break;(N.text||N.attachments.length)&&i.push({type:"user_message",...N,...typeof b.clientMessageId=="string"?{clientMessageId:b.clientMessageId}:{}});for(const D of S)D.type==="tool_result"&&o(yt(D.tool_use_id),D,y)}else if(b.role==="assistant"){const N=Kc(b.content),D=S.filter(z=>z.type==="reasoning").map(z=>yt(z.reasoningContent)||yt(z.text)).join("");if(N||D){const z=y?{agentId:y}:{};i.push({type:"stream_request_start",...z}),D&&i.push({type:"thinking_delta",text:D,...z}),N&&i.push({type:"text_delta",text:N,...z}),i.push({type:"assistant_message",...z})}for(const z of S)z.type==="tool_use"&&d(yt(z.id),yt(z.name),On(z.input)??{},y)}else b.role==="tool"&&o(yt(b.tool_call_id),b,y);break}case"tool_use":d(yt(b.toolCallId),yt(b.toolName),On(b.args)??{},y);break;case"tool_result":o(yt(b.toolCallId),b,y);break;case"subagent":y&&i.push({type:"agent_start",agentId:y,name:yt(b.name),description:yt(b.description),status:"recorded"});break;case"error":yt(b.error)&&i.push({type:"error",error:b.error});break;case"turn_stopped":i.push({type:"turn_complete",reason:"aborted_tools"});break;case"session_meta":yt(b.sessionId)&&i.push({type:"session_started",sessionId:b.sessionId});break}}return i}function rE(n){let i=As();for(const r of iE(n))i=Os(i,r);return{...i,run:i.run==="error"?"error":"idle",liveByAgent:{}}}function aE(n){const i=new URLSearchParams(n).get("session");return i&&/^[a-zA-Z0-9_-]{1,128}$/.test(i)?i:null}function Zy(n,i){return!i||!n.hubEpoch||n.hubSequence===void 0?!0:n.hubEpoch===i.epoch&&n.hubSequence>i.sequence}function Ag(n,i=[]){let r=rE(n.transcript);for(const f of n.liveStream?.events??[])r=Os(r,f.event);n.running?r={...r,run:"running"}:n.running===!1&&(r.run==="running"||r.run==="waiting")&&(r={...r,run:"idle"});let s=n.streamCursor;for(const f of i)Zy(f,s)&&(r=Os(r,f.event),f.hubEpoch&&f.hubSequence!==void 0&&(s={epoch:f.hubEpoch,sequence:f.hubSequence}));return{chat:r,cursor:s,truncated:n.liveStream?.truncated??!1}}function Ky(n,i){if(n?.title)return n.title;const r=n?.items.find(s=>s.kind==="user");if(r&&r.kind==="user"&&r.text.trim()){const s=r.text.trim().split(`
50
50
  `)[0];return s.length>32?`${s.slice(0,32)}…`:s}return r?.kind==="user"&&r.attachments?.length?`附件:${r.attachments[0].name}`:i.slice(0,8)}function sE(n,i){if(i.workspaceKey!==n.workspaceKey||i.sessionId!==n.activeId)throw new Error("当前工作区或对话已经变化,请重新打开面板后发送。");if(n.connection!=="open"||n.loading)throw new Error("工作台尚未连接,请连接后重新发送面板任务。");if(n.readOnly)throw new Error("当前对话为只读,无法发送面板任务。");if(n.running||n.chat.run==="running"||n.chat.run==="waiting"||n.approvals.some(r=>!r.sessionId||r.sessionId===i.sessionId))throw new Error("当前对话仍在处理任务,请完成后再发送面板任务。");if(n.uncertain||n.uploading||n.uploadBusy)throw new Error("当前消息或附件仍在发送,请等待结果后重试。");if(n.draft.length>0||n.files.length>0)throw new Error("当前对话还有草稿或附件,请先处理它们,再发送面板任务。");if(!i.prompt.trim()||i.prompt.length>2e4)throw new Error("面板任务内容无效。");if(n.setDraft(i.prompt),!n.send())throw n.setDraft(""),new Error("当前对话暂时无法接收任务,请稍后重新发送。");return{accepted:!0}}function uE({controller:n,onBackToProjects:i,projectName:r}){const{connection:s,sessions:f,activeId:d,chat:o,draft:m,files:g,uploading:p,workerNote:b,replayNote:y,error:v,workspaceCwd:S,workspaceName:N,configuration:D,configurationVersion:z,sessionsVersion:_,localDrafts:M,running:H,title:oe,approvalCount:ce,onAuthLost:R,refreshSessions:W,refreshConfiguration:ie,session:F}=n,A=n.workspaceApi,G=n.host==="desktop"?"桌面":"服务端",[V,se]=w.useState(!1),ae=w.useRef(null),P=w.useRef(null),[E,U]=w.useState("chat"),[te,he]=w.useState(),[k,T]=w.useState(),[K,C]=w.useState(0),[re,ve]=w.useState(!1),[Q,pe]=w.useState(null),[je,Y]=w.useState("overview"),[xe,J]=w.useState(()=>window.matchMedia("(max-width: 760px)").matches),[ye,Ae]=w.useState(()=>!window.matchMedia("(max-width: 760px)").matches),we=w.useRef(null),Ye=w.useRef(null),nt=w.useRef(!1),jt=w.useRef(null),Yt=w.useRef(null),at=w.useRef(!0);w.useEffect(()=>{he(void 0),U(q=>q==="panel"?"panels":q)},[n.workspaceKey]),w.useEffect(()=>{xe&&!ye&&nt.current&&!V&&Ye.current?.focus(),nt.current=ye},[xe,ye,V]),w.useEffect(()=>{const q=window.matchMedia("(max-width: 760px)"),ze=()=>{J(q.matches),Ae(!q.matches)};return q.addEventListener("change",ze),()=>q.removeEventListener("change",ze)},[]),w.useEffect(()=>{if(!xe||!ye)return;const q=we.current;q?.querySelector("button")?.focus();const ze=St=>{if(!document.querySelector("dialog[open]")){if(St.key==="Escape"&&!St.isComposing)St.preventDefault(),Ae(!1),Ye.current?.focus();else if(St.key==="Tab"){const de=Array.from(q?.querySelectorAll('button:not(:disabled), select:not(:disabled), input:not(:disabled), textarea:not(:disabled), a[href], summary, [tabindex]:not([tabindex="-1"])')??[]).filter(_e=>_e.getClientRects().length>0),Re=de?.[0],Je=de?.[de.length-1];St.shiftKey&&document.activeElement===Re?(St.preventDefault(),Je?.focus()):!St.shiftKey&&document.activeElement===Je&&(St.preventDefault(),Re?.focus())}}};return document.addEventListener("keydown",ze),()=>document.removeEventListener("keydown",ze)},[xe,ye]),w.useLayoutEffect(()=>{const q=Yt.current;!q||E!=="chat"||(q.style.height="auto",q.style.height=`${Math.min(180,Math.max(64,q.scrollHeight))}px`)},[m,E]),w.useLayoutEffect(()=>{const q=jt.current;q&&at.current&&E==="chat"&&(q.scrollTop=q.scrollHeight)},[o.items,n.approvals.length,E]);const mt=()=>{xe&&(Ae(!1),Ye.current?.focus())},ut=q=>{if(E==="settings"&&je===q){mt();return}ot(()=>{Y(q),U("settings"),mt()})},ot=q=>{re?pe(()=>q):q()},Gt=q=>ot(()=>{T(q),C(ze=>ze+1),U("files"),mt()}),vt=w.useRef(Gt);vt.current=Gt;const qt=w.useCallback(q=>vt.current(q),[]);w.useEffect(()=>{if(!re&&!n.uploadBusy&&!n.hasUnsent)return;const q=ze=>{ze.preventDefault(),ze.returnValue=""};return window.addEventListener("beforeunload",q),()=>window.removeEventListener("beforeunload",q)},[re,n.uploadBusy,n.hasUnsent]);const ne=q=>ot(()=>{U("chat"),mt(),at.current=!0,q()}),me=q=>ne(()=>{n.selectSession(q)}),Te=()=>ne(n.newSession),ge=()=>{at.current=!0,n.send()},ke=n.stop,Ce=n.approvals.filter(q=>!q.sessionId||q.sessionId===d),B=n.approvals.filter(q=>q.sessionId&&q.sessionId!==d),Se=o.items.length===0&&Ce.length===0,Ke=D?.connections.find(q=>q.id===D.defaults.text),lt=s==="open"?"已连接":s==="connecting"?"连接中":"正在重连",Be=E==="chat"?oe:E==="files"?"工作区文件":E==="history"?"历史对话":E==="links"?"Link":E==="panels"||E==="panel"?te&&E==="panel"?te.panel.title["zh-CN"]||te.panel.title.default:"面板":je==="skills"?"Skills":"设置";return u.jsxs("div",{className:`shell${ye?" sidebar-open":""}`,children:[xe&&ye?u.jsx("div",{className:"sidebar-backdrop",onClick:()=>{Ae(!1),Ye.current?.focus()},"aria-hidden":"true"}):null,u.jsxs("aside",{id:"workbench-sidebar",ref:we,className:"rail",hidden:!ye,role:xe?"dialog":void 0,"aria-modal":xe&&ye?!0:void 0,"aria-label":"工作台导航",children:[u.jsxs("div",{className:"rail-head",children:[u.jsx("span",{className:"brand-mark",children:u.jsx(Et,{name:"brand"})}),u.jsx("strong",{children:"CodeShell"}),u.jsx("span",{className:"hub-badge",children:n.host==="desktop"?"Desktop":A?"Hub":"Web"}),u.jsx("button",{className:"icon-button sidebar-close","aria-label":"收起侧栏",onClick:()=>{Ae(!1),Ye.current?.focus()},children:u.jsx(Et,{name:"sidebar"})})]}),u.jsxs("nav",{className:"workbench-nav","aria-label":"主要功能",children:[i?u.jsxs("button",{className:"nav-button",title:r,onClick:()=>{re||n.hasUnsent||n.uploadBusy?pe(()=>i):i()},children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:"返回项目列表"})]}):null,u.jsxs("button",{className:"nav-button new-chat-button",onClick:Te,children:[u.jsx(Et,{name:"plus"}),u.jsx("span",{children:"新对话"})]}),u.jsxs("button",{className:`nav-button${E==="chat"?" active":""}`,onClick:()=>{ot(()=>{U("chat"),mt()})},"aria-current":E==="chat"?"page":void 0,children:[u.jsx(Et,{name:"chat"}),u.jsx("span",{children:"对话"})]}),A?u.jsxs(u.Fragment,{children:[u.jsxs("button",{className:`nav-button${E==="history"?" active":""}`,onClick:()=>ot(()=>{U("history"),mt()}),"aria-current":E==="history"?"page":void 0,children:[u.jsx(Et,{name:"history"}),u.jsx("span",{children:"历史对话"})]}),u.jsxs("button",{className:`nav-button${E==="files"?" active":""}`,onClick:()=>Gt(),"aria-current":E==="files"?"page":void 0,children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:"文件"})]}),u.jsxs("button",{className:`nav-button${E==="settings"&&je==="skills"?" active":""}`,onClick:()=>ut("skills"),"aria-current":E==="settings"&&je==="skills"?"page":void 0,children:[u.jsx(Et,{name:"skills"}),u.jsx("span",{children:"Skills"})]}),u.jsxs("button",{className:`nav-button${E==="panels"||E==="panel"?" active":""}`,onClick:()=>ot(()=>{U("panels"),mt()}),"aria-current":E==="panels"||E==="panel"?"page":void 0,children:[u.jsx(Et,{name:"panels"}),u.jsx("span",{children:"面板"})]}),u.jsxs("button",{className:`nav-button${E==="links"?" active":""}`,onClick:()=>ot(()=>{U("links"),mt()}),"aria-current":E==="links"?"page":void 0,children:[u.jsx(Et,{name:"links"}),u.jsx("span",{children:"Link"})]}),u.jsxs("button",{className:`nav-button${E==="settings"&&je!=="skills"?" active":""}`,onClick:()=>ut("overview"),"aria-current":E==="settings"&&je!=="skills"?"page":void 0,children:[u.jsx(Et,{name:"settings"}),u.jsx("span",{children:"设置"})]})]}):null]}),u.jsx("div",{className:"rail-section-label",children:"工作区"}),A?u.jsxs("button",{className:"workspace-button",title:S??void 0,onClick:()=>Gt(),children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:r??N}),u.jsx(Et,{name:"chevron"})]}):u.jsxs("div",{className:"workspace-button",title:S??void 0,children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:r??N})]}),u.jsxs("div",{className:"rail-section-label history-label",children:[u.jsx("span",{children:"最近对话"}),u.jsx("span",{children:f.length})]}),n.renderSidebar?.({guard:ot,conversation:ne}),u.jsxs("ul",{className:"sessions","aria-label":"最近对话",children:[M.map(({sessionId:q,draft:ze})=>u.jsx("li",{children:u.jsxs("button",{className:q===d&&E==="chat"?"session active":"session",onClick:()=>{me(q)},children:[u.jsx("span",{className:"session-title",children:ze.text.trim()||`附件:${ze.files[0]?.name??"新对话"}`}),u.jsx("span",{className:"session-meta",children:"草稿"})]})},`draft-${q}`)),f.map(q=>u.jsx("li",{children:u.jsxs("button",{className:q.sessionId===d&&E==="chat"?"session active":"session",onClick:()=>{me(q.sessionId)},"aria-current":q.sessionId===d&&E==="chat"?"page":void 0,children:[u.jsx("span",{className:"session-title",children:q.sessionId===d?q.customTitle||o.title||q.title||Ky(o,q.sessionId):q.title||q.preview?.trim()||q.sessionId.slice(0,8)}),u.jsxs("span",{className:"session-meta",children:[n.unreadSessionIds?.has(q.sessionId)&&q.sessionId!==d?u.jsxs("span",{className:"session-unread","aria-label":"有新消息",children:["●"," "]}):null,ce(q.sessionId)?`${ce(q.sessionId)} 项待审批`:q.running?"进行中":cE(q.status),n.showTurnCounts!==!1?u.jsxs("span",{children:[" · ",q.turnCount," 轮"]}):null]})]})},q.sessionId)),f.length===0&&M.length===0?u.jsx("li",{className:"empty",children:"开始对话后,记录会保存在这里。"}):null]}),u.jsxs("div",{className:"rail-footer",children:[u.jsxs("div",{className:"host-label",children:[u.jsx("span",{className:`dot ${s}`}),u.jsxs("span",{children:[G,lt]})]}),n.host==="hub"?u.jsxs("button",{className:"account-button",onClick:()=>{mt(),se(!0)},children:[u.jsx("span",{className:"account-avatar",children:(F?.username||"C").slice(0,1).toUpperCase()}),u.jsxs("span",{className:"account-copy",children:[u.jsx("strong",{children:F?.username||"账号"}),u.jsx("span",{children:"设备与退出"})]}),u.jsx(Et,{name:"chevron"})]}):null,n.logout?u.jsxs("button",{className:"account-button",onClick:n.logout,children:[u.jsx("span",{className:"account-avatar",children:(n.accountName||"D").slice(0,1)}),u.jsxs("span",{className:"account-copy",children:[u.jsx("strong",{children:n.accountName||"已配对设备"}),u.jsx("span",{children:"退出此设备"})]})]}):null]})]}),u.jsxs("main",{className:"workbench-main",inert:xe&&ye?!0:void 0,children:[u.jsxs("header",{className:"workbench-topbar",children:[u.jsx("button",{ref:Ye,className:"icon-button","aria-label":ye?"收起侧栏":"展开侧栏","aria-expanded":ye,"aria-controls":"workbench-sidebar",onClick:()=>Ae(q=>!q),children:u.jsx(Et,{name:"sidebar"})}),u.jsx("span",{className:"topbar-title",title:Be,children:Be}),u.jsxs("span",{className:"connection-pill",title:`任务在${G}工作区执行`,children:[u.jsx("span",{className:`dot ${s}`}),u.jsx("span",{children:G})]})]}),b?u.jsx("div",{className:"banner",children:b}):null,y?u.jsx("div",{className:"banner",children:y}):null,v?u.jsxs("div",{className:"banner form-error",role:"alert",children:[v,u.jsx("button",{className:"ghost","aria-label":"关闭错误提示",onClick:n.clearError,children:"×"})]}):null,B.length?u.jsxs("div",{className:"banner",children:["其他会话有待处理审批。",B.map(q=>u.jsxs("button",{className:"ghost",onClick:()=>{me(q.sessionId)},children:["打开 ",q.sessionId.slice(0,8)]},q.id))]}):null,s!=="open"?u.jsxs("div",{className:"banner",children:["连接",s==="connecting"?"中…":"已断开,重连中…"]}):null,E!=="chat"&&Ce.length>0?u.jsxs("div",{className:"banner",children:["当前对话需要你的确认。",u.jsx("button",{className:"ghost",onClick:()=>ot(()=>U("chat")),children:"返回对话"})]}):null,u.jsxs("section",{className:`chat${Se?" chat-empty":""}`,hidden:E!=="chat","aria-label":"对话",children:[u.jsx("div",{className:"messages",ref:jt,onScroll:q=>{const ze=q.currentTarget;at.current=ze.scrollHeight-ze.scrollTop-ze.clientHeight<100},children:u.jsxs("div",{className:"transcript",children:[n.chatControls,n.loading?u.jsx("div",{className:"banner",role:"status",children:"正在恢复会话记录…"}):null,o.goal?u.jsxs("div",{className:"banner goal",children:[u.jsx("span",{children:o.goal}),n.goalActions]}):null,o.items.map(q=>{switch(q.kind){case"user":return u.jsxs("div",{className:"msg user",children:[q.text,q.attachments?.map((ze,St)=>A&&ze.path?u.jsxs("button",{className:"attachment attachment-open",onClick:()=>Gt(ze.path),children:["📎 ",ze.name]},St):u.jsxs("span",{className:"attachment",children:["📎 ",ze.name]},St))]},q.id);case"assistant":return q.done&&!q.text&&!q.reasoning?null:u.jsx("div",{className:"msg assistant",children:u.jsx($C,{text:q.text,reasoning:q.reasoning,streaming:!q.done,onOpenFile:A?qt:void 0})},q.id);case"tool":return u.jsx("div",{className:`msg tool${q.error?" tool-error":""}`,children:u.jsx(PC,{item:q,running:H})},q.id);case"subagent":return u.jsxs("div",{className:"msg info",children:["↳ ",q.label," · ",WC(q.status)]},q.id);case"system_error":return u.jsx("div",{className:"msg error",children:q.text},q.id);default:return null}}),n.approvalContent,Se?u.jsxs("div",{className:"empty-chat",children:[u.jsx("span",{className:"welcome-mark",children:u.jsx(Et,{name:"brand"})}),u.jsx("h1",{children:"今天想完成什么?"}),u.jsx("p",{children:"从一个问题或想法开始,让 CodeShell 帮你一步步完成。"}),u.jsxs("span",{className:"welcome-workspace",children:[u.jsx(Et,{name:"folder"}),r??N]})]}):null]})}),n.readOnlyNote?u.jsx("div",{className:"banner",children:n.readOnlyNote}):null,u.jsxs("div",{className:"composer-wrap",children:[u.jsxs("footer",{className:"composer",children:[g.length||p&&n.host==="hub"?u.jsxs("div",{className:"attachments","aria-live":"polite",children:[g.map(q=>u.jsxs("span",{className:"attachment",children:[u.jsx(Et,{name:"attachment"}),q.name,u.jsx("button",{className:"ghost","aria-label":`移除 ${q.name}`,onClick:()=>{n.removeFile(q.id)},children:"×"})]},q.id)),p&&n.host==="hub"?u.jsx("span",{children:"正在上传…"}):null]}):null,u.jsx("textarea",{ref:Yt,"aria-label":"任务内容",value:m,disabled:n.readOnly,rows:2,placeholder:"描述你的任务,或提出一个问题…",onChange:q=>{n.setDraft(q.target.value)},onKeyDown:q=>{q.key==="Enter"&&!q.shiftKey&&!q.nativeEvent.isComposing&&(q.preventDefault(),ge())}}),u.jsxs("div",{className:"composer-toolbar",children:[A?u.jsxs(u.Fragment,{children:[u.jsx("input",{hidden:!0,multiple:!0,type:"file",accept:n.attachmentAccept,ref:ae,onChange:q=>{const ze=q.currentTarget;Promise.resolve(n.addFiles(ze.files)).finally(()=>{ze.value=""})}}),u.jsx("button",{className:"icon-button attach-button","aria-label":"添加附件",title:"添加附件",disabled:n.uploadBusy||s!=="open"||n.readOnly,onClick:()=>ae.current?.click(),children:u.jsx(Et,{name:"plus"})}),n.cameraAttachments?u.jsxs(u.Fragment,{children:[u.jsx("input",{hidden:!0,type:"file",accept:"image/*",capture:"environment",ref:P,onChange:q=>{const ze=q.currentTarget;Promise.resolve(n.addFiles(ze.files)).finally(()=>{ze.value=""})}}),u.jsx("button",{className:"icon-button attach-button","aria-label":"拍照",title:"拍照",disabled:n.uploadBusy||s!=="open"||n.readOnly,onClick:()=>P.current?.click(),children:u.jsx(Et,{name:"camera"})})]}):null,u.jsxs("button",{className:"model-button",title:"打开模型设置",onClick:()=>ut("models"),children:[u.jsx("span",{children:Ke?.model||"配置模型"}),u.jsx(Et,{name:"chevron"})]})]}):null,u.jsx("span",{className:"composer-run-status",role:"status",children:n.uncertain?"正在核对消息…":p?n.host==="desktop"?"正在发送…":"正在上传附件…":Ce.length?"等待你的确认":H?"正在处理…":""}),H?u.jsx("button",{className:"stop composer-submit","aria-label":"停止",title:"停止",onClick:ke,disabled:s!=="open",children:u.jsx(Et,{name:"stop"})}):u.jsx("button",{className:"send composer-submit","aria-label":"发送",title:"发送",onClick:ge,disabled:s!=="open"||p||n.uncertain||n.readOnly||!m.trim()&&!g.length,children:u.jsx(Et,{name:"send"})})]})]}),u.jsxs("div",{className:"composer-caption",children:[u.jsxs("span",{children:["任务在",G,"工作区执行"]}),u.jsx("span",{children:"Enter 发送 · Shift + Enter 换行"})]})]})]}),E==="settings"&&A?u.jsx(l0,{host:n.host==="desktop"?"desktop":"hub",section:je,onSectionChange:ut,onAuthLost:R,onConfigurationChange:()=>{ie()},configurationVersion:z,onDirtyChange:ve},`${n.workspaceKey}:settings`):null,E==="files"&&A?u.jsx(c0,{initialPath:k,openVersion:K,onAuthLost:R},`${n.workspaceKey}:files`):null,E==="history"&&A?u.jsx(f0,{onAuthLost:R,onOpen:q=>{me(q)},onChanged:()=>{W()},version:_,onDirtyChange:ve},`${n.workspaceKey}:history`):null,E==="links"&&A?u.jsx(h0,{onAuthLost:R,onDirtyChange:ve,hostLabel:G,configurationVersion:z},`${n.workspaceKey}:links`):null,E==="panels"&&A?u.jsx(m0,{onAuthLost:R,onDirtyChange:ve,onChanged:()=>{ie()},hostLabel:G,configurationVersion:z,onOpen:q=>ot(()=>{he({panel:q,workspaceKey:n.workspaceKey}),U("panel"),mt()})},`${n.workspaceKey}:panels`):null,E==="panel"&&A&&te?.workspaceKey===n.workspaceKey?u.jsx(S0,{panel:te.panel,sessionId:d,busy:H||p||n.uncertain,onAuthLost:R,onDirtyChange:ve,onClose:()=>ot(()=>U("panels")),onSubmitPrompt:async q=>sE(n,{...q,workspaceKey:te.workspaceKey})},`${n.workspaceKey}:panel:${te.panel.id}:${d}`):null]}),Q?u.jsx(oE,{onStay:()=>pe(null),onLeave:()=>{const q=Q;pe(null),ve(!1),q()}}):null,V&&n.host==="hub"?u.jsx(wv,{session:F,onClose:()=>se(!1),onAuthLost:R}):null]})}function oE({onStay:n,onLeave:i}){const r=w.useRef(null);return w.useEffect(()=>{const s=document.activeElement;return r.current?.showModal(),()=>{r.current?.close(),s?.focus()}},[]),u.jsxs("dialog",{className:"navigation-prompt",ref:r,"aria-labelledby":"navigation-prompt-title",onCancel:s=>{s.preventDefault(),n()},children:[u.jsx("h2",{id:"navigation-prompt-title",children:"还有未保存的修改"}),u.jsx("p",{children:"离开会丢弃未提交的修改;切换项目还会清除未发送的草稿和附件。已经提交的操作可能仍会完成,请等待结果后再离开。"}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button primary",onClick:n,autoFocus:!0,children:"留在此页"}),u.jsx("button",{className:"library-button",onClick:i,children:"放弃修改并离开"})]})]})}function cE(n){switch(n){case"running":return"进行中";case"waiting":case"waiting_approval":return"等待确认";case"completed":return"已完成";case"cancelled":case"canceled":return"已停止";case"failed":case"error":return"发生错误";case"idle":return"可继续";default:return"对话"}}function Et({name:n}){const i={panels:u.jsxs(u.Fragment,{children:[u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),u.jsx("path",{d:"M15 3v18M15 10h6"})]}),camera:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M3 7h4l2-3h6l2 3h4v13H3Z"}),u.jsx("circle",{cx:"12",cy:"13",r:"4"})]}),links:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2"}),u.jsx("path",{d:"M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})]}),brand:u.jsx(u.Fragment,{children:u.jsx("path",{d:"m5 7 5 5-5 5M13 17h6"})}),sidebar:u.jsxs(u.Fragment,{children:[u.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),u.jsx("path",{d:"M9 4v16"})]}),plus:u.jsx("path",{d:"M12 5v14M5 12h14"}),chat:u.jsx("path",{d:"M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"}),history:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),u.jsx("path",{d:"M3 3v5h5M12 7v5l3 2"})]}),skills:u.jsx(u.Fragment,{children:u.jsx("path",{d:"m12 3 2.7 5.5L21 9.4l-4.5 4.4 1.1 6.2L12 17.1 6.4 20l1.1-6.2L3 9.4l6.3-.9L12 3Z"})}),settings:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"m9 3-.7 3-2.6 1-2.6 2 1.4 3-1.4 3 2.6 2 2.6 1 .7 3h6l.7-3 2.6-1 2.6-2-1.4-3 1.4-3-2.6-2-2.6-1L15 3H9Z"}),u.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),folder:u.jsx("path",{d:"M3 7V5a1 1 0 0 1 1-1h5l2 3h9a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7Z"}),chevron:u.jsx("path",{d:"m9 5 7 7-7 7"}),attachment:u.jsx("path",{d:"m21 11-8 8a6 6 0 0 1-8.5-8.5l9-9A4 4 0 0 1 19 7l-9 9a2 2 0 0 1-2.8-2.8l8-8"}),send:u.jsx("path",{d:"M12 19V5m-6 6 6-6 6 6"}),stop:u.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2",fill:"currentColor",stroke:"none"})};return u.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i[n]})}class Ll extends Error{constructor(i,r,s){super(i),this.kind=r,this.code=s,this.name="ProtocolRequestError"}kind;code}const fE=3e4,zg=800,dE=15e3;class hE{constructor(i){this.url=i}url;ws=null;nextId=1;pending=new Map;notificationHandlers=new Set;stateHandlers=new Set;reconnectDelay=zg;closedByUser=!1;reconnectTimer;authHandlers=new Set;connect(){this.ws||(clearTimeout(this.reconnectTimer),this.closedByUser=!1,this.openSocket())}openSocket(){if(this.closedByUser)return;this.reconnectTimer=void 0,this.emitState("connecting");const i=new WebSocket(this.url);this.ws=i,i.onopen=()=>{this.ws!==i||this.closedByUser||(this.reconnectDelay=zg,this.emitState("open"))},i.onmessage=r=>{if(this.ws!==i||this.closedByUser)return;let s;try{if(s=JSON.parse(String(r.data)),!s||typeof s!="object"||Array.isArray(s))return}catch{return}if(s.id!==void 0&&s.method===void 0){const f=this.pending.get(String(s.id));if(!f)return;this.pending.delete(String(s.id)),clearTimeout(f.timer),s.error?f.reject(new Ll(s.error.message??"request failed","response",s.error.code)):f.resolve(s.result);return}if(s.method)for(const f of this.notificationHandlers)f(s.method,s.params??{})},i.onclose=r=>{if(this.ws===i){if(this.ws=null,this.emitState("closed"),this.failAllPending(new Ll("connection closed","transport")),r.code===4401||r.code===4403){this.closedByUser=!0;for(const s of this.authHandlers)s()}this.closedByUser||(this.reconnectTimer=setTimeout(()=>this.openSocket(),this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*2,dE))}},i.onerror=()=>{}}close(){this.closedByUser=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const i=this.ws;this.ws=null,i?.close(),this.failAllPending(new Ll("connection closed","transport"))}onNotification(i){return this.notificationHandlers.add(i),()=>this.notificationHandlers.delete(i)}onStateChange(i){return this.stateHandlers.add(i),()=>this.stateHandlers.delete(i)}onAuthLost(i){return this.authHandlers.add(i),()=>this.authHandlers.delete(i)}request(i,r,s=fE){const f=this.ws;if(!f||f.readyState!==WebSocket.OPEN)return Promise.reject(new Ll("not connected","not-sent"));const d=`web-${this.nextId++}`;return new Promise((o,m)=>{const g=s>0?setTimeout(()=>{this.pending.delete(d),m(new Ll(`request timed out: ${i}`,"timeout"))},s):void 0;this.pending.set(d,{resolve:o,reject:m,timer:g});try{f.send(JSON.stringify({jsonrpc:"2.0",id:d,method:i,params:r}))}catch(p){clearTimeout(g),this.pending.delete(d),m(new Ll(p instanceof Error?p.message:"send failed","not-sent"))}})}run(i){return this.request("agent/run",i,0)}listSessions(){return this.request("agent/query",{type:"sessions"})}sessionDetail(i){return this.request("agent/query",{type:"session_detail",sessionId:i})}approve(i,r,s){return this.request("agent/approve",{sessionId:i.sessionId??"",...i.connectionId?{connectionId:i.connectionId}:{},...i.generation!==void 0?{generation:i.generation}:{},requestId:i.requestId,decision:r?{approved:!0,...s?{answer:s}:{}}:{approved:!1}})}cancel(i){return this.request("agent/cancel",{sessionId:i})}emitState(i){for(const r of this.stateHandlers)r(i)}failAllPending(i){for(const[,r]of this.pending)clearTimeout(r.timer),r.reject(i);this.pending.clear()}}function pE(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${Rt("/ws")}`}function mE(n,i){const{method:r,params:s}=i;if(r==="serve/approvalSnapshot"){if(!Array.isArray(s.approvals))return n;const d={};for(const o of s.approvals)o?.requestId&&o.request&&(d[o.requestId]={payload:o});return d}if(r==="agent/approvalRequest"){const d=s;return!d.requestId||!d.request?n:{...n,[d.requestId]:{...n[d.requestId],payload:d}}}const f=s.requestId;if(typeof f!="string"||!n[f])return n;if(r==="agent/approvalResolved"){const d={...n};return delete d[f],d}return r==="serve/approvalLease"?{...n,[f]:{...n[f],lease:s}}:n}class gE{drafts=new Map;get(i){return this.drafts.get(i)??{text:"",files:[],revision:0}}update(i,r){const s={...r,revision:this.get(i).revision+1};return this.drafts.set(i,s),s}setText(i,r){return this.update(i,{...this.get(i),text:r})}addFile(i,r){const s=this.get(i);return this.update(i,{...s,files:[...s.files,r]})}removeFile(i,r){const s=this.get(i);return this.update(i,{...s,files:s.files.filter(f=>f.id!==r)})}take(i){const r=this.get(i),s=this.update(i,{text:"",files:[]});return{sessionId:i,draft:r,clearedRevision:s.revision}}restore(i){const r=this.get(i.sessionId);return r.revision!==i.clearedRevision||r.text||r.files.length?!1:(this.update(i.sessionId,i.draft),!0)}unsent(){return[...this.drafts].flatMap(([i,r])=>r.text.trim()||r.files.length?[{sessionId:i,draft:r}]:[])}}const yE="codeshell.uiLanguage";function bE(){try{const n=globalThis.localStorage?.getItem(yE);if(n==="zh"||n==="en")return n}catch{}return"zh"}const xE={zh:{mobile:{app:{extendGoal:"延长目标",clearGoal:"清除目标",loadingCcSession:"正在加载 CC 会话…",loadingSession:"正在加载会话…",conversationFallback:"对话",desktopSession:"桌面会话",newSession:"新会话",openSessionsAria:"打开会话",leaveSessionAria:"退出会话",deviceFallback:"设备",logoutAria:"退出登录",permission:"权限",ccRoomObserving:"此会话当前为只读查看;请在桌面端明确接管后再发送消息。"},approval:{risk:{low:"低风险",medium:"中风险",high:"高风险"},readSourceSummary:"读取数据源 {source} / {scope} / {resource}",question:"问题",customPlaceholder:"或输入自定义回答…",sendCustom:"发送自定义回答",rememberScope:"记住范围",scope:{once:"仅本次",session:"本会话",project:"本项目"},pathScopeLabel:"路径范围",pathScope:{file:"此文件",dir:"此目录",tool:"此工具"},allow:"允许",reject:"拒绝"},cc:{title:"CC 会话",subtitle:"外部 {label} 会话",selectProjectFirst:"先选择一个项目。",probingCli:"正在检测 {label} CLI…",cliMissing:"未检测到 {label} CLI(需在桌面端机器的 PATH 中)。",loadingSessions:"正在加载 cc 会话…",empty:"该项目下没有 {label} 会话。",messageCount:"{count} 条"},sidePane:{localTab:"会话",ccTab:"CC 会话"},composer:{disconnected:"未连接",placeholder:"发消息…",stop:"停止",send:"发送",chooseImages:"从相册选择图片",takePhoto:"拍照",removeImage:"移除图片",uploading:"上传中…",tooManyImages:"每条消息最多发送 4 张图片",unsupportedImage:"不支持此图片格式",sendFailed:"图片发送失败,请重试"},connection:{connectingTitle:"正在连接…",connectingBody:"与 CodeShell 建立通道",authenticatingTitle:"认证中…",authenticatingBody:"正在校验设备身份",unpairedTitle:"未配对",unpairedBody:"请在 CodeShell 桌面端打开「设置 → 远程」,扫码或打开配对链接。",offlineTitle:"连接断开",offlineBody:"正在自动重连…"},format:{noProject:"无项目",justNow:"刚刚",minutesAgo:"{n} 分钟前",hoursAgo:"{n} 小时前",daysAgo:"{n} 天前",monthsAgo:"{n} 个月前",yearsAgo:"{n} 年前"},notice:{roomMissing:"会话不存在或未就绪",roomError:"会话错误",sessionRecoveryIncomplete:"当前回复的开头尚未恢复,请重新打开会话以读取已保存的内容。",sessionRecoveryHistoryOnly:"已恢复保存的聊天记录。当前回复的实时部分暂时无法接续,请稍后重新打开会话。",goalExtendFailed:"延长目标失败",ccRoomOpenFailed:"cc 会话无法打开",ccRoomObserving:"此 CC 会话当前为只读查看,消息未发送",attachmentSendFailed:"图片发送失败:{error}"},permissionMode:{default:"默认",acceptEdits:"自动改",bypassPermissions:"全放行",defaultDesc:"每个工具调用都要你确认",acceptEditsDesc:"自动放行文件编辑,其余仍确认",bypassDesc:"跳过所有权限确认(危险)",title:"选择权限模式",confirmBypass:"全放行模式会跳过所有权限确认。确定吗?"},sessionList:{title:"会话",takeoverCount:"{count} 个可接管",refreshAria:"刷新会话",new:"新建",createHint:"新会话默认使用当前目录",currentProject:"当前项目 · {name}",noProjectConversation:"无项目对话",desktopCwd:"当前桌面目录",unboundRepo:"不绑定 repo",followsDesktopCwd:"跟随桌面当前 cwd",otherProjects:"其他项目",loading:"正在加载会话…",empty:"还没有会话。点「新建」开一个,或在桌面端开始。",automation:"自动",noProjectPath:"无项目路径",unreadAria:"有新内容",primaryRoot:"主目录",secondaryRoot:"次目录"},status:{conn:{connecting:"连接中…",authenticating:"认证中…",unpaired:"未配对",online:"在线",offline:"已断开"},run:{idle:"空闲",running:"运行中",waiting:"待审批",completed:"已完成",error:"出错"}},storage:{browserDevice:"{platform} 浏览器"},stream:{showReasoning:"显示思考",hideReasoning:"隐藏思考",subagent:"子代理",loading:"正在加载…",generating:"正在生成回复",emptyHint:"发个任务试试,或在侧栏打开一个 Claude Code 会话。"},tool:{running:"运行中",failed:"失败",completed:"完成",fallbackName:"操作",truncated:"… (已截断)"}}},en:{mobile:{app:{extendGoal:"Extend goal",clearGoal:"Clear goal",loadingCcSession:"Loading CC session…",loadingSession:"Loading conversation…",conversationFallback:"Conversation",desktopSession:"Desktop session",newSession:"New session",openSessionsAria:"Open sessions",leaveSessionAria:"Leave session",deviceFallback:"Device",logoutAria:"Log out",permission:"Permission",ccRoomObserving:"This session is read-only. Take it over explicitly on desktop before sending messages."},approval:{risk:{low:"Low risk",medium:"Medium risk",high:"High risk"},readSourceSummary:"Read data source {source} / {scope} / {resource}",question:"Question",customPlaceholder:"Or enter a custom answer…",sendCustom:"Send custom answer",rememberScope:"Remember scope",scope:{once:"Once",session:"This session",project:"This project"},pathScopeLabel:"Path scope",pathScope:{file:"This file",dir:"This directory",tool:"This tool"},allow:"Allow",reject:"Deny"},cc:{title:"CC sessions",subtitle:"External {label} sessions",selectProjectFirst:"Select a project first.",probingCli:"Checking {label} CLI…",cliMissing:"{label} CLI was not found (it must be in PATH on the desktop machine).",loadingSessions:"Loading cc sessions…",empty:"No {label} sessions in this project.",messageCount:"{count} messages"},sidePane:{localTab:"Sessions",ccTab:"CC"},composer:{disconnected:"Disconnected",placeholder:"Message…",stop:"Stop",send:"Send",chooseImages:"Choose images",takePhoto:"Take photo",removeImage:"Remove image",uploading:"Uploading…",tooManyImages:"Up to 4 images can be sent per message",unsupportedImage:"This image format is not supported",sendFailed:"Could not send images; try again"},connection:{connectingTitle:"Connecting…",connectingBody:"Opening a channel to CodeShell",authenticatingTitle:"Authenticating…",authenticatingBody:"Verifying this device",unpairedTitle:"Not paired",unpairedBody:"Open Settings → Remote in CodeShell desktop, then scan the QR code or open the pairing link.",offlineTitle:"Disconnected",offlineBody:"Reconnecting automatically…"},format:{noProject:"No project",justNow:"Just now",minutesAgo:"{n} min ago",hoursAgo:"{n} hr ago",daysAgo:"{n} days ago",monthsAgo:"{n} mo ago",yearsAgo:"{n} yr ago"},notice:{roomMissing:"Session does not exist or is not ready",roomError:"Session error",sessionRecoveryIncomplete:"The beginning of this reply could not be restored. Reopen the conversation to read its saved content.",sessionRecoveryHistoryOnly:"Saved chat history has been restored. Reopen the conversation later to see the rest of this reply.",goalExtendFailed:"Failed to extend goal",ccRoomOpenFailed:"Could not open cc session",ccRoomObserving:"This CC session is read-only; the message was not sent",attachmentSendFailed:"Could not send images: {error}"},permissionMode:{default:"Default",acceptEdits:"Auto-edit",bypassPermissions:"Allow all",defaultDesc:"Confirm every tool call",acceptEditsDesc:"Allow file edits automatically; confirm everything else",bypassDesc:"Skip all permission confirmations (dangerous)",title:"Choose permission mode",confirmBypass:"Allow all mode skips every permission confirmation. Continue?"},sessionList:{title:"Sessions",takeoverCount:"{count} available",refreshAria:"Refresh sessions",new:"New",createHint:"New sessions default to the current directory",currentProject:"Current project · {name}",noProjectConversation:"No-project conversation",desktopCwd:"Current desktop directory",unboundRepo:"Do not bind a repo",followsDesktopCwd:"Follow desktop current cwd",otherProjects:"Other projects",loading:"Loading sessions…",empty:"No sessions yet. Tap “New” to start one, or start from desktop.",automation:"Automation",noProjectPath:"No project path",unreadAria:"New content",primaryRoot:"Primary",secondaryRoot:"Secondary"},status:{conn:{connecting:"Connecting…",authenticating:"Authenticating…",unpaired:"Not paired",online:"Online",offline:"Disconnected"},run:{idle:"Idle",running:"Running",waiting:"Awaiting approval",completed:"Completed",error:"Error"}},storage:{browserDevice:"{platform} browser"},stream:{showReasoning:"Show reasoning",hideReasoning:"Hide reasoning",subagent:"Subagent",loading:"Loading…",generating:"Generating response",emptyHint:"Send a task, or open a Claude Code session from the sidebar."},tool:{running:"Running",failed:"Failed",completed:"Completed",fallbackName:"Operation",truncated:"… (truncated)"}}}},Rg=xE;function _g(n,i){let r=n;for(const s of i.split(".")){if(r==null||typeof r!="object")return;r=r[s]}return typeof r=="string"?r:void 0}function vE(n,i){return i?n.replace(/\{(\w+)\}/g,(r,s)=>s in i?String(i[s]):r):n}function SE(n,i,r){const s=_g(Rg[n],i)??_g(Rg.zh,i)??i;return vE(s,r)}function jE(n,i){return SE(bE(),n,i)}const kE=["command","file_path","path","url","pattern","query"];function wE(n,i,r){let s="";const f=n?.source,d=n?.scope,o=n?.resource;if(r==="ReadSource"&&typeof f=="string"&&f.length>0&&typeof d=="string"&&d.length>0&&typeof o=="string"&&o.length>0)s=jE("mobile.approval.readSourceSummary",{source:f,scope:d,resource:o});else for(const g of kE){const p=n?.[g];if(typeof p=="string"&&p.length>0){s=p;break}}s||(s=JSON.stringify(n??{}));let m;return i==="low"||i==="medium"||i==="high"?m=i:i===void 0||i===""?m="medium":m="high",{summary:s,risk:m}}function CE({payload:n,onDecide:i,busy:r,connected:s}){const[f,d]=w.useState(""),o=n.request.toolName==="__ask_user__",{summary:m,risk:g}=wE(n.request.args,n.request.riskLevel,n.request.toolName);return u.jsxs("div",{className:"approval",children:[u.jsxs("div",{className:"approval-title",children:[o?"Agent 提问":`工具审批:${n.request.toolName}`,o?null:u.jsxs("em",{children:[" · ",g]})]}),n.request.description?u.jsx("div",{className:"approval-desc",children:n.request.description}):null,o?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"approval-summary",children:m}),u.jsxs("details",{className:"approval-raw",children:[u.jsx("summary",{children:"原始参数"}),u.jsx("pre",{className:"approval-args",children:JSON.stringify(n.request.args,null,2)})]})]}),o?u.jsx("textarea",{className:"approval-answer",value:f,placeholder:"输入回答…",onChange:p=>d(p.target.value)}):null,r?u.jsx("span",{className:"muted",role:"status",children:"设备正在处理此审批…"}):null,u.jsxs("div",{className:"approval-actions",children:[u.jsx("button",{className:"send",disabled:r||!s||o&&!f.trim(),onClick:()=>i(n,!0,o?f:void 0),children:o?"回答":"允许"}),u.jsx("button",{className:"stop",disabled:r||!s,onClick:()=>i(n,!1),children:"拒绝"})]})]})}function Dg(){return la()}const EE=()=>{},NE=async()=>{};function TE({session:n,hub:i=!1,onAuthLost:r=EE,onCheckAuth:s=NE}){const f=w.useRef(null),[d,o]=w.useState("connecting"),[m,g]=w.useState([]),p=w.useRef([]),[b,y]=w.useState(()=>aE(window.location.search)??Dg()),[v,S]=w.useState(As()),[N,D]=w.useReducer(mE,{}),[z,_]=w.useState({}),[M,H]=w.useState(""),[oe,ce]=w.useState([]),R=w.useRef(new gE),[W,ie]=w.useState(0),[F,A]=w.useState(null),G=F===b,[V,se]=w.useState(null),[ae,P]=w.useState(null),[E,U]=w.useState(""),[te,he]=w.useState(Date.now()),[k,T]=w.useState(0),[K,C]=w.useState(null),[re,ve]=w.useState(0),Q=w.useRef(0),pe=w.useRef(b),je=w.useRef(null),Y=w.useRef(new Map),xe=w.useRef(new Map),J=w.useRef(new Set),ye=w.useRef(new Set),Ae=w.useRef(new Set),we=w.useRef(!1),Ye=w.useRef(null),nt=w.useRef(null),jt=w.useCallback(de=>{if(ie(Je=>Je+1),pe.current!==de)return;const Re=R.current.get(de);H(Re.text),ce(Re.files)},[]);w.useEffect(()=>{const de=new URL(window.location.href);de.searchParams.set("session",b),window.history.replaceState(window.history.state,"",de)},[b]);const Yt=w.useCallback((de,Re)=>{const Je=R.current.restore(de.draft);jt(de.draft.sessionId),pe.current===de.draft.sessionId&&(S(_e=>({..._e,run:"error",items:_e.items.filter(Ue=>Ue.kind!=="user"||Ue.clientMessageId!==de.clientMessageId)})),Je&&U(`${Re?`${Re} `:"消息未送达。"}内容和附件已恢复,可以重试。`))},[jt]),at=w.useCallback(de=>{we.current&&(de instanceof We&&de.status===401?r():U(de instanceof Error?de.message:"操作失败,请重试。"))},[r]),mt=w.useCallback(async()=>{if(!i||!we.current)return;const de=++Q.current;try{const Re=await Hg();we.current&&de===Q.current&&C(Re)}catch(Re){we.current&&Re instanceof We&&Re.status===401&&r()}},[i,r]),ut=w.useCallback(async()=>{const de=f.current;if(de)try{const Re=i?(await Dc()).sessions:(await de.listSessions()).data;if(f.current===de&&we.current){const Je=[...Re].sort((_e,Ue)=>(Ue.lastActiveAt??Ue.startedAt)-(_e.lastActiveAt??_e.startedAt));p.current=Je,g(Je)}}catch(Re){at(Re)}},[at,i]),ot=w.useCallback(async()=>{const de=f.current;if(de)for(const[Re,Je]of xe.current)try{const _e=await de.sessionDetail(Re);if(!we.current||de!==f.current||xe.current.get(Re)!==Je)continue;Ag(_e.data).chat.items.some(Oe=>Oe.kind==="user"&&Oe.clientMessageId===Je.clientMessageId)?xe.current.delete(Re):_e.data.running||(xe.current.delete(Re),Yt(Je))}catch(_e){if(!we.current||de!==f.current||xe.current.get(Re)!==Je)continue;_e instanceof Ll&&_e.kind==="response"&&_e.code===-32001&&_e.message===`Session not found: ${Re}`&&(xe.current.delete(Re),Yt(Je))}},[Yt]),Gt=w.useCallback(async de=>{const Re=f.current;if(!Re)return;const Je={sessionId:de,events:[]};nt.current=Je;try{const _e=await Re.sessionDetail(de);if(!we.current||nt.current!==Je||pe.current!==de)return;const Ue=Je.running??_e.data.running;Ue?ye.current.add(de):Ue===!1&&ye.current.delete(de);const et=Ag(_e.data,Je.events),Oe=et.chat;je.current=et.cursor??null,P(et.truncated?"这次运行的实时记录较长,已恢复已保存的内容;结束后重新打开可查看完整记录。":null),Ue||J.current.has(de)?Oe.run="running":Ue===!1&&(Oe.run==="running"||Oe.run==="waiting")&&(Oe.run="idle"),S(Oe)}catch(_e){pe.current===de&&at(_e)}finally{nt.current===Je&&(nt.current=null)}},[at]);w.useEffect(()=>{we.current=!0;const de=new hE(pE());f.current=de;const Re=de.onAuthLost(r),Je=de.onStateChange(Ue=>{o(Ue),Ue==="open"?(se(null),U(""),ut().then(()=>{const et=pe.current;we.current&&f.current===de&&(p.current.some(Oe=>Oe.sessionId===et)||ye.current.has(et)||J.current.has(et)||xe.current.has(et))&&Gt(et)}),mt(),ot()):Ue==="closed"&&(i&&s(),S(et=>({...et,run:"idle"})))}),_e=de.onNotification((Ue,et)=>{if(Ue==="serve/sessionsChanged"){ut(),T(Oe=>Oe+1);return}if(Ue==="agent/runAccepted"&&typeof et.sessionId=="string"){const Oe=Y.current.get(et.sessionId);Oe&&(Oe.accepted=!0);return}if(Ue==="serve/configurationChanged"){mt(),ve(Oe=>Oe+1);return}if(Ue==="agent/streamEvent"){const Oe=et,{sessionId:_t,event:Ft}=Oe,ol=Y.current.get(_t);if(ol&&["stream_request_start","text_delta","thinking_delta","tool_use_start"].includes(String(Ft.type))&&(ol.accepted=!0),_t===pe.current){if(nt.current?.sessionId===_t&&nt.current.events.push(Oe),!Zy(Oe,je.current))return;Oe.hubEpoch&&Oe.hubSequence!==void 0&&(je.current={epoch:Oe.hubEpoch,sequence:Oe.hubSequence}),S(Qs=>Os(Qs,Ft))}Ft.type==="stream_request_start"&&se(null),Ft.type==="turn_complete"&&ut();return}if(Ue==="serve/sessionStatus"){T(Ft=>Ft+1);const{sessionId:Oe,running:_t}=et;if(typeof Oe!="string"||typeof _t!="boolean")return;nt.current?.sessionId===Oe&&(nt.current.running=_t),_t?ye.current.add(Oe):ye.current.delete(Oe),!_t&&xe.current.has(Oe)&&ot(),Oe===pe.current&&S(Ft=>_t?{...Ft,run:"running"}:Ft.run==="running"||Ft.run==="waiting"?{...Ft,run:"idle"}:Ft),ut();return}if(Ue==="agent/approvalRequest"||Ue==="agent/approvalResolved"||Ue==="serve/approvalSnapshot"||Ue==="serve/approvalLease"){D({method:Ue,params:et});return}if(Ue==="serve/workerExit"){ye.current.clear();const Oe=et.clean;se(Oe?"服务进程已退出,发送消息会自动重启":"服务进程异常退出,发送消息会自动重启"),S(_t=>({..._t,run:"idle"}))}});return de.connect(),()=>{we.current=!1,Ye.current?.abort(),Je(),_e(),Re(),de.close(),f.current=null}},[ut,Gt,mt,ot,r,s,i]);const vt=Object.values(N).some(de=>de.lease?.holderId&&(de.lease.expiresAt??0)>te);w.useEffect(()=>{if(!vt)return;he(Date.now());const de=setInterval(()=>he(Date.now()),1e3);return()=>clearInterval(de)},[vt]);const qt=async de=>{pe.current=de,je.current=null,y(de),jt(de),S(As()),U(""),P(null),!(!m.some(Re=>Re.sessionId===de)&&!ye.current.has(de)&&R.current.unsent().some(Re=>Re.sessionId===de))&&await Gt(de)},ne=()=>{const de=Dg();pe.current=de,je.current=null,nt.current=null,y(de),jt(de),S(As()),U(""),P(null)},me=()=>{const de=R.current.get(pe.current),Re=de.text.trim(),Je=f.current;if(!Re&&!de.files.length||!Je||d!=="open"||G)return!1;const _e=pe.current;if(J.current.has(_e)||ye.current.has(_e)||v.run==="running"||v.run==="waiting"||Object.values(N).some(Oe=>Oe.payload.sessionId===_e)||xe.current.has(_e))return!1;pe.current=_e,y(_e),J.current.add(_e);const Ue={clientMessageId:la(),draft:R.current.take(_e),accepted:!1};Y.current.set(_e,Ue);const et=Ue.draft.draft.files;return jt(_e),U(""),S(Oe=>({...nE(Oe,Re,et.map(_t=>({name:_t.name,mime:_t.mimeType,size:_t.size})),Ue.clientMessageId),run:"running"})),Je.run({sessionId:_e,task:Re,clientMessageId:Ue.clientMessageId,displayText:Re,...et.length?{uploadIds:et.map(Oe=>Oe.id)}:{}}).catch(Oe=>{we.current&&(at(Oe),Oe instanceof Ll&&(Oe.kind==="transport"||Oe.kind==="timeout")?(xe.current.set(_e,Ue),U("连接中断,重新连接后会核对这条消息是否已经送达。")):Ue.accepted||Yt(Ue,Oe instanceof Error?Oe.message==="upload not found or expired"?"附件已失效,请移除后重新上传。":Oe.message:void 0),pe.current===_e&&S(_t=>({..._t,run:"error"})))}).finally(()=>{J.current.delete(_e),Y.current.get(_e)===Ue&&Y.current.delete(_e),we.current&&pe.current===_e&&!ye.current.has(_e)&&S(Oe=>Oe.run==="running"?{...Oe,run:"idle"}:Oe)}),!0},Te=(de,Re,Je)=>{const _e=f.current;!_e||d!=="open"||Ae.current.has(de.requestId)||(Ae.current.add(de.requestId),_(Ue=>({...Ue,[de.requestId]:!0})),U(""),_e.approve({...de,sessionId:de.sessionId??pe.current??""},Re,Je).then(()=>D({method:"agent/approvalResolved",params:{requestId:de.requestId}})).catch(at).finally(()=>{Ae.current.delete(de.requestId),_(Ue=>{const et={...Ue};return delete et[de.requestId],et})}))},ge=()=>{b&&f.current?.cancel(b).catch(at)},ke=async de=>{if(!de?.length||Ye.current)return;const Re=new AbortController,Je=Ug();Ye.current=Re,A(pe.current),U("");const _e=pe.current;try{for(const Ue of Array.from(de)){if(!we.current||Re.signal.aborted)break;const et=await kv(Ue,{signal:Re.signal,scope:Je});we.current&&!Re.signal.aborted&&(R.current.addFile(_e,et),jt(_e))}}catch(Ue){at(Ue)}finally{Ye.current===Re&&(Ye.current=null),we.current&&A(null)}},Ce=Object.values(N).filter(de=>!de.payload.sessionId||de.payload.sessionId===b),B=de=>Object.values(N).filter(Re=>Re.payload.sessionId===de).length,Se=v.run==="running"||v.run==="waiting"||Ce.length>0,Ke=w.useMemo(()=>R.current.unsent().filter(de=>!m.some(Re=>Re.sessionId===de.sessionId)),[W,m]),lt=K?.workspace.path??m.find(de=>de.sessionId===b)?.cwd??m[0]?.cwd??null,Be=lt?.split(/[\\/]/).filter(Boolean).pop()??"服务端工作区",q=v.items.length===0&&Ce.length===0,ze=m.find(de=>de.sessionId===b),St=q?"新对话":ze?.customTitle||v.title||ze?.title||ze?.preview?.trim()||Ky(v,b??"新对话");return{host:i?"hub":"legacy",workspaceApi:i,connection:d,session:n,activeId:b,chat:v,sessions:m,workspaceCwd:lt,workspaceName:Be,title:St,workspaceKey:lt??"hub",configuration:K,configurationVersion:re,sessionsVersion:k,draft:M,files:oe,uploading:G,uploadBusy:F!==null,hasUnsent:R.current.unsent().length>0,localDrafts:Ke,uncertain:xe.current.has(b),running:Se,approvals:Object.values(N).map(de=>({id:de.payload.requestId,sessionId:de.payload.sessionId})),approvalCount:B,approvalContent:Ce.map(de=>u.jsx(CE,{payload:de.payload,onDecide:Te,busy:!!z[de.payload.requestId]||!!(de.lease?.holderId&&(de.lease.expiresAt??0)>te),connected:d==="open"},de.payload.requestId)),workerNote:V,replayNote:ae,error:E,clearError:()=>U(""),setDraft:de=>{R.current.setText(pe.current,de),jt(pe.current)},removeFile:de=>{R.current.removeFile(pe.current,de),jt(pe.current)},selectSession:qt,newSession:ne,send:me,stop:ge,addFiles:ke,refreshSessions:ut,refreshConfiguration:mt,onAuthLost:r}}function Og({onBackToProjects:n,projectName:i,...r}){return u.jsx(uE,{controller:TE(r),onBackToProjects:n,projectName:i})}function Fy(n){if(!n||typeof n!="object")return!1;const i=n;return Wr(i.id)&&typeof i.name=="string"&&i.name.length>0&&["stopped","starting","running","stopping","error"].includes(i.status)&&Number.isSafeInteger(i.generation)&&i.generation>=0&&Number.isSafeInteger(i.createdAt)&&i.createdAt>=0&&(i.error===void 0||typeof i.error=="string")}function AE(n){const i=n;if(!i||i.runtime!=="docker"||typeof i.available!="boolean"||!Array.isArray(i.projects)||!i.projects.every(Fy)||new Set(i.projects.map(r=>r.id)).size!==i.projects.length||i.error!==void 0&&typeof i.error!="string")throw new Error("服务端返回了无效的项目列表,请重试。");return i}function Mg(){return new URL(window.location.href).searchParams.get("project")}function Fr(n,i=!1){const r=new URL(window.location.href);n?r.searchParams.set("project",n):r.searchParams.delete("project"),i||r.searchParams.delete("session"),window.history.replaceState(window.history.state,"",r)}const zE={stopped:"已停止",starting:"正在启动",running:"运行中",stopping:"正在停止",error:"启动失败"};function RE({children:n,onAuthLost:i}){const[r,s]=w.useState(null),[f,d]=w.useState(!1),[o,m]=w.useState(null),[g,p]=w.useState(""),[b,y]=w.useState(!0),[v,S]=w.useState(null),[N,D]=w.useState(""),[z,_]=w.useState(null),M=w.useRef(null),H=w.useRef(Mg()),oe=w.useRef(o),ce=w.useRef(r),R=w.useRef(0),W=w.useRef(0),ie=w.useRef(null),F=w.useRef(i),A=w.useRef(!1);F.current=i,oe.current=o,ce.current=r;const G=w.useCallback(E=>{if(E.status!=="running")return;const U=Mg()===E.id;vs(),xs(E.id),Fr(E.id,U),H.current=null,oe.current=E,m(E),p("")},[]),V=w.useCallback(()=>{H.current=null,oe.current=null,m(null),xs(null),vs(),Fr(null)},[]),se=w.useCallback(async E=>{if(A.current)return;const U=++W.current,te=R.current;try{const he=AE(await Ve("/api/v1/projects",{signal:E}));if(E?.aborted||U!==W.current||te!==R.current)return;s(he),ce.current=he,y(!1),p("");const k=oe.current;if(k){const K=he.projects.find(C=>C.id===k.id);(!K||K.status!=="running"||K.generation!==k.generation)&&(V(),p("项目运行状态已经变化,请重新打开项目。未发送的内容不会带入其他项目。"));return}if(!H.current)return;const T=he.projects.find(K=>K.id===H.current);T?T.status==="running"&&he.available&&G(T):(H.current=null,Fr(null),p("链接中的项目不存在或当前账号无权访问,请选择一个项目。"))}catch(he){if(E?.aborted||U!==W.current||te!==R.current)return;y(!1),he instanceof We&&he.status===404&&!ce.current?(xs(null),vs(),A.current=!0,d(!0)):he instanceof We&&he.status===401?F.current():p(he instanceof Error?he.message:"无法读取项目,请重试。")}},[V,G]);w.useEffect(()=>{R.current++;const E=new AbortController;se(E.signal);const U=()=>{se(E.signal)},te=()=>{document.visibilityState==="visible"&&U()};return window.addEventListener("focus",U),document.addEventListener("visibilitychange",te),()=>{R.current++,E.abort(),ie.current?.abort(),window.removeEventListener("focus",U),document.removeEventListener("visibilitychange",te),xs(null),vs()}},[se]);const ae=r?.projects.some(E=>E.status==="starting"||E.status==="stopping");w.useEffect(()=>{if(f||!r)return;const E=new AbortController,U=setInterval(()=>{se(E.signal)},ae?2e3:1e4);return()=>{clearInterval(U),E.abort()}},[f,!!r,ae,se]),w.useEffect(()=>{if(!z)return;const E=document.activeElement,U=M.current;return U?.showModal?.(),()=>{U?.close?.(),E?.focus()}},[z]);const P=async(E,U)=>{if(ie.current||E==="create"&&!N.trim())return;const te=new AbortController;ie.current=te,S(U?.id??"create"),p(""),W.current++;try{const he=await Ve(E==="create"?"/api/v1/projects":`/api/v1/projects/${U.id}/${E}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E==="create"?{name:N.trim()}:{}),signal:te.signal});if(te.signal.aborted)return;if(!Fy(he.project)||U&&U.id!==he.project.id)throw new Error("服务端返回了无效的项目状态,请刷新列表。");const k=he.project;s(T=>T&&{...T,projects:T.projects.some(K=>K.id===k.id)?T.projects.map(K=>K.id===k.id?k:K):[...T.projects,k]}),E==="create"&&D(""),E==="start"&&(H.current=k.id,Fr(k.id),k.status==="running"&&G(k)),E==="stop"&&(H.current===k.id&&(H.current=null,Fr(null)),_(null)),await se(te.signal)}catch(he){if(te.signal.aborted)return;he instanceof We&&he.status===401?F.current():p(he instanceof Error?he.message:"项目操作失败,请重试。")}finally{ie.current===te&&(ie.current=null),te.signal.aborted||S(null)}};return f?u.jsx(w.Fragment,{children:n(null)},"single-project"):o?u.jsxs(w.Fragment,{children:[g?u.jsxs("div",{className:"project-connection-note",role:"status",children:["项目状态暂时无法刷新,当前工作台会保留。",g]}):null,n(o,V)]},`${o.id}:${o.generation}`):u.jsxs("main",{className:"projects-page",children:[u.jsxs("header",{className:"projects-header",children:[u.jsxs("div",{className:"auth-brand",children:["CodeShell ",u.jsx("span",{children:"Hub"})]}),u.jsx("h1",{children:"你的项目"}),u.jsx("p",{children:"每个项目有独立的运行环境、文件、会话和配置。启动后进入同一个工作台。"})]}),b?u.jsx("p",{role:"status",children:"正在读取项目…"}):null,g?u.jsxs("div",{className:"form-error",role:"alert",children:[g,u.jsx("button",{className:"library-button",onClick:()=>{se()},children:"刷新项目"})]}):null,r?u.jsxs(u.Fragment,{children:[r.available?null:u.jsxs("p",{className:"form-error",role:"alert",children:["项目运行环境暂不可用。",r.error||"请检查服务端 Docker 是否已启动。"]}),u.jsxs("form",{className:"project-create",onSubmit:E=>{E.preventDefault(),P("create")},children:[u.jsxs("label",{children:["新项目名称",u.jsx("input",{value:N,maxLength:80,required:!0,placeholder:"例如:个人网站",onChange:E=>D(E.target.value)})]}),u.jsx("button",{className:"library-button primary",disabled:!!v||!N.trim(),type:"submit",children:v==="create"?"正在创建…":"创建项目"})]}),u.jsxs("section",{className:"projects-grid","aria-label":"项目列表",children:[r.projects.length===0?u.jsx("p",{className:"project-empty",children:"创建第一个项目,开始配置模型、添加技能和使用面板。"}):null,r.projects.map(E=>u.jsxs("article",{className:"project-card",children:[u.jsxs("div",{className:"project-card-heading",children:[u.jsx("h2",{children:E.name}),u.jsx("span",{className:`project-status ${E.status}`,children:zE[E.status]})]}),u.jsxs("p",{className:"project-date",children:["创建于 ",new Date(E.createdAt).toLocaleDateString()]}),E.error?u.jsx("p",{className:"form-error",role:"alert",children:E.error}):null,u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button primary",disabled:!!v||!r.available||E.status==="starting"||E.status==="stopping",onClick:()=>E.status==="running"?G(E):void P("start",E),children:v===E.id||E.status==="starting"||E.status==="stopping"?"正在处理…":E.status==="running"?"打开项目":"启动并打开"}),E.status==="running"?u.jsx("button",{className:"library-button",disabled:!!v,onClick:()=>_(E),children:"停止项目"}):null]})]},E.id))]})]}):null,z?u.jsxs("dialog",{className:"project-stop-confirm",ref:M,role:"alertdialog","aria-modal":"true","aria-labelledby":"project-stop-title",onCancel:E=>{E.preventDefault(),v||_(null)},children:[u.jsxs("h2",{id:"project-stop-title",children:["停止 ",z.name,"?"]}),u.jsx("p",{children:"正在运行的任务和面板进程会中断。项目文件和配置保留,可稍后重新启动。"}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button primary",disabled:!!v,onClick:()=>_(null),children:"继续运行"}),u.jsx("button",{className:"library-button",disabled:!!v,onClick:()=>{P("stop",z)},children:"确认停止"})]})]}):null]})}function _E({setupToken:n}){const[i,r]=w.useState("checking"),[s,f]=w.useState(),[d,o]=w.useState(""),[m,g]=w.useState(""),[p,b]=w.useState(""),[y,v]=w.useState(n),[S,N]=w.useState(""),[D,z]=w.useState(!1),_=w.useRef(!1),M=w.useRef(0),H=w.useRef(i);H.current=i;const oe=w.useCallback(ie=>{_.current&&(f(ie?.session),r(ie===null?"legacy":ie.initialized?ie.authenticated?"authenticated":"login":"setup"),N(""),ie?.initialized&&v(""))},[]),ce=w.useCallback(async()=>{const ie=++M.current;try{const F=await Sv();ie===M.current&&oe(F)}catch(F){if(!_.current||ie!==M.current||H.current==="authenticated"||H.current==="legacy")return;r("error"),N(F instanceof Error?F.message:"无法连接服务端")}},[oe]);w.useEffect(()=>{_.current=!0,ce();const ie=()=>{ce()},F=()=>{document.visibilityState==="visible"&&ce()};return window.addEventListener("focus",ie),document.addEventListener("visibilitychange",F),()=>{_.current=!1,window.removeEventListener("focus",ie),document.removeEventListener("visibilitychange",F)}},[ce]);const R=w.useCallback(()=>{M.current++,f(void 0),r("login"),g(""),N("登录已过期或此设备已被撤销,请重新登录。")},[]),W=async ie=>{if(ie.preventDefault(),!D){M.current++,z(!0),N("");try{const F=await qg(`/api/v1/auth/${i==="setup"?"setup":"login"}`,{username:d.trim(),password:m,deviceName:p.trim()||void 0,...i==="setup"?{token:y.trim()}:{}});if(!F.authenticated)throw new Error("登录失败,请重试。");M.current++,g(""),v(""),oe({initialized:!0,authenticated:!0,session:F.session})}catch(F){N(F instanceof Error?F.message:"登录失败,请重试。"),F instanceof We&&F.status===409&&ce()}finally{z(!1)}}};return i==="authenticated"?u.jsx(RE,{onAuthLost:R,children:(ie,F)=>u.jsx(Og,{session:s,hub:!0,onAuthLost:R,onCheckAuth:ce,projectName:ie?.name,onBackToProjects:F})}):i==="legacy"?u.jsx(Og,{session:s,hub:!1,onAuthLost:R,onCheckAuth:ce}):u.jsx("main",{className:"auth-page",children:u.jsxs("section",{className:"auth-card",children:[u.jsxs("div",{className:"auth-brand",children:["CodeShell ",u.jsx("span",{children:"Hub"})]}),i==="checking"?u.jsx("p",{role:"status",children:"正在连接你的工作空间…"}):null,i==="error"?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"form-error",role:"alert",children:S}),u.jsx("button",{className:"send",onClick:()=>{ce()},children:"重试连接"})]}):null,i==="setup"||i==="login"?u.jsxs("form",{onSubmit:ie=>{W(ie)},children:[u.jsx("h1",{children:i==="setup"?"创建管理员账号":"登录工作空间"}),u.jsx("p",{children:i==="setup"?"首次启动需要服务端提供的初始化令牌。创建后,可在其他设备使用此账号登录。":"连接服务端,继续你的会话与任务。"}),i==="setup"?u.jsxs("label",{children:["初始化令牌",u.jsx("input",{type:"password",autoComplete:"off",required:!0,value:y,onChange:ie=>v(ie.target.value)})]}):null,u.jsxs("label",{children:["用户名",u.jsx("input",{autoComplete:"username",required:!0,maxLength:64,value:d,onChange:ie=>o(ie.target.value)})]}),u.jsxs("label",{children:["密码",u.jsx("input",{type:"password",autoComplete:i==="setup"?"new-password":"current-password",required:!0,maxLength:256,minLength:i==="setup"?12:void 0,value:m,onChange:ie=>g(ie.target.value)})]}),i==="setup"?u.jsx("small",{children:"密码至少 12 个字符。"}):null,u.jsxs("label",{children:["设备名称 ",u.jsx("span",{children:"(可选)"}),u.jsx("input",{autoComplete:"off",maxLength:100,placeholder:"例如:我的笔记本",value:p,onChange:ie=>b(ie.target.value)})]}),S?u.jsx("p",{className:"form-error",role:"alert",children:S}):null,u.jsx("button",{className:"send",type:"submit",disabled:D,children:D?"正在连接…":i==="setup"?"创建并进入":"登录"})]}):null]})})}function DE(n="/"){"serviceWorker"in navigator&&window.isSecureContext&&navigator.serviceWorker.register(`${n}sw.js`).catch(()=>{})}const OE=jv(window.location,window.history);yv.createRoot(document.getElementById("root")).render(u.jsx(w.StrictMode,{children:u.jsx(_E,{setupToken:OE})}));DE("/");