From 24a3ff1b9968e6c4b6d5ff14de08902a3a28ea1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= <188421097+HunYiSage@users.noreply.github.com> Date: Sun, 20 Sep 2026 16:02:53 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.11-beta.1?= =?UTF-8?q?=EF=BC=8CSkill=20=E5=AF=BC=E5=85=A5=E5=AE=98=E6=96=B9=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E5=B9=B6=E5=8A=A0=E6=AD=A3=E5=BC=8F/=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E9=80=9A=E9=81=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 设置页可导入压缩包或文件夹到官方 skills;导入约束路径与符号链接,保存保留官方 frontmatter。 Co-authored-by: Cursor --- README.md | 17 +- README.zh-CN.md | 17 +- client.js | 480 +++++++++++++++++++++++++++++++++++++++-- lib/core.js | 47 +++- lib/index.js | 207 +++++++++++++++++- lib/skills.js | 560 ++++++++++++++++++++++++++++++++++++++++++++++++ lib/update.js | 384 +++++++++++++++++++++++++++++---- package.json | 2 +- 8 files changed, 1628 insertions(+), 86 deletions(-) create mode 100644 lib/skills.js diff --git a/README.md b/README.md index ee045de..46e3488 100644 --- a/README.md +++ b/README.md @@ -586,6 +586,7 @@ The **Rules** card appears on the dsh web settings page. Switch **Light / Ink**. | Patches | grouped status, Apply, Restore, or Uninstall | | Prompt | edit `prompt-inject.md` as the session override | | Rule sets | multiple `AGENTS.md` / `CLAUDE.md`; Enable writes under `$DSH_HOME`, Delete removes the row | +| Skills | import a zip or folder into this host’s official `$DSH_HOME/skills//SKILL.md` (web and desktop each use their own home; no drive letter is hardcoded); DSH owns match, load, and `/name`. You can also delete that folder yourself | --- @@ -610,6 +611,7 @@ dsh-purge/ │ ├── restart-web.js │ ├── rewind.js │ ├── rules.js +│ ├── skills.js │ ├── uninstall-restart.js │ ├── uninstall.js │ └── update.js @@ -620,7 +622,7 @@ dsh-purge/ └── README.zh-CN.md ``` -Runtime user files: `$DSH_HOME/prompt-inject.md`, `$DSH_HOME/rules/`. If `DSH_HOME` is unset, the launcher-adjacent `.dsh` wins over `~/.dsh`. +Runtime user files: `$DSH_HOME/prompt-inject.md`, `$DSH_HOME/rules/`, `$DSH_HOME/skills/`. If `DSH_HOME` is unset, the launcher-adjacent `.dsh` wins over `~/.dsh`. Skills are not part of the `dsh-purge` inject section and do not replace the prompt. --- @@ -646,12 +648,13 @@ dsh-purge --edit /purge status | apply | revert | uninstall | edit | help /rules list | use | create | delete | reset | help +/skills list | import | create [description] | delete | help /rewind purge_status purge_apply purge_revert ``` -Patched packages load only after a restart. Apply does not restart by itself. +Patched packages load only after a restart. Apply does not restart by itself. Under the patch title you can switch **Stable / Beta** or roll back from the version list. A rollback is pinned; click **Update** to return to the channel tip. The composer **Undo** button drops the last turn and puts the last user sentence back in the input. On the main agent you can rewind once or the whole last round (including subagents). After rewind, send only what is in the box now. `/rewind` does the same. @@ -667,6 +670,7 @@ node --check lib/web.js node --check lib/desktop.js node --check lib/host.js node --check lib/rewind.js +node --check lib/skills.js node --check client.js ``` @@ -695,6 +699,8 @@ prompt-inject.md has content? ──yes──> write it verbatim as the dsh-purg └─> no override section ``` +**Skills (official catalog, not injected):** Settings import (zip or folder) or `/skills import` writes only to official `$DSH_HOME/skills//SKILL.md` (companion files in that folder are kept). Official `dsh-skill-filesystem` watches that directory; the model loads via the `skill` tool or `/id`. Uninstalling the plugin does not delete user skills. + **Identity (1.3.6):** the plugin does not invent an “operator / LCS” second persona. Official Harness identity lines are stripped; `prompt-inject.md` is the identity. On 0.1.5 the inject is folded into `persona-prefix` so liangshen phase-1 cannot drop it. **Windows CMD silence:** on Node 24, `import { spawn } from "node:child_process"` is not a live binding. `registerHooks` redirects `node:child_process` to a `windowsHide` facade; `@deepseek-ai/dsh-subprocess-local` also gets `windowsHide: true`. Doctor relaunch uses `node + bin.js` and does not leave a noop `supervisor.cmd`. @@ -745,10 +751,17 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change ## Changelog +### 1.1.11-beta.1 + +- Settings can import a zip or folder into official `$DSH_HOME/skills`; Stable / Beta can be switched and rolled back +- Import ignores symlinks and checks archive paths; save keeps official frontmatter fields + ### 1.1.10 - Saving or applying with both the prompt and the rule set empty is blocked and shows a dialog - First-turn inject is complete; later turns no longer pin the previous full system prompt +- Settings / `/skills` can import a zip or folder into official `$DSH_HOME/skills`; DSH still owns match and load +- Settings can switch Stable / Beta and roll back to a published version; a rollback is pinned and will not auto-follow ### 1.1.9 diff --git a/README.zh-CN.md b/README.zh-CN.md index 07fd11a..3770329 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -583,6 +583,7 @@ dsh-purge --uninstall | 补丁 | 分组查看状态,应用、还原或卸载 | | 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 | | 规则集 | 多套 `AGENTS.md` / `CLAUDE.md`;启用写入 `$DSH_HOME`,删除从列表去掉 | +| Skill | 导入压缩包或文件夹到当前宿主官方目录 `$DSH_HOME/skills//SKILL.md`(Web / 桌面各用自己的主目录,不写死盘符);命中、加载、`/名称` 由 DSH 负责。也可自己删该文件夹 | --- @@ -607,6 +608,7 @@ dsh-purge/ │ ├── restart-web.js │ ├── rewind.js │ ├── rules.js +│ ├── skills.js │ ├── uninstall-restart.js │ ├── uninstall.js │ └── update.js @@ -617,7 +619,7 @@ dsh-purge/ └── README.zh-CN.md ``` -运行时用户文件:`$DSH_HOME/prompt-inject.md`、`$DSH_HOME/rules/`。未设 `DSH_HOME` 时,优先用 dsh 安装目录旁边的 `.dsh`,再退回 `~/.dsh`。 +运行时用户文件:`$DSH_HOME/prompt-inject.md`、`$DSH_HOME/rules/`、`$DSH_HOME/skills/`。未设 `DSH_HOME` 时,优先用 dsh 安装目录旁边的 `.dsh`,再退回 `~/.dsh`。Skill 不进 `dsh-purge` 注入段,也不顶替提示词。 --- @@ -645,13 +647,14 @@ dsh-purge --edit # 聊天 /purge status | apply | revert | uninstall | edit | help /rules list | use | create | delete | reset | help +/skills list | import <压缩包或文件夹> | create [说明] | delete | help /rewind # 模型工具 purge_status purge_apply purge_revert ``` -设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。 +设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。补丁标题下可切换「正式版 / 测试版」,或从版本列表回退;回退后会固定在该版本,要回到通道最新再点「更新」。 输入框旁的「回退」会丢掉最近一轮对话,并把上一句填回输入框;聊天里 `/rewind` 同样可用。 @@ -663,6 +666,7 @@ purge_status purge_apply purge_revert node --check lib/index.js node --check lib/core.js node --check lib/rewind.js +node --check lib/skills.js node --check client.js ``` @@ -691,6 +695,8 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt └─> 不写入覆盖段 ``` +**Skill(官方目录,不注入):** 设置页导入压缩包/文件夹,或 `/skills import`,只把内容写到官方 `$DSH_HOME/skills//SKILL.md`(可带同目录脚本等资源)。官方 `dsh-skill-filesystem` 监视该目录;模型用 `skill` 工具或 `/id` 加载。卸载插件不删用户 Skill。 + **身份(1.3.6):** 插件不发明「操作员 / LCS」第二套人设。官方 Harness 身份句剥掉;`prompt-inject.md` 原文就是身份。0.1.5 把 inject 折进 `persona-prefix`,避免被梁神 phase-1 滤掉。 **Windows CMD 无感:** Node 24 上 `import { spawn } from "node:child_process"` 不是实时绑定。`registerHooks` 把 `node:child_process` 指到带 `windowsHide` 的封装层,并直接给 `@deepseek-ai/dsh-subprocess-local` 加 `windowsHide: true`。doctor 重启走 `node + bin.js`,不写空操作 `supervisor.cmd`。 @@ -732,10 +738,17 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt ## 更新记录 +### 1.1.11-beta.1 + +- 设置页可导入压缩包或文件夹到官方 `$DSH_HOME/skills`;正式版 / 测试版可切换并回退 +- 导入不再跟符号链接,压缩包先检查路径;保存时保留官方 frontmatter 字段 + ### 1.1.10 - 提示词和规则集都空时不能保存或应用,弹窗要求先添加提示词 - 第一轮完整注入;不再钉上一轮整篇系统提示,避免来回追加 +- 设置页 / `/skills` 可把压缩包或文件夹导入官方 `$DSH_HOME/skills`;命中与加载仍由 DSH 负责 +- 设置页可切换正式版 / 测试版,并从历史版本回退;回退后会固定,不再自动跟上 ### 1.1.9 diff --git a/client.js b/client.js index 2cde99d..5332b7d 100644 --- a/client.js +++ b/client.js @@ -45,6 +45,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const method = String((init && init.method) || "GET").toUpperCase(); if (path.indexOf("/dsh-purge/update") !== -1) return method === "POST" ? 180000 : 45000; if (path.indexOf("/dsh-purge/uninstall") !== -1) return 90000; + if (path.indexOf("/dsh-purge/skill") !== -1) return method === "POST" ? 120000 : 20000; return 20000; } function isAbortError(e) { @@ -110,6 +111,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { }); } + function skillsRouteMissing(e) { + return /\b404\b|\b405\b|non-json/i.test(String((e && e.message) || e || "")); + } + + function skillsApi(op, extra) { + const init = { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(Object.assign({ op: op }, extra || {})), + }; + return apiJson("/dsh-purge/skills", init).catch((e) => { + if (!skillsRouteMissing(e)) throw e; + return apiJson("/dsh-purge/skill", init); + }); + } + const TARGETS = ["AGENTS.md", "CLAUDE.md"]; const PATCH_GROUPS = [ { key: "prompt", ids: [1, 2, 3, 4, 5, 26, 27, 28, 29, 33] }, @@ -139,7 +156,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "apply.hint": "待应用=原文还在。跳过=没装或官方已改写,再点也不会变。", "warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。", "warn.noRoot.desktop": "未定位到当前桌面应用里的 @deepseek-ai。请退出托盘后重新打开 DSH Desktop.exe,再在桌面端设置页点「应用」。安装目录不限盘符。", - "warn.noInject": "提示词优先;为空则注入当前启用的规则集。两边都空会提示必须添加。", + "warn.noInject": "提示词优先;为空则注入当前启用的规则集。两边都空会提示必须添加。Skill 不顶替提示词。", "need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。", "btn.restoreInject": "恢复默认", "saved.restoreInject": "已填入默认提示词,点保存写入", @@ -163,16 +180,26 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "btn.checkUpdate.busy": "检测中…", "btn.doUpdate": "更新", "btn.doUpdate.busy": "更新中…", + "channel.title": "通道", + "channel.stable": "正式版", + "channel.beta": "测试版", "update.checking": "正在检测更新…", "update.applying": "正在更新…", + "update.switching": "正在切换版本…", "update.latest": "已是最新({version})", "update.available": "有新版本 {remote},当前 {local}", + "update.pinned": "已固定在 {version},通道最新是 {remote}", "update.done": "已更新到 {version},请重启", + "update.switched": "已切换到 {version},请重启", "update.autoDone": "已自动更新到 {version},请重启", "update.dirty": "有新版本,本地有改动未自动覆盖", "update.fail": "更新失败: {error}", "update.timeout": "检测超时,请再点一次检测更新", "update.needRestart": "检测接口未加载,请先重启 dsh 再点检测更新", + "update.noBeta": "还没有测试版", + "update.switch": "切换到此版本", + "update.current": "当前", + "update.confirmSwitch": "切换到 {version}?之后可再选回正式版或其它版本。本地未提交的插件改动不会保留。", "metric.version": "版本", "action.apply": "应用", "action.revert": "还原", @@ -203,6 +230,24 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "need.id": "需要 id", "ph.content": "", "btn.saveRule": "保存", + "skills.title": "Skill", + "skills.hint": "官方 Skill 目录。可导入压缩包或文件夹。命中和加载由 DSH 负责。", + "skills.hint.desktop": "当前桌面宿主的官方 Skill 目录。可导入压缩包或文件夹。命中和加载由 DSH 负责。", + "skills.empty": "暂无用户 Skill", + "btn.importZip": "导入压缩包", + "btn.importFolder": "导入文件夹", + "skills.importing": "正在导入…", + "saved.import": "已导入 {count} 个 Skill", + "need.import": "请选择压缩包或文件夹", + "err.import.folder": "没读到文件夹里的文件,请直接选 Skill 目录(里面要有 SKILL.md)", + "skills.pick": "选择 Skill", + "skills.invalid": "官方会忽略:格式不对", + "ph.skill.desc": "description(何时用)", + "btn.saveSkill": "保存", + "need.skill.id": "id 必须是 kebab-case,例如 code-review", + "confirm.delete.skill": "从官方 $DSH_HOME/skills 删除 {id}?宿主会自动从目录拿掉。", + "err.skills": "读取失败: {error}", + "err.skills.needRestart": "Skill 接口未加载,请先重启当前宿主", "btn.restart": "重启", "btn.restart.busy": "重启中…", "restarting": "重启中…", @@ -310,7 +355,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "apply.hint": "Pending = original text still present. Skipped = missing or already rewritten.", "warn.noRoot": "Could not find this host’s @deepseek-ai tree, so Apply will not patch anything. Fully quit and reopen this host, then Apply here. Desktop may live on any drive; do not use official dsh to purge Desktop.", "warn.noRoot.desktop": "Could not find @deepseek-ai inside this desktop app. Quit the tray, reopen DSH Desktop.exe, then Apply on the desktop Settings page. The install folder can be on any drive.", - "warn.noInject": "The prompt box wins. If it is empty, the enabled rule set is injected. If both are empty you will be asked to add a prompt.", + "warn.noInject": "The prompt box wins. If it is empty, the enabled rule set is injected. If both are empty you will be asked to add a prompt. Skills do not replace the prompt.", "need.prompt": "Both the prompt and the rule set are empty. Add a prompt, or enable a rule that has content.", "btn.restoreInject": "Reset default", "saved.restoreInject": "Default prompt loaded. Save to write.", @@ -334,16 +379,26 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "btn.checkUpdate.busy": "Checking…", "btn.doUpdate": "Update", "btn.doUpdate.busy": "Updating…", + "channel.title": "Channel", + "channel.stable": "Stable", + "channel.beta": "Beta", "update.checking": "Checking for updates…", "update.applying": "Updating…", + "update.switching": "Switching version…", "update.latest": "Up to date ({version})", "update.available": "Update {remote} available (now {local})", + "update.pinned": "Pinned at {version}; channel latest is {remote}", "update.done": "Updated to {version}. Restart to apply.", + "update.switched": "Switched to {version}. Restart to apply.", "update.autoDone": "Auto-updated to {version}. Restart to apply.", "update.dirty": "Update available; local edits were not overwritten.", "update.fail": "Update failed: {error}", "update.timeout": "Check timed out. Click Check update again.", "update.needRestart": "Update API is not loaded. Restart dsh, then check again.", + "update.noBeta": "No beta build yet", + "update.switch": "Switch to this version", + "update.current": "current", + "update.confirmSwitch": "Switch to {version}? You can switch back later. Uncommitted plugin edits will not be kept.", "metric.version": "Version", "action.apply": "Apply", "action.revert": "Restore", @@ -374,6 +429,24 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "need.id": "id required", "ph.content": "", "btn.saveRule": "Save", + "skills.title": "Skills", + "skills.hint": "Official skill catalog. Import a zip or folder. DSH owns match and load.", + "skills.hint.desktop": "This desktop host’s official skill catalog. Import a zip or folder. DSH owns match and load.", + "skills.empty": "No user skills", + "btn.importZip": "Import zip", + "btn.importFolder": "Import folder", + "skills.importing": "Importing…", + "saved.import": "Imported {count} skill(s)", + "need.import": "Choose a zip or folder", + "err.import.folder": "No files were read. Select the skill folder itself (it must contain SKILL.md).", + "skills.pick": "Select a skill", + "skills.invalid": "Official catalog will ignore this: invalid format", + "ph.skill.desc": "description (when to use)", + "btn.saveSkill": "Save", + "need.skill.id": "id must be kebab-case, e.g. code-review", + "confirm.delete.skill": "Delete {id} from official $DSH_HOME/skills? The host will drop it from the catalog.", + "err.skills": "Read failed: {error}", + "err.skills.needRestart": "Skill API is not loaded. Restart this host first.", "btn.restart": "Restart", "btn.restart.busy": "Restarting…", "restarting": "Restarting…", @@ -521,6 +594,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .dshp-cr-row label{display:inline-flex;align-items:center;gap:6px;color:var(--dshp-ink)} .dshp-cr-num{width:64px;min-width:64px;height:28px;padding:0 8px} .dshp-cr-text{width:120px;min-width:88px;height:28px;padding:0 8px} +.dshp-ver{min-width:168px;max-width:260px;height:28px;padding:0 8px;font-size:12px} .dshp-area{min-height:220px;resize:vertical} .dshp-field:focus,.dshp-area:focus{outline:none;border-color:var(--dshp-accent);box-shadow:0 0 0 3px var(--dshp-accent-soft)} .dshp-field:disabled,.dshp-area:disabled{opacity:.5} @@ -609,7 +683,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { function PatchGroups({ state }) { const t = useT(); - const [open, setOpen] = useState({ prompt: true, code: true, engine: true, tools: false, compat: true }); + const [open, setOpen] = useState({}); if (!state || !state.patch_status) return h("div", { className: "dshp-skel", style: { height: 120 } }); return PATCH_GROUPS.map((group) => { const rows = group.ids.map((id) => { @@ -763,6 +837,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const [updateNotice, setUpdateNotice] = useState({ kind: "idle", text: "" }); const [updateInfo, setUpdateInfo] = useState(null); const [canApplyUpdate, setCanApplyUpdate] = useState(false); + const [channel, setChannel] = useState("stable"); + const [selectedRef, setSelectedRef] = useState(""); const actionTicket = useRef(0); const updateErrorText = (tr, e) => { @@ -772,41 +848,78 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { return tr("update.fail", { error: msg }); }; + const applyUpdateInfo = useCallback((d, tr, kind) => { + if (d.channel) setChannel(d.channel); + setUpdateInfo(d); + setCanApplyUpdate(Boolean(d.hasUpdate) && !d.error); + const versions = d.versions || []; + const current = versions.find((item) => item.current); + if (current && current.ref) setSelectedRef(current.ref); + else if (d.pin) setSelectedRef(d.pin); + const version = d.localVersion || d.localSha || "—"; + const remote = d.remoteVersion || d.remoteSha || "—"; + let text = tr("update.latest", { version }); + if (d.hasUpdate) text = tr("update.available", { remote, local: version }); + if (d.pinned && d.hasUpdate) text = tr("update.pinned", { version, remote }); + if (kind === "switched") text = tr("update.switched", { version: d.localVersion || d.remoteVersion || selectedRef || "—" }); + if (kind === "done") text = tr("update.done", { version: d.localVersion || d.remoteVersion || "—" }); + if (d.error) text = d.error; + setUpdateNotice({ kind: d.ok === false || d.error ? "error" : "ok", text }); + }, [selectedRef]); + const checkUpdate = useCallback(() => { setUpdateBusy(true); const tr = tRef.current; setUpdateNotice({ kind: "ok", text: tr("update.checking") }); apiJson("/dsh-purge/update") .then((d) => { - if (!d || !d.ok) throw new Error((d && d.error) || "check failed"); - setUpdateInfo(d); - setCanApplyUpdate(Boolean(d.hasUpdate)); - setUpdateNotice({ - kind: "ok", - text: d.hasUpdate - ? tr("update.available", { remote: d.remoteVersion || d.remoteSha, local: d.localVersion || d.localSha }) - : tr("update.latest", { version: d.localVersion || d.localSha || "—" }), - }); + if (!d || (!d.ok && !d.channel)) throw new Error((d && d.error) || "check failed"); + applyUpdateInfo(d, tr); }) .catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) })) .finally(() => setUpdateBusy(false)); - }, []); + }, [applyUpdateInfo]); - const doUpdate = useCallback(() => { + const postUpdate = useCallback((body, kind) => { setUpdateBusy(true); const tr = tRef.current; - setUpdateNotice({ kind: "ok", text: tr("update.applying") }); - apiJson("/dsh-purge/update", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }) + setUpdateNotice({ kind: "ok", text: kind === "switched" || kind === "channel" ? tr("update.switching") : tr("update.applying") }); + return apiJson("/dsh-purge/update", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body || {}), + }) .then((d) => { - if (!d || !d.ok) throw new Error((d && d.error) || "update failed"); - setUpdateInfo(d); - setCanApplyUpdate(false); - setUpdateNotice({ kind: "ok", text: tr("update.done", { version: d.localVersion || d.remoteVersion || "—" }) }); + if (!d || (d.ok === false && d.error)) throw new Error((d && d.error) || "update failed"); + applyUpdateInfo(d, tr, kind === "channel" ? "done" : kind); if (d.applied || d.needRestart) setAskRestart(true); + return d; + }) + .catch((e) => { + setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) }); + throw e; }) - .catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) })) .finally(() => setUpdateBusy(false)); - }, []); + }, [applyUpdateInfo]); + + const doUpdate = useCallback(() => { + postUpdate({ op: "apply" }, "done").catch(() => {}); + }, [postUpdate]); + + const changeChannel = useCallback((next) => { + if (!next || next === channel) return; + postUpdate({ op: "channel", channel: next }, "channel").catch(() => {}); + }, [channel, postUpdate]); + + const switchSelected = useCallback(() => { + const tr = tRef.current; + const versions = (updateInfo && updateInfo.versions) || []; + const hit = versions.find((item) => item.ref === selectedRef); + const label = (hit && (hit.label || hit.version)) || selectedRef; + if (!selectedRef) return; + if (!window.confirm(tr("update.confirmSwitch", { version: label }))) return; + postUpdate({ op: "switch", ref: selectedRef }, "switched").catch(() => {}); + }, [postUpdate, selectedRef, updateInfo]); const loadAll = useCallback(() => { const tr = tRef.current; @@ -814,7 +927,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .then((d) => { if (d && d.ok) { setState(d); - if (d.update && d.update.ok && !d.update.error && !d.update.hasUpdate) setUpdateInfo(d.update); + if (d.channel) setChannel(d.channel); + if (d.update && d.update.ok && !d.update.error) setUpdateInfo(d.update); } else { setState({ ok: false, patches_total: 0, patches_applied: 0, patch_status: {}, shim_cmd: "n/a", shim_ps1: "n/a", shim_bin: "n/a", has_backup: false }); setNotice({ kind: "error", text: tr("err.status", { error: (d && d.error) || "bad response" }) }); @@ -824,6 +938,17 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { setState({ ok: false, patches_total: 0, patches_applied: 0, patch_status: {}, shim_cmd: "n/a", shim_ps1: "n/a", shim_bin: "n/a", has_backup: false }); setNotice({ kind: "error", text: tr("err.status", { error: e.message }) }); }); + apiJson("/dsh-purge/update") + .then((d) => { + if (!d) return; + if (d.channel) setChannel(d.channel); + setUpdateInfo(d); + setCanApplyUpdate(Boolean(d.hasUpdate) && !d.error); + const current = (d.versions || []).find((item) => item.current); + if (current && current.ref) setSelectedRef(current.ref); + else if (d.pin) setSelectedRef(d.pin); + }) + .catch(() => {}); apiJson("/dsh-purge/override") .then((d) => { if (d && d.ok) { @@ -1050,11 +1175,16 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const updateBtnLabel = updateBusy ? (canApplyUpdate ? t("btn.doUpdate.busy") : t("btn.checkUpdate.busy")) : (canApplyUpdate ? t("btn.doUpdate") : t("btn.checkUpdate")); + const versions = (updateInfo && updateInfo.versions) || []; + const selected = versions.find((item) => item.ref === selectedRef); + const canSwitchVersion = Boolean(selectedRef && selected && !selected.current); + const channelNow = (updateInfo && updateInfo.channel) || channel || "stable"; return h("section", { className: "dshp-panel", "aria-label": t("purge.title") }, h("div", { className: "dshp-head" }, h("h3", { className: "dshp-title" }, t("purge.title")), h("div", { className: "dshp-row", style: { margin: 0, flex: 1, justifyContent: "flex-end" } }, h("span", { className: "dshp-pill" }, t("surface." + hostSurface)), + h("span", { className: "dshp-pill" + (channelNow === "beta" ? " is-wait" : "") }, t("channel." + (channelNow === "beta" ? "beta" : "stable"))), versionText ? h("span", { className: "dshp-pill" + (canApplyUpdate ? " is-wait" : "") }, versionText) : null, h(Btn, { tiny: true, @@ -1065,6 +1195,38 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { noticeNode(updateNotice), ), ), + h("div", { className: "dshp-row", style: { margin: "-4px 0 12px" } }, + h("div", { className: "dshp-switch", role: "group", "aria-label": t("channel.title") }, + h("button", { + type: "button", + className: channelNow === "stable" ? "is-on" : "", + disabled: updateBusy, + onClick: () => changeChannel("stable"), + }, t("channel.stable")), + h("button", { + type: "button", + className: channelNow === "beta" ? "is-on" : "", + disabled: updateBusy, + onClick: () => changeChannel("beta"), + }, t("channel.beta")), + ), + h("select", { + className: "dshp-field dshp-ver", + value: selectedRef, + disabled: updateBusy || versions.length === 0, + onChange: (e) => setSelectedRef(e.target.value), + "aria-label": t("update.switch"), + }, + versions.length + ? versions.map((item) => h("option", { key: item.ref + (item.sha || ""), value: item.ref }, item.label + (item.current ? " · " + t("update.current") : ""))) + : h("option", { value: "" }, t("btn.checkUpdate")), + ), + h(Btn, { + tiny: true, + disabled: updateBusy || !canSwitchVersion, + onClick: switchSelected, + }, t("update.switch")), + ), s ? h("div", { className: "dshp-metrics" }, h("div", { className: "dshp-metric" }, h("b", null, settled + " / " + total), @@ -1359,6 +1521,277 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { ); } + function SkillsSection() { + const t = useT(); + const tRef = useRef(t); + tRef.current = t; + const [st, setSt] = useState(null); + const [editId, setEditId] = useState(null); + const [editDesc, setEditDesc] = useState(""); + const [content, setContent] = useState(""); + const [busy, setBusy] = useState(false); + const [notice, setNotice] = useState({ kind: "idle", text: "" }); + const zipRef = useRef(null); + const folderRef = useRef(null); + + const loadStatus = useCallback(() => { + const tr = tRef.current; + const fail = (e) => { + setSt({ ok: false, skills: [] }); + setNotice({ + kind: "error", + text: skillsRouteMissing(e) ? tr("err.skills.needRestart") : tr("err.skills", { error: (e && e.message) || e || "bad response" }), + }); + }; + const apply = (d) => { + if (d && d.ok) setSt({ ok: true, skills: d.skills || [] }); + else fail({ message: (d && d.error) || "bad response" }); + }; + skillsApi("status") + .then(apply) + .catch(() => apiJson("/dsh-purge/status") + .then((d) => { + if (d && d.ok) apply({ ok: true, skills: d.skills || [] }); + else fail({ message: (d && d.error) || "404 Not Found" }); + }) + .catch(fail)); + }, []); + + useEffect(() => { loadStatus(); }, [loadStatus]); + + const doPost = useCallback((action, payload, after) => { + setBusy(true); + setNotice({ kind: "idle", text: "" }); + skillsApi(action, payload) + .then((d) => { + if (d && d.ok) { + setNotice({ kind: "ok", text: t("ok.done") }); + loadStatus(); + if (after) after(d); + } else { + setNotice({ kind: "error", text: t("err.action", { error: (d && d.error) || "" }) }); + } + }) + .catch((e) => setNotice({ + kind: "error", + text: skillsRouteMissing(e) ? t("err.skills.needRestart") : t("err.action", { error: e.message }), + })) + .finally(() => setBusy(false)); + }, [loadStatus, t]); + + const openSkill = useCallback((id) => { + setBusy(true); + skillsApi("read", { id: id }) + .then((d) => { + if (d.ok) { + setEditId(id); + setEditDesc(d.description || ""); + setContent(typeof d.content === "string" ? d.content : ""); + } else setNotice({ kind: "error", text: t("err.read", { error: d.error || "" }) }); + }) + .catch((e) => setNotice({ kind: "error", text: t("err.read", { error: e.message }) })) + .finally(() => setBusy(false)); + }, [t]); + + const clearEditor = () => { + setEditId(null); + setEditDesc(""); + setContent(""); + }; + + const readAsBase64 = (file) => new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + const text = String(reader.result || ""); + const at = text.indexOf(","); + resolve(at >= 0 ? text.slice(at + 1) : text); + }; + reader.onerror = () => reject(new Error(t("need.import"))); + reader.readAsDataURL(file); + }); + + const importZip = (file) => { + if (!file) { + setNotice({ kind: "error", text: t("need.import") }); + return; + } + setBusy(true); + setNotice({ kind: "ok", text: t("skills.importing") }); + readAsBase64(file) + .then((data) => skillsApi("import", { data, name: file.name })) + .then((d) => { + if (!d || !d.ok) throw new Error((d && d.error) || ""); + setNotice({ kind: "ok", text: t("saved.import", { count: (d.imported || []).length || 1 }) }); + loadStatus(); + }) + .catch((e) => setNotice({ + kind: "error", + text: skillsRouteMissing(e) ? t("err.skills.needRestart") : t("err.action", { error: e.message }), + })) + .finally(() => setBusy(false)); + }; + + const keepFolderFile = (file) => { + const rel = String(file.webkitRelativePath || file.name || "").replace(/\\/g, "/"); + if (!rel || rel.includes("..")) return false; + if (/(^|\/)(node_modules|\.git|__MACOSX|\.system)(\/|$)/i.test(rel)) return false; + if (/(^|\/)\._/.test(rel) || /\/\.DS_Store$/i.test(rel)) return false; + return true; + }; + + const importFolder = (list) => { + const files = Array.from(list || []).filter(keepFolderFile); + if (!files.length) { + setNotice({ kind: "error", text: t("err.import.folder") }); + return; + } + setBusy(true); + setNotice({ kind: "ok", text: t("skills.importing") }); + Promise.all(files.map((file) => readAsBase64(file).then((content) => ({ + path: file.webkitRelativePath || file.name, + content, + encoding: "base64", + })))) + .then((payload) => skillsApi("import", { + files: payload, + name: String(payload[0] && payload[0].path || "").split("/")[0], + })) + .then((d) => { + if (!d || !d.ok) throw new Error((d && d.error) || ""); + setNotice({ kind: "ok", text: t("saved.import", { count: (d.imported || []).length || 1 }) }); + loadStatus(); + }) + .catch((e) => setNotice({ + kind: "error", + text: skillsRouteMissing(e) ? t("err.skills.needRestart") : t("err.action", { error: e.message }), + })) + .finally(() => setBusy(false)); + }; + + let list; + if (!st) { + list = h("div", { className: "dshp-skel", style: { height: 80, margin: 12 } }); + } else if (!st.skills || st.skills.length === 0) { + list = h("p", { className: "dshp-empty" }, t("skills.empty")); + } else { + list = st.skills.map((item) => { + const isEdit = item.id === editId; + return h("div", { + key: item.id, + className: "dshp-ruleitem" + (isEdit ? " is-edit" : ""), + role: "button", + tabIndex: 0, + onClick: () => openSkill(item.id), + onKeyDown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openSkill(item.id); } }, + }, + h("div", { className: "dshp-rule-main" }, + h("span", { className: "dshp-rule-name" }, item.id), + h("span", { className: "dshp-rule-meta" }, + (item.valid ? item.description : t("skills.invalid")) + " · " + formatSize(item.size), + ), + ), + h("div", { className: "dshp-rule-ops" }, + h(Btn, { + tiny: true, + kind: "danger", + disabled: busy, + onClick: (e) => { + e.stopPropagation(); + if (!window.confirm(t("confirm.delete.skill", { id: item.id }))) return; + if (editId === item.id) clearEditor(); + doPost("delete", { id: item.id }); + }, + }, t("delete")), + ), + ); + }); + } + + return h("section", { className: "dshp-panel", "aria-label": t("skills.title") }, + h("div", { className: "dshp-head" }, + h("h3", { className: "dshp-title" }, t("skills.title")), + h("div", { className: "dshp-row", style: { margin: 0 } }, noticeNode(notice)), + ), + h("p", { className: "dshp-hint", style: { margin: "0 0 10px", color: "var(--dshp-mute)", fontSize: 12 } }, hostText(t, "skills.hint", hostSurfaceOf())), + h("div", { className: "dshp-split" }, + h("div", { className: "dshp-rulelist" }, + h("div", { className: "dshp-rulebody" }, list), + h("div", { className: "dshp-create" }, + h("div", { className: "dshp-create-row" }, + h("input", { + ref: zipRef, + type: "file", + accept: ".zip,.tgz,.tar.gz,.tar,.skill", + style: { display: "none" }, + onChange: (e) => { + const file = e.target.files && e.target.files[0]; + e.target.value = ""; + importZip(file); + }, + }), + h("input", { + ref: (el) => { + folderRef.current = el; + if (!el) return; + el.setAttribute("webkitdirectory", ""); + el.setAttribute("directory", ""); + el.multiple = true; + }, + type: "file", + multiple: true, + style: { display: "none" }, + onChange: (e) => { + const files = Array.from((e.target && e.target.files) || []); + e.target.value = ""; + importFolder(files); + }, + }), + h(Btn, { + kind: "primary", + tiny: true, + disabled: busy, + onClick: () => zipRef.current && zipRef.current.click(), + }, t("btn.importZip")), + h(Btn, { + tiny: true, + disabled: busy, + onClick: () => folderRef.current && folderRef.current.click(), + }, t("btn.importFolder")), + ), + ), + ), + h("div", { className: "dshp-editor" }, + editId ? [ + h("div", { key: "meta", className: "dshp-row" }, + h("input", { + className: "dshp-field", + placeholder: t("ph.skill.desc"), + value: editDesc, + onChange: (e) => setEditDesc(e.target.value), + }), + ), + h("textarea", { + key: "body", + className: "dshp-area", + value: content, + onChange: (e) => setContent(e.target.value), + spellCheck: false, + placeholder: "", + }), + h("div", { key: "save", className: "dshp-row" }, + h(Btn, { + kind: "primary", + disabled: busy, + onClick: () => doPost("save", { id: editId, content, description: editDesc }), + }, t("btn.saveSkill")), + noticeNode(notice), + ), + ] : h("div", { className: "dshp-editor-empty" }, t("skills.pick")), + ), + ), + ); + } + function reopenAfterRestart() { const url = new URL(window.location.href); url.searchParams.delete("token"); @@ -1500,6 +1933,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { ), h(PurgifySection, null), h(RulesSection, null), + h(SkillsSection, null), ); } diff --git a/lib/core.js b/lib/core.js index 1bbf350..7a51fc6 100644 --- a/lib/core.js +++ b/lib/core.js @@ -1318,7 +1318,37 @@ export function normPath(p) { export function isDshHomeDir(dir) { if (!dir || !isDir(dir)) return false; - return path.basename(path.normalize(dir)) === ".dsh"; + const base = path.basename(path.normalize(dir)).toLowerCase(); + return base === ".dsh" || base === "dsh-home"; +} + +function desktopHomeCandidates() { + const out = []; + const push = (dir) => { + if (!dir) return; + const root = path.normalize(dir); + out.push(root); + out.push(path.join(root, ".dsh")); + out.push(path.join(root, "dsh-home")); + }; + try { + const exe = desktop.findDesktopAppExecutable(); + if (exe) push(path.dirname(exe)); + } catch { /* ignore */ } + try { + if (process.resourcesPath) push(path.dirname(path.normalize(process.resourcesPath))); + } catch { /* ignore */ } + try { + for (const root of desktop.listDesktopInstallRoots()) push(root); + } catch { /* ignore */ } + for (const guess of desktopDshHomeGuesses()) out.push(guess); + const seen = new Set(); + return out.filter((item) => { + const key = path.normalize(item).replace(/\\/g, "/").toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); } export function portableHomeFromLauncher(shimDir, prefix) { @@ -1350,15 +1380,24 @@ function desktopDshHomeGuesses() { ]; } -// DSH_HOME → 启动器旁 .dsh → ~/.dsh +// DSH_HOME → 桌面进程旁 .dsh/dsh-home → 启动器旁 .dsh → ~/.dsh +// 不写死盘符;桌面端不借用 Web 启动器旁的主目录。 export function findDshHome(options = {}) { const env = options.env ?? process.env; const fromEnv = env.DSH_HOME; if (fromEnv && String(fromEnv).trim()) return path.normalize(fromEnv.trim()); + const desktopHost = adapterFor(detectSurface(options)) === "desktop"; + if (desktopHost) { + for (const cand of desktopHomeCandidates()) { + if (isDshHomeDir(cand)) return path.normalize(cand); + } + } const shimDir = options.shimDir !== undefined ? options.shimDir : findShimDir(); const prefix = options.prefix !== undefined ? options.prefix : findNpmPrefix(); - const portable = portableHomeFromLauncher(shimDir, prefix); - if (portable) return portable; + if (!desktopHost) { + const portable = portableHomeFromLauncher(shimDir, prefix); + if (portable) return portable; + } const unix = path.join(os.homedir(), ".dsh"); if (isDir(unix)) return unix; const wslWin = findWslWindowsDshHome(env); diff --git a/lib/index.js b/lib/index.js index 3d38719..ce1528b 100644 --- a/lib/index.js +++ b/lib/index.js @@ -3,6 +3,7 @@ import { promises as fsp } from "node:fs"; import * as core from "./core.js"; import * as hostctl from "./host.js"; import * as rules from "./rules.js"; +import * as skills from "./skills.js"; import * as updater from "./update.js"; import { GLOBAL_PROMPT_ORDER, @@ -397,7 +398,8 @@ async function handlePurgeCommand(rawInput, config) { " /purge uninstall 卸载插件(已应用则先还原)\n" + " /purge edit 编辑注入文件 prompt-inject.md\n" + " /purge help 显示帮助\n" + - "规则集切换见 /rules(list | use | create | delete | reset)", + "规则集切换见 /rules(list | use | create | delete | reset)\n" + + "官方 Skill 安装见 /skills(list | import <路径> | create [说明] | delete )", }; } } @@ -511,6 +513,97 @@ async function handleRulesCommand(rawInput) { } } +function renderSkillsStatus(st) { + const out = []; + out.push("官方用户 Skill / $DSH_HOME/skills"); + out.push(` ${st.skills_dir}`); + out.push(" 命中与加载由官方 skill 工具负责;插件只安装和删除目录。"); + out.push(""); + if (!st.skills.length) { + out.push(" (暂无用户 Skill — 用 /skills import <压缩包或文件夹> 或设置页导入)"); + return out.join("\n"); + } + for (const item of st.skills) { + const mark = item.valid ? "·" : "!"; + const desc = item.description || "(无说明)"; + out.push(` ${mark} ${item.id} ${desc} (${skills.formatSize(item.size)})`); + if (!item.valid && item.error) out.push(` ${item.error}`); + } + return out.join("\n"); +} + +async function handleSkillsCommand(rawInput) { + const args = (rawInput || "").trim().split(/\s+/).filter(Boolean); + const sub = (args[0] || "list").toLowerCase(); + const dshHome = core.findDshHome(); + + switch (sub) { + case "list": + case "ls": + case "s": + return { kind: "success", text: renderSkillsStatus(await skills.skillsStatus(dshHome)) }; + case "create": + case "new": + case "c": { + const id = args[1]; + if (!id) return { kind: "error", text: "用法: /skills create [说明]" }; + if (!skills.validSkillName(id)) { + return { kind: "error", text: "id 必须是 kebab-case,例如 code-review" }; + } + const description = args.slice(2).join(" ").trim() || id; + try { + const saved = skills.toPublicSkill(dshHome, await skills.saveSkill(dshHome, id, "", description)); + return { + kind: "success", + text: `✓ 已写入官方目录 ${saved.path}\n新会话会进官方 Skill 目录;任务对上或输入 /${id} 时由官方加载。`, + }; + } catch (e) { + return { kind: "error", text: `安装失败: ${e.message}` }; + } + } + case "import": + case "i": { + const src = args.slice(1).join(" ").trim(); + if (!src) return { kind: "error", text: "用法: /skills import <压缩包或文件夹>" }; + try { + const packed = await skills.importFromPath(dshHome, src); + const names = packed.imported.map((item) => item.id).join(", "); + return { kind: "success", text: `✓ 已导入到官方 $DSH_HOME/skills:${names}` }; + } catch (e) { + return { kind: "error", text: `导入失败: ${e.message}` }; + } + } + case "delete": + case "rm": + case "d": { + const id = args[1]; + if (!id) return { kind: "error", text: "用法: /skills delete " }; + try { + const removed = skills.toPublicSkill(dshHome, await skills.deleteSkill(dshHome, id)); + return { + kind: "success", + text: `✓ 已从官方目录删除 ${id}${removed.backup ? `\n备份:${removed.backup}` : ""}`, + }; + } catch (e) { + return { kind: "error", text: `删除失败: ${e.message}` }; + } + } + case "help": + case "h": + default: + return { + kind: "success", + text: "官方 Skill 安装:\n" + + " /skills list 列出 $DSH_HOME/skills\n" + + " /skills create [说明] 写入 /SKILL.md\n" + + " /skills import <路径> 导入压缩包或文件夹到官方目录\n" + + " /skills delete 删除该目录(官方会从目录拿掉)\n" + + " 也可自己删 $DSH_HOME/skills/\n" + + " 不注入 systemPrompt,不替代提示词", + }; + } +} + export function apply(ctx, config) { const cfg = { ...DEFAULTS, ...(config || {}) }; if (!cfg.enabled) return; @@ -572,6 +665,12 @@ export function apply(ctx, config) { input: { hint: "list | use | create [别名] [目标] | delete | reset | help" }, handler: async (invocation) => handleRulesCommand(invocation.rawInput ?? ""), }); + commands.register({ + name: "skills", + description: "官方用户 Skill($DSH_HOME/skills):list | import <路径> | create [说明] | delete | help", + input: { hint: "list | import <路径> | create [说明] | delete | help" }, + handler: async (invocation) => handleSkillsCommand(invocation.rawInput ?? ""), + }); commands.register({ name: "rewind", description: "回退:子代理直接回退一次;主代理 /rewind once 或 /rewind round", @@ -744,6 +843,8 @@ function installWebServer(ctx, cfg) { dsh_home: state.dsh_home, plugin_version: updater.localVersion(), update: updater.lastUpdateResult(), + ...updater.channelPublic(), + ...(await skills.skillsStatus(core.findDshHome()).catch(() => ({ skills: [] }))), }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); @@ -908,10 +1009,7 @@ function installWebServer(ctx, cfg) { if (request.method === "POST") { try { const body = await readJsonBody(request); - const result = body && body.auto - ? await updater.autoUpdateIfNeeded() - : await updater.applyUpdate(); - sendJson(response, 200, result); + sendJson(response, 200, await updater.handleUpdateOp(body || {})); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } @@ -1082,6 +1180,7 @@ function installWebServer(ctx, cfg) { }, }, "dsh-purge: override"); installRulesHttp(host.webServer); + installSkillsHttp(host.webServer); host.webServer.register({ kind: "exact", path: "/dsh-purge/restart", @@ -1186,6 +1285,99 @@ function rulesHttpHandler(forcedOp) { }; } +async function handleSkillsOp(op, body, queryId) { + const dshHome = core.findDshHome(); + const id = typeof body?.id === "string" ? body.id : String(queryId || ""); + if (op === "status") { + return { ok: true, ...(await skills.skillsStatus(dshHome)) }; + } + if (op === "read") { + if (!skills.validSkillName(id)) return { status: 400, ok: false, error: "invalid skill name" }; + const item = await skills.readSkill(dshHome, id); + if (!item) return { status: 404, ok: false, error: `skill not found: ${id}` }; + return { ok: true, ...skills.toPublicSkill(dshHome, item) }; + } + if (op === "save") { + if (!skills.validSkillName(id)) return { status: 400, ok: false, error: "id 必须是 kebab-case,例如 code-review" }; + const content = typeof body?.content === "string" ? body.content : ""; + const description = typeof body?.description === "string" ? body.description : ""; + const saved = await skills.saveSkill(dshHome, id, content, description); + return { ok: true, ...skills.toPublicSkill(dshHome, saved) }; + } + if (op === "delete") { + if (!skills.validSkillName(id)) return { status: 400, ok: false, error: "invalid skill name" }; + const removed = await skills.deleteSkill(dshHome, id); + return { ok: true, ...skills.toPublicSkill(dshHome, removed) }; + } + if (op === "import") { + if (body?.path || body?.source || body?.folder) { + return { status: 400, ok: false, error: "请在本机选择压缩包或文件夹导入" }; + } + if (typeof body?.data === "string" && body.data.trim()) { + const packed = await skills.importArchive(dshHome, Buffer.from(body.data, "base64"), body.name || "skill.zip"); + return { ok: true, ...packed }; + } + if (Array.isArray(body?.files) && body.files.length) { + const packed = await skills.importFileTree(dshHome, body.files, body.name || ""); + return { ok: true, ...packed }; + } + return { status: 400, ok: false, error: "请选择压缩包或文件夹" }; + } + return { status: 400, ok: false, error: `unknown op: ${op}` }; +} + +function skillsHttpHandler(forcedOp) { + return async (request, response) => { + if (request.method === "OPTIONS") { + sendOptions(response); + return; + } + if (request.method !== "GET" && request.method !== "POST") { + response.writeHead(405, { allow: "GET, POST, OPTIONS" }); + response.end(); + return; + } + try { + const url = new URL(request.url ?? "", "http://127.0.0.1"); + const tail = skillRouteTail(url.pathname); + const body = request.method === "POST" ? await readJsonBody(request, 14 * 1024 * 1024) : {}; + const op = forcedOp + || body.op + || tail + || url.searchParams.get("op") + || (url.searchParams.get("id") ? "read" : "status"); + const result = await handleSkillsOp(op, body, url.searchParams.get("id")); + sendJson(response, result.status || 200, result); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e && e.message ? e.message : e) }); + } + }; +} + +function skillRouteTail(pathname) { + const match = String(pathname || "").match(/^\/dsh-purge\/skills?(?:\/(.*))?$/i); + if (!match) return ""; + return String(match[1] || "").replace(/\/$/, ""); +} + +function installSkillsHttp(webServer) { + const stop = []; + const add = (spec) => stop.push(registerRoute(webServer, spec)); + for (const routePath of ["/dsh-purge/skills", "/dsh-purge/skill"]) { + add({ kind: "exact", path: routePath, handler: skillsHttpHandler("") }); + } + add({ kind: "prefix", path: "/dsh-purge/skills", handler: skillsHttpHandler("") }); + for (const op of ["status", "read", "save", "delete", "import"]) { + add({ kind: "exact", path: `/dsh-purge/skills/${op}`, handler: skillsHttpHandler(op) }); + add({ kind: "exact", path: `/dsh-purge/skill/${op}`, handler: skillsHttpHandler(op) }); + } + return () => { + for (let i = stop.length - 1; i >= 0; i -= 1) { + try { stop[i]?.(); } catch { /* ignore */ } + } + }; +} + function installRulesHttp(webServer) { const stop = []; stop.push(registerRoute(webServer, { @@ -1241,13 +1433,14 @@ function registerRoute(webServer, spec) { } } -async function readJsonBody(request) { +async function readJsonBody(request, maxBytes = 512 * 1024) { const chunks = []; let size = 0; + const limit = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : 512 * 1024; for await (const chunk of request) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); size += buffer.length; - if (size > 512 * 1024) throw new Error("request body too large"); + if (size > limit) throw new Error("request body too large"); chunks.push(buffer); } const raw = Buffer.concat(chunks).toString("utf8").trim(); diff --git a/lib/skills.js b/lib/skills.js new file mode 100644 index 0000000..b532883 --- /dev/null +++ b/lib/skills.js @@ -0,0 +1,560 @@ +import { promises as fsp } from "node:fs"; +import { spawnSync } from "node:child_process"; +import os from "node:os"; +import path from "node:path"; +import { findDshHome } from "./core.js"; + +export { findDshHome }; + +/** 与官方 @deepseek-ai/dsh-skill 一致:kebab-case。 */ +const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +const MAX_SKILL_BYTES = 256 * 1024; +const MAX_ARCHIVE_BYTES = 12 * 1024 * 1024; +const MAX_IMPORT_FILES = 200; +const MAX_DESCRIPTION = 500; +const SKIP_COPY_NAMES = new Set([".", "..", ".system", ".git", "node_modules", "__MACOSX", ".DS_Store"]); + +export function validSkillName(id) { + return typeof id === "string" && SKILL_NAME_RE.test(id); +} + +export function skillsDir(dshHome) { + return path.join(dshHome, "skills"); +} + +export function skillBackupDir(dshHome) { + return path.join(dshHome, "dsh-purge-backups", "skills"); +} + +export function skillBundleDir(dshHome, id) { + return path.join(skillsDir(dshHome), id); +} + +export function skillBundleFile(dshHome, id) { + return path.join(skillBundleDir(dshHome, id), "SKILL.md"); +} + +export function skillFlatFile(dshHome, id) { + return path.join(skillsDir(dshHome), `${id}.md`); +} + +/** 对外只报 $DSH_HOME/...,不暴露本机盘符或安装目录。 */ +export function displayUnderHome(dshHome, absPath) { + if (!absPath) return ""; + const home = path.resolve(dshHome); + const abs = path.resolve(absPath); + if (abs === home) return "$DSH_HOME"; + const rel = path.relative(home, abs); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return "$DSH_HOME"; + return `$DSH_HOME/${rel.split(/[/\\]/).join("/")}`; +} + +export function toPublicSkill(dshHome, item) { + if (!item || typeof item !== "object") return item; + const next = { ...item }; + if (typeof next.path === "string") next.path = displayUnderHome(dshHome, next.path); + if (typeof next.backup === "string") next.backup = displayUnderHome(dshHome, next.backup); + return next; +} + +function assertInside(root, target) { + const a = path.resolve(root); + const b = path.resolve(target); + const prefix = a.endsWith(path.sep) ? a : a + path.sep; + if (b !== a && !b.startsWith(prefix)) { + throw new Error("skill path escaped official skills directory"); + } +} + +function yamlScalar(value) { + const text = String(value ?? "").trim(); + if (!text) return '""'; + if (/^[A-Za-z0-9._+/-]+$/.test(text)) return text; + return JSON.stringify(text); +} + +export function splitFrontmatter(raw) { + const text = String(raw || "").replace(/^\uFEFF/, ""); + if (!text.startsWith("---")) return null; + const afterOpen = text.slice(3); + if (!/^\r?\n/.test(afterOpen)) return null; + const rest = afterOpen.replace(/^\r?\n/, ""); + const close = rest.match(/\r?\n---(?:\r?\n|$)/); + if (!close || close.index == null) return null; + return { + head: rest.slice(0, close.index), + body: rest.slice(close.index + close[0].length), + }; +} + +function yamlLineField(head, key) { + const re = new RegExp(`^${key}:\\s*(.*)$`, "m"); + const match = String(head || "").match(re); + if (!match) return ""; + let value = match[1].trim(); + if (!value) return ""; + if (value === "|" || value === ">" || value === "|-" || value === ">-") return ""; + if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) { + try { + return value.startsWith("\"") ? JSON.parse(value) : value.slice(1, -1); + } catch { + return value.slice(1, -1); + } + } + const comment = value.indexOf(" #"); + if (comment >= 0) value = value.slice(0, comment).trim(); + return value; +} + +export function parseSkillDocument(raw) { + const parts = splitFrontmatter(raw); + if (!parts) return { ok: false, error: "缺少 YAML frontmatter(须以 --- 包围)" }; + const name = yamlLineField(parts.head, "name"); + const description = yamlLineField(parts.head, "description"); + if (!validSkillName(name)) return { ok: false, error: "frontmatter.name 必须是 kebab-case,例如 code-review" }; + if (!description) return { ok: false, error: "frontmatter.description 必填(单行)" }; + return { ok: true, name, description, body: parts.body, head: parts.head }; +} + +export function renderSkillDocument(id, description, body = "") { + if (!validSkillName(id)) throw new Error("invalid skill name"); + const desc = String(description || "").trim() || id; + const text = String(body || "").replace(/^\uFEFF/, ""); + const parts = splitFrontmatter(text); + const inner = parts ? parts.body : text; + return `---\nname: ${id}\ndescription: ${yamlScalar(desc.slice(0, MAX_DESCRIPTION))}\n---\n\n${inner.replace(/^\r?\n/, "")}`; +} + +function upsertYamlLine(head, key, value) { + const line = `${key}: ${yamlScalar(value)}`; + const re = new RegExp(`^${key}:\\s*.*$`, "m"); + if (re.test(head)) return head.replace(re, line); + return `${line}\n${String(head || "").replace(/^\r?\n/, "")}`; +} + +/** 保留官方 whenToUse / invocation / metadata,只改 name 与 description。 */ +export function mergeSkillDocument(id, description, raw = "") { + const parsed = parseSkillDocument(raw); + const desc = String(description || "").trim() || (parsed.ok ? parsed.description : "") || id; + if (!parsed.ok) return renderSkillDocument(id, desc, raw); + const head = upsertYamlLine(upsertYamlLine(parsed.head, "name", id), "description", desc.slice(0, MAX_DESCRIPTION)); + return `---\n${head.replace(/^\r?\n/, "").replace(/\r?\n$/, "")}\n---\n\n${parsed.body.replace(/^\r?\n/, "")}`; +} + +export function formatSize(bytes) { + if (!Number.isFinite(bytes) || bytes < 0) return "0 B"; + if (bytes < 1024) return `${bytes} B`; + const kb = bytes / 1024; + return `${kb >= 100 ? Math.round(kb) : kb.toFixed(1)} KB`; +} + +async function fileSize(fp) { + try { + return (await fsp.stat(fp)).size; + } catch { + return 0; + } +} + +async function pathExists(fp) { + try { + await fsp.access(fp); + return true; + } catch { + return false; + } +} + +async function skillFromFile(id, fp, kind) { + const content = await fsp.readFile(fp, "utf8"); + const parsed = parseSkillDocument(content); + return { + id, + kind, + path: fp, + content, + description: parsed.ok ? parsed.description : "", + valid: parsed.ok, + error: parsed.ok ? null : parsed.error, + size: Buffer.byteLength(content, "utf8"), + }; +} + +export async function readSkill(dshHome, id) { + if (!validSkillName(id)) throw new Error(`invalid skill name: ${id}`); + const bundle = skillBundleFile(dshHome, id); + if (await pathExists(bundle)) return skillFromFile(id, bundle, "bundle"); + const flat = skillFlatFile(dshHome, id); + if (await pathExists(flat)) return skillFromFile(id, flat, "flat"); + const dir = skillsDir(dshHome); + let entries = []; + try { + entries = await fsp.readdir(dir, { withFileTypes: true }); + } catch { + return null; + } + for (const entry of entries) { + if (!entry.isDirectory() || entry.name === ".system") continue; + const fp = path.join(dir, entry.name, "SKILL.md"); + if (!(await pathExists(fp))) continue; + const parsed = parseSkillDocument(await fsp.readFile(fp, "utf8")); + if (parsed.ok && parsed.name === id) return skillFromFile(id, fp, "bundle"); + } + return null; +} + +export async function listSkills(dshHome) { + const dir = skillsDir(dshHome); + const out = []; + let entries = []; + try { + entries = await fsp.readdir(dir, { withFileTypes: true }); + } catch { + return out; + } + const seen = new Set(); + for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { + if (entry.name === ".system") continue; + if (entry.isDirectory()) { + const fp = path.join(dir, entry.name, "SKILL.md"); + if (!(await pathExists(fp))) continue; + const parsed = parseSkillDocument(await fsp.readFile(fp, "utf8")); + const id = parsed.ok ? parsed.name : (validSkillName(entry.name) ? entry.name : ""); + if (!id || seen.has(id)) continue; + seen.add(id); + out.push(await skillFromFile(id, fp, "bundle")); + continue; + } + if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name === "SKILL.md") continue; + const fallback = entry.name.slice(0, -3); + const fp = path.join(dir, entry.name); + const parsed = parseSkillDocument(await fsp.readFile(fp, "utf8")); + const id = parsed.ok ? parsed.name : (validSkillName(fallback) ? fallback : ""); + if (!id || seen.has(id)) continue; + seen.add(id); + out.push(await skillFromFile(id, fp, "flat")); + } + return out; +} + +async function copyDir(src, dest) { + await fsp.mkdir(dest, { recursive: true }); + for (const entry of await fsp.readdir(src, { withFileTypes: true })) { + if (SKIP_COPY_NAMES.has(entry.name) || entry.name.startsWith("._")) continue; + if (entry.isSymbolicLink()) continue; + const from = path.join(src, entry.name); + const to = path.join(dest, entry.name); + assertInside(dest, to); + if (entry.isDirectory()) await copyDir(from, to); + else if (entry.isFile()) await fsp.copyFile(from, to); + } +} + +async function backupExisting(dshHome, id) { + const existing = await readSkill(dshHome, id).catch(() => null); + const root = skillsDir(dshHome); + const bundleDir = existing?.kind === "bundle" ? path.dirname(existing.path) : skillBundleDir(dshHome, id); + const flat = existing?.kind === "flat" ? existing.path : skillFlatFile(dshHome, id); + const hasBundle = await pathExists(bundleDir); + const hasFlat = await pathExists(flat); + if (!hasBundle && !hasFlat) return null; + const stamp = new Date().toISOString().replace(/[:.]/g, "-"); + const dest = path.join(skillBackupDir(dshHome), `${id}_${stamp}`); + assertInside(path.join(dshHome, "dsh-purge-backups"), dest); + await fsp.mkdir(dest, { recursive: true }); + if (hasBundle) { + assertInside(root, bundleDir); + await copyDir(bundleDir, path.join(dest, id)); + } + if (hasFlat) { + assertInside(root, flat); + await fsp.copyFile(flat, path.join(dest, `${id}.md`)); + } + return dest; +} + +async function removeOfficialSkill(dshHome, id) { + const existing = await readSkill(dshHome, id).catch(() => null); + const root = skillsDir(dshHome); + const bundleDir = existing?.kind === "bundle" ? path.dirname(existing.path) : skillBundleDir(dshHome, id); + const flat = existing?.kind === "flat" ? existing.path : skillFlatFile(dshHome, id); + if (await pathExists(bundleDir)) { + assertInside(root, bundleDir); + await fsp.rm(bundleDir, { recursive: true, force: true }); + } + if (await pathExists(flat)) { + assertInside(root, flat); + await fsp.rm(flat, { force: true }); + } + const canonical = skillBundleDir(dshHome, id); + if (canonical !== bundleDir && await pathExists(canonical)) { + assertInside(root, canonical); + await fsp.rm(canonical, { recursive: true, force: true }); + } +} + +export async function saveSkill(dshHome, id, content, description) { + if (!validSkillName(id)) throw new Error(`invalid skill name: ${id}`); + const parsed = parseSkillDocument(content); + const desc = String(description || "").trim() || (parsed.ok ? parsed.description : ""); + const document = mergeSkillDocument(id, desc, String(content || "")); + if (Buffer.byteLength(document, "utf8") > MAX_SKILL_BYTES) { + throw new Error("skill too large (max 256KB)"); + } + const check = parseSkillDocument(document); + if (!check.ok) throw new Error(check.error); + const root = skillsDir(dshHome); + const dest = skillBundleFile(dshHome, id); + assertInside(root, dest); + const backup = await backupExisting(dshHome, id); + await removeOfficialSkill(dshHome, id); + await fsp.mkdir(skillBundleDir(dshHome, id), { recursive: true }); + await fsp.writeFile(dest, document, "utf8"); + return { + id, + path: dest, + description: check.description, + backup, + size: Buffer.byteLength(document, "utf8"), + content: document, + }; +} + +export async function deleteSkill(dshHome, id) { + if (!validSkillName(id)) throw new Error(`invalid skill name: ${id}`); + const existing = await readSkill(dshHome, id); + if (!existing) throw new Error(`skill not found: ${id}`); + const backup = await backupExisting(dshHome, id); + await removeOfficialSkill(dshHome, id); + return { id, backup, path: existing.path }; +} + +function kebabFromLabel(name) { + const base = String(name || "") + .replace(/\.(zip|tgz|tar\.gz|tar|skill)$/i, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return validSkillName(base) ? base : ""; +} + +function isUnsafeArchiveEntry(name) { + const rel = String(name || "").replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\/+$/, ""); + if (!rel) return false; + if (rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return true; + return rel.split("/").some((part) => part === ".." || part === ""); +} + +function listArchiveEntries(archivePath) { + const result = spawnSync("tar", ["-tf", archivePath], { + windowsHide: true, + encoding: "utf8", + timeout: 15000, + }); + if (result.status !== 0) return null; + return String(result.stdout || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean); +} + +function extractArchive(archivePath, dest) { + const entries = listArchiveEntries(archivePath); + if (entries && entries.some(isUnsafeArchiveEntry)) { + throw new Error("压缩包路径不合法"); + } + if (entries && entries.length > MAX_IMPORT_FILES) { + throw new Error("压缩包里文件太多"); + } + const result = spawnSync("tar", ["-xf", archivePath, "-C", dest], { + windowsHide: true, + encoding: "utf8", + timeout: 30000, + }); + if (result.status === 0) return; + if (/\.zip$/i.test(archivePath) && process.platform === "win32") { + const ps = spawnSync("powershell", [ + "-NoProfile", + "-Command", + `Expand-Archive -LiteralPath '${String(archivePath).replace(/'/g, "''")}' -DestinationPath '${String(dest).replace(/'/g, "''")}' -Force`, + ], { + windowsHide: true, + encoding: "utf8", + timeout: 30000, + }); + if (ps.status === 0) return; + } + const detail = String(result.stderr || result.stdout || "").trim(); + throw new Error(detail || "无法解压,请改用文件夹导入"); +} + +async function walkFiles(root, onFile, depth = 0) { + if (depth > 6) return; + let entries = []; + try { + entries = await fsp.readdir(root, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + if (entry.name === "." || entry.name === ".." || entry.name === ".system" || entry.name === "__MACOSX" || entry.name === ".DS_Store") continue; + if (entry.name.startsWith("._")) continue; + const full = path.join(root, entry.name); + assertInside(root, full); + if (entry.isDirectory()) await walkFiles(full, onFile, depth + 1); + else if (entry.isFile()) await onFile(full); + } +} + +export async function findSkillRoots(root) { + const dirs = []; + const flats = []; + async function visit(dir, depth) { + if (depth > 4) return; + let entries = []; + try { + entries = await fsp.readdir(dir, { withFileTypes: true }); + } catch { + return; + } + if (entries.some((entry) => entry.isFile() && entry.name === "SKILL.md")) { + dirs.push(dir); + return; + } + for (const entry of entries) { + if (entry.name === "." || entry.name === "..") continue; + if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "SKILL.md") { + const raw = await fsp.readFile(path.join(dir, entry.name), "utf8"); + if (parseSkillDocument(raw).ok) flats.push(path.join(dir, entry.name)); + } + } + for (const entry of entries) { + if (!entry.isDirectory()) continue; + if (entry.name === "." || entry.name === ".." || entry.name === ".system" || entry.name === "__MACOSX") continue; + const next = path.join(dir, entry.name); + assertInside(root, next); + await visit(next, depth + 1); + } + } + await visit(root, 0); + return { dirs, flats }; +} + +async function installBundleDir(dshHome, srcDir, fallbackId) { + const mdPath = path.join(srcDir, "SKILL.md"); + const raw = await fsp.readFile(mdPath, "utf8"); + const parsed = parseSkillDocument(raw); + const id = parsed.ok ? parsed.name : kebabFromLabel(fallbackId || path.basename(srcDir)); + if (!validSkillName(id)) throw new Error("压缩包/文件夹里没有合法的 Skill 名称"); + const dest = skillBundleDir(dshHome, id); + assertInside(skillsDir(dshHome), dest); + const backup = await backupExisting(dshHome, id); + await removeOfficialSkill(dshHome, id); + await copyDir(srcDir, dest); + const destMd = path.join(dest, "SKILL.md"); + if (parsed.ok && parsed.name !== id) { + await fsp.writeFile(destMd, mergeSkillDocument(id, parsed.description, raw), "utf8"); + } else if (!parsed.ok && !String(raw).replace(/^\uFEFF/, "").startsWith("---")) { + await fsp.writeFile(destMd, renderSkillDocument(id, id, raw), "utf8"); + } + return { id, path: destMd, backup, description: parsed.ok ? parsed.description : id }; +} + +async function installFlatFile(dshHome, srcFile, fallbackId) { + const raw = await fsp.readFile(srcFile, "utf8"); + const parsed = parseSkillDocument(raw); + const id = parsed.ok ? parsed.name : kebabFromLabel(fallbackId || path.basename(srcFile, ".md")); + if (!parsed.ok) throw new Error(parsed.error); + return saveSkill(dshHome, id, raw, parsed.description); +} + +async function installFoundSkills(dshHome, root, fallbackId) { + const found = await findSkillRoots(root); + const imported = []; + for (const dir of found.dirs) { + imported.push(await installBundleDir(dshHome, dir, fallbackId || path.basename(dir))); + } + if (!imported.length) { + for (const file of found.flats) { + imported.push(await installFlatFile(dshHome, file, fallbackId)); + } + } + if (!imported.length) throw new Error("未找到 SKILL.md 或合法的 Skill 文件"); + return imported; +} + +export async function importArchive(dshHome, buffer, filename = "skill.zip") { + const bytes = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + if (!bytes.length) throw new Error("压缩包是空的"); + if (bytes.length > MAX_ARCHIVE_BYTES) throw new Error("压缩包太大(最大 12MB)"); + const temp = await fsp.mkdtemp(path.join(os.tmpdir(), "dshp-skill-")); + const archive = path.join(temp, path.basename(filename) || "skill.zip"); + const unpacked = path.join(temp, "unpacked"); + try { + await fsp.mkdir(unpacked, { recursive: true }); + await fsp.writeFile(archive, bytes); + extractArchive(archive, unpacked); + await walkFiles(unpacked, async () => {}); + const imported = await installFoundSkills(dshHome, unpacked, kebabFromLabel(filename)); + return { imported: imported.map((item) => toPublicSkill(dshHome, item)) }; + } finally { + await fsp.rm(temp, { recursive: true, force: true }).catch(() => {}); + } +} + +export async function importFileTree(dshHome, files, fallbackId = "") { + if (!Array.isArray(files) || !files.length) throw new Error("文件夹是空的"); + if (files.length > MAX_IMPORT_FILES) throw new Error("文件夹里文件太多"); + const temp = await fsp.mkdtemp(path.join(os.tmpdir(), "dshp-skill-")); + try { + let total = 0; + for (const file of files) { + const rel = String(file?.path || file?.name || "").replace(/\\/g, "/").replace(/^\/+/, ""); + if (!rel || rel.includes("..") || path.isAbsolute(rel) || isUnsafeArchiveEntry(rel)) { + throw new Error("文件夹路径不合法"); + } + const dest = path.join(temp, rel); + assertInside(temp, dest); + await fsp.mkdir(path.dirname(dest), { recursive: true }); + const text = typeof file.content === "string" ? file.content : ""; + const raw = file.encoding === "base64" ? Buffer.from(text, "base64") : Buffer.from(text, "utf8"); + total += raw.length; + if (raw.length > MAX_ARCHIVE_BYTES || total > MAX_ARCHIVE_BYTES) throw new Error("文件太大"); + await fsp.writeFile(dest, raw); + } + const imported = await installFoundSkills(dshHome, temp, fallbackId); + return { imported: imported.map((item) => toPublicSkill(dshHome, item)) }; + } finally { + await fsp.rm(temp, { recursive: true, force: true }).catch(() => {}); + } +} + +export async function importFromPath(dshHome, sourcePath) { + const src = path.resolve(String(sourcePath || "")); + const stat = await fsp.stat(src); + if (stat.isDirectory()) { + const imported = await installFoundSkills(dshHome, src, kebabFromLabel(path.basename(src))); + return { imported: imported.map((item) => toPublicSkill(dshHome, item)) }; + } + if (stat.isFile()) { + const name = path.basename(src); + if (/\.(zip|tgz|tar\.gz|tar|skill)$/i.test(name)) { + return importArchive(dshHome, await fsp.readFile(src), name); + } + return { imported: [toPublicSkill(dshHome, await installFlatFile(dshHome, src, kebabFromLabel(name)))] }; + } + throw new Error("只能导入压缩包或文件夹"); +} + +export async function skillsStatus(dshHome) { + const listed = await listSkills(dshHome); + return { + skills_dir: "$DSH_HOME/skills", + skills: listed.map((item) => ({ + id: item.id, + description: item.description, + kind: item.kind, + valid: item.valid, + error: item.error, + size: item.size, + path: displayUnderHome(dshHome, item.path), + })), + }; +} diff --git a/lib/update.js b/lib/update.js index 0e2d710..cc85c5d 100644 --- a/lib/update.js +++ b/lib/update.js @@ -9,11 +9,14 @@ import { adapterFor, detectSurface } from "./surface.js"; import { cliInvocation } from "./desktop.js"; const REPO = "YuJunZhiXue/dsh-purge"; -const BRANCH = "master"; -const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`; -export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.tar.gz`; -const GITHUB_SPEC = `github:${REPO}#${BRANCH}`; +const STABLE_REF = "master"; +const BETA_REF = "beta"; +export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${STABLE_REF}.tar.gz`; const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), ".."); +const CHANNELS = { + stable: { id: "stable", ref: STABLE_REF, label: "正式版" }, + beta: { id: "beta", ref: BETA_REF, label: "测试版" }, +}; const COPY_NAMES = [ "lib", "bin", @@ -47,10 +50,86 @@ export function localVersion() { } } +function channelStatePath() { + return path.join(findDshHome(), "dsh-purge", "channel.json"); +} + +function historyPath() { + return path.join(findDshHome(), "dsh-purge", "version-history.json"); +} + function stampPath() { return path.join(findDshHome(), "dsh-purge", "installed-rev"); } +export function normalizeChannel(value) { + return String(value || "").toLowerCase() === "beta" ? "beta" : "stable"; +} + +function isBetaName(name) { + return /(?:^|[-._])(beta|rc|pre|preview|test)(?:\d|$|[-._])/i.test(String(name || "")); +} + +export function readChannelState() { + const raw = readJson(channelStatePath()) || {}; + return { + channel: normalizeChannel(raw.channel), + pin: typeof raw.pin === "string" ? raw.pin.trim() : "", + }; +} + +function writeChannelState(next) { + const state = { + channel: normalizeChannel(next?.channel), + pin: typeof next?.pin === "string" ? next.pin.trim() : "", + }; + fs.mkdirSync(path.dirname(channelStatePath()), { recursive: true }); + fs.writeFileSync(channelStatePath(), `${JSON.stringify(state, null, 2)}\n`, "utf8"); + return state; +} + +export function channelPublic(state = readChannelState()) { + const meta = CHANNELS[state.channel] || CHANNELS.stable; + return { + channel: meta.id, + channelLabel: meta.label, + pin: state.pin || "", + }; +} + +function currentChannelRef(state = readChannelState()) { + return (CHANNELS[state.channel] || CHANNELS.stable).ref; +} + +function readHistory() { + const raw = readJson(historyPath()); + return Array.isArray(raw) ? raw : []; +} + +function pushHistory(entry) { + const next = [entry, ...readHistory().filter((item) => item && item.ref !== entry.ref)].slice(0, 20); + fs.mkdirSync(path.dirname(historyPath()), { recursive: true }); + fs.writeFileSync(historyPath(), `${JSON.stringify(next, null, 2)}\n`, "utf8"); +} + +function archiveZipUrl(ref) { + const value = String(ref || STABLE_REF); + if (/^[0-9a-f]{40}$/i.test(value)) return `https://github.com/${REPO}/archive/${value}.zip`; + if (/^v?\d/.test(value)) return `https://github.com/${REPO}/archive/refs/tags/${encodeURIComponent(value)}.zip`; + return `https://github.com/${REPO}/archive/refs/heads/${encodeURIComponent(value)}.zip`; +} + +function archiveTarballUrl(ref) { + const value = String(ref || STABLE_REF); + if (/^[0-9a-f]{40}$/i.test(value)) return `https://github.com/${REPO}/archive/${value}.tar.gz`; + if (/^v?\d/.test(value)) return `https://github.com/${REPO}/archive/refs/tags/${encodeURIComponent(value)}.tar.gz`; + return `https://github.com/${REPO}/archive/refs/heads/${encodeURIComponent(value)}.tar.gz`; +} + +function githubSpec(ref) { + return `github:${REPO}#${ref || STABLE_REF}`; +} + function readStamp() { try { return fs.readFileSync(stampPath(), "utf8").trim(); @@ -205,15 +284,15 @@ export function runDshPlugin(profile, args) { }); } -export function pluginAddSpec(spec) { +export function pluginAddSpec(spec, ref = currentChannelRef()) { const s = String(spec || ""); - if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return TARBALL_URL; - if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC; + if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return archiveTarballUrl(ref); + if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return githubSpec(ref); return ""; } -function dshReinstall(profile, spec) { - const addSpec = pluginAddSpec(spec); +function dshReinstall(profile, spec, ref = currentChannelRef()) { + const addSpec = pluginAddSpec(spec, ref); if (addSpec) { runDshPlugin(profile, ["add", "--force", addSpec]); return; @@ -221,7 +300,7 @@ function dshReinstall(profile, spec) { try { runDshPlugin(profile, ["update", "dsh-purge"]); } catch { - runDshPlugin(profile, ["add", "--force", TARBALL_URL]); + runDshPlugin(profile, ["add", "--force", archiveTarballUrl(ref)]); } } @@ -312,8 +391,8 @@ function versionFromPackageText(text) { return pkg && pkg.version ? String(pkg.version) : ""; } -async function remotePackageVersion(sha = "") { - const ref = sha || BRANCH; +async function remotePackageVersion(sha = "", fallbackRef = STABLE_REF) { + const ref = sha || fallbackRef; const urls = [ sha ? `https://cdn.jsdelivr.net/gh/${REPO}@${sha}/package.json` : "", `https://raw.githubusercontent.com/${REPO}/${ref}/package.json`, @@ -340,11 +419,12 @@ async function remotePackageVersion(sha = "") { return ""; } -async function remoteHeadSha() { - const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`) +async function remoteHeadSha(ref = STABLE_REF) { + const target = encodeURIComponent(ref || STABLE_REF); + const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${target}`) .then((data) => (data?.sha ? String(data.sha) : "")) .catch(() => ""); - const fromAtom = fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`) + const fromAtom = fetchText(`https://github.com/${REPO}/commits/${ref}.atom`) .then((atom) => { const hit = atom.match(/tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/); return hit ? hit[1] : ""; @@ -354,31 +434,163 @@ async function remoteHeadSha() { return apiSha || atomSha || ""; } -export async function checkUpdate() { +function versionLabel(version, channel, sha = "") { + const ver = String(version || "").replace(/^v/, "") || (sha ? String(sha).slice(0, 7) : ""); + const mark = channel === "beta" ? "测试" : "正式"; + return ver ? `${ver}(${mark})` : mark; +} + +function rememberVersion(item, seen) { + if (!item || !item.ref) return null; + const key = `${item.sha || ""}|${item.ref}`.toLowerCase(); + if (seen.has(key)) return null; + seen.add(key); + return item; +} + +async function listGithubTags() { + try { + const rows = await fetchJson(`https://api.github.com/repos/${REPO}/tags?per_page=50`); + if (!Array.isArray(rows)) return []; + return rows.map((row) => { + const name = String(row?.name || "").trim(); + if (!name || !/^v?\d+\.\d+/.test(name)) return null; + const sha = row?.commit?.sha ? String(row.commit.sha) : ""; + const channel = isBetaName(name) ? "beta" : "stable"; + return { + id: name, + ref: name, + sha, + version: name.replace(/^v/, ""), + channel, + label: versionLabel(name, channel, sha), + kind: "tag", + }; + }).filter(Boolean); + } catch { + return []; + } +} + +async function listRemoteVersions() { + const state = readChannelState(); + const seen = new Set(); + const out = []; + const add = (item) => { + const next = rememberVersion(item, seen); + if (next) out.push(next); + }; + + const [stableSha, betaSha, tags] = await Promise.all([ + remoteHeadSha(STABLE_REF), + remoteHeadSha(BETA_REF), + listGithubTags(), + ]); + + if (stableSha) { + const version = await remotePackageVersion(stableSha, STABLE_REF).catch(() => ""); + add({ + id: STABLE_REF, + ref: STABLE_REF, + sha: stableSha, + version: version || "", + channel: "stable", + label: `${versionLabel(version, "stable", stableSha)} · 最新`, + kind: "head", + latest: true, + }); + } + if (betaSha) { + const version = await remotePackageVersion(betaSha, BETA_REF).catch(() => ""); + add({ + id: BETA_REF, + ref: BETA_REF, + sha: betaSha, + version: version || "", + channel: "beta", + label: `${versionLabel(version, "beta", betaSha)} · 最新`, + kind: "head", + latest: true, + }); + } + for (const tag of tags) add(tag); + for (const item of readHistory()) { + if (!item || !item.ref) continue; + add({ + ...item, + label: item.label || versionLabel(item.version, item.channel, item.sha), + kind: item.kind || "history", + }); + } + const localVer = localVersion(); - const remoteSha = await remoteHeadSha(); - const remoteVer = await remotePackageVersion(remoteSha); - if (!remoteSha && !remoteVer) throw new Error("无法读取 GitHub master"); + const localSha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp(); + return { + versions: out.map((item) => ({ + ...item, + shaShort: item.sha ? String(item.sha).slice(0, 7) : "", + current: Boolean( + (localSha && item.sha && sameRev(localSha, item.sha)) + || (state.pin && item.ref === state.pin) + || (!state.pin && item.latest && item.channel === state.channel && item.version && item.version === localVer), + ), + })), + hasBeta: Boolean(betaSha || out.some((item) => item.channel === "beta" && item.kind === "tag")), + stableSha, + betaSha, + }; +} + +export async function checkUpdate() { + const state = readChannelState(); + const localVer = localVersion(); + const listed = await listRemoteVersions(); + const channelRef = currentChannelRef(state); + const remoteSha = state.channel === "beta" ? listed.betaSha : listed.stableSha; + const remoteVer = remoteSha ? await remotePackageVersion(remoteSha, channelRef) : ""; + if (!remoteSha && !remoteVer) { + if (state.channel === "beta") { + return rememberUpdate({ + ok: true, + hasUpdate: false, + hasBeta: false, + error: "还没有测试版", + localVersion: localVer, + remoteVersion: "", + localSha: ((gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp()).slice(0, 7), + remoteSha: "", + via: detectVia(), + versions: listed.versions, + ...channelPublic(state), + }); + } + throw new Error("无法读取 GitHub master"); + } const gitSha = gitOk() ? gitHead(PLUGIN_ROOT) : ""; const stamp = readStamp(); const localRev = gitSha || stamp; let hasUpdate = false; - if (remoteSha && localRev) { + if (state.pin) { + hasUpdate = Boolean(remoteSha && localRev && !sameRev(localRev, remoteSha)); + } else if (remoteSha && localRev) { hasUpdate = !sameRev(localRev, remoteSha); } else if (remoteVer && localVer && remoteVer !== localVer) { hasUpdate = true; } else if (remoteSha && !localRev) { - // zip / dsh 安装没有 stamp,按有更新处理,拉一次与 master 对齐。 hasUpdate = true; } const result = { ok: true, hasUpdate, + hasBeta: listed.hasBeta, + pinned: Boolean(state.pin), localVersion: localVer, remoteVersion: remoteVer || (remoteSha ? remoteSha.slice(0, 7) : ""), localSha: localRev ? localRev.slice(0, 7) : "", remoteSha: remoteSha ? remoteSha.slice(0, 7) : "", via: detectVia(), + versions: listed.versions, + ...channelPublic(state), }; rememberUpdate(result); return result; @@ -422,21 +634,26 @@ function runGit(dir, args, timeout = 20000) { } } -function gitPull(dir) { - try { - runGit(dir, ["pull", "--ff-only", "origin", BRANCH], 60000); - return; - } catch (pullErr) { - try { - runGit(dir, ["fetch", "origin", BRANCH], 60000); - runGit(dir, ["reset", "--hard", `origin/${BRANCH}`], 60000); - return; - } catch (resetErr) { - throw new Error( - `git 更新失败(${dir}):${String(resetErr.message || resetErr).slice(0, 240)};${String(pullErr.message || pullErr).slice(0, 160)}`, - ); - } +function gitResetTo(dir, ref, { force = false } = {}) { + if (!force && gitTrackedDirty(dir)) { + throw new Error("本地插件文件有未提交改动,未覆盖"); } + const target = String(ref || STABLE_REF); + try { + if (target === STABLE_REF || target === BETA_REF) { + runGit(dir, ["pull", "--ff-only", "origin", target], 60000); + return; + } + } catch { + // 再走 fetch + reset。 + } + try { + runGit(dir, ["fetch", "origin", "--tags", target], 60000); + } catch { + runGit(dir, ["fetch", "origin", "--tags"], 60000); + } + const remote = (target === STABLE_REF || target === BETA_REF) ? `origin/${target}` : target; + runGit(dir, ["reset", "--hard", remote], 60000); } function extractZip(zip, dest) { @@ -457,12 +674,12 @@ function extractZip(zip, dest) { ); } -async function overlayFromZip(dests) { +async function overlayFromZip(dests, ref = STABLE_REF) { const unique = [...new Set(dests.filter(Boolean).map((d) => realPath(d)))]; if (!unique.length) return; const tmp = await fsp.mkdtemp(path.join(os.tmpdir(), "dsh-purge-upd-")); - const zip = path.join(tmp, "master.zip"); - const res = await fetchRes(ZIP_URL, 45000); + const zip = path.join(tmp, "plugin.zip"); + const res = await fetchRes(archiveZipUrl(ref), 45000); await fsp.writeFile(zip, Buffer.from(await res.arrayBuffer())); extractZip(zip, tmp); const names = await fsp.readdir(tmp); @@ -484,23 +701,31 @@ async function overlayFromZip(dests) { } } -export async function applyUpdate(jobs = planUpdates()) { +export async function applyUpdate(jobs = planUpdates(), options = {}) { + if (!Array.isArray(jobs)) { + options = jobs && typeof jobs === "object" ? jobs : {}; + jobs = planUpdates(); + } + const state = readChannelState(); + const ref = String(options.ref || currentChannelRef(state) || STABLE_REF); + const force = options.force !== false; const zipDirs = []; const vias = new Set(); for (const job of jobs) { if (job.kind === "git") { try { - gitPull(job.dir); + gitResetTo(job.dir, ref, { force }); vias.add("git"); continue; - } catch { + } catch (e) { + if (!force && /未提交改动/.test(String(e && e.message))) throw e; zipDirs.push(job.dir); } continue; } if (job.kind === "dsh") { try { - dshReinstall(job.profile, job.spec); + dshReinstall(job.profile, job.spec, ref); vias.add("dsh"); continue; } catch { @@ -511,28 +736,92 @@ export async function applyUpdate(jobs = planUpdates()) { } } if (zipDirs.length) { - await overlayFromZip(zipDirs); + await overlayFromZip(zipDirs, ref); vias.add("zip"); } - const sha = (await remoteHeadSha()) || (gitOk() ? gitHead(PLUGIN_ROOT) : ""); + const sha = (await remoteHeadSha(ref)) || (gitOk() ? gitHead(PLUGIN_ROOT) : ""); if (sha) writeStamp(sha); const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia(); + const pin = options.pin === false ? "" : (options.pin || state.pin || ""); + const channel = normalizeChannel(options.channel || state.channel); + const saved = writeChannelState({ channel, pin }); + const localVer = localVersion(); + pushHistory({ + ref, + sha: sha || "", + version: localVer, + channel, + label: versionLabel(localVer, channel, sha), + at: new Date().toISOString(), + }); + const listed = await listRemoteVersions().catch(() => ({ versions: [], hasBeta: saved.channel === "beta" })); return rememberUpdate({ ok: true, applied: true, hasUpdate: false, - localVersion: localVersion(), - remoteVersion: localVersion(), + hasBeta: listed.hasBeta, + pinned: Boolean(saved.pin), + localVersion: localVer, + remoteVersion: localVer, localSha: sha ? String(sha).slice(0, 7) : "", remoteSha: sha ? String(sha).slice(0, 7) : "", needRestart: true, via, + versions: listed.versions, + ...channelPublic(saved), }); } +export async function switchChannel(channel, { apply = true } = {}) { + const next = normalizeChannel(channel); + writeChannelState({ channel: next, pin: "" }); + if (next === "beta") { + const betaSha = await remoteHeadSha(BETA_REF); + const tags = await listGithubTags(); + const hasBeta = Boolean(betaSha || tags.some((item) => item.channel === "beta")); + if (!hasBeta) { + const stable = writeChannelState({ channel: "stable", pin: "" }); + return rememberUpdate({ + ok: false, + error: "还没有测试版", + hasBeta: false, + ...channelPublic(stable), + versions: [], + }); + } + if (!betaSha && apply) { + const tag = tags.find((item) => item.channel === "beta"); + if (tag) return applyUpdate(planUpdates(), { ref: tag.ref, channel: "beta", pin: false, force: true }); + } + } + if (!apply) return checkUpdate(); + return applyUpdate(planUpdates(), { ref: currentChannelRef(), channel: next, pin: false, force: true }); +} + +export async function switchVersion(ref) { + const target = String(ref || "").trim(); + if (!target) throw new Error("请选择要回退的版本"); + const listed = await listRemoteVersions(); + const hit = listed.versions.find((item) => item.ref === target || item.id === target || item.version === target || item.sha === target); + const resolved = hit?.ref || target; + const channel = hit?.channel || readChannelState().channel; + const pin = hit?.latest ? "" : resolved; + return applyUpdate(planUpdates(), { ref: resolved, channel, pin, force: true }); +} + +export async function handleUpdateOp(body = {}) { + const op = String(body.op || (body.auto ? "auto" : "apply")).toLowerCase(); + if (op === "check" || op === "status" || op === "versions") return checkUpdate(); + if (op === "channel") return switchChannel(body.channel, { apply: body.apply !== false }); + if (op === "switch" || op === "rollback") return switchVersion(body.ref || body.version || body.id); + if (op === "auto") return autoUpdateIfNeeded(); + return applyUpdate(planUpdates(), { ref: body.ref || currentChannelRef(), pin: false, force: true }); +} + export async function autoUpdateIfNeeded() { try { const check = await checkUpdate(); + if (check.pinned) return rememberUpdate({ ...check, auto: true, skipped: "pinned" }); if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" }); const jobs = planUpdates(); const dirtyGit = jobs.filter((j) => j.kind === "git" && gitTrackedDirty(j.dir)); @@ -545,7 +834,7 @@ export async function autoUpdateIfNeeded() { error: "本地插件文件有未提交改动,未自动覆盖", }); } - const applied = await applyUpdate(runnable); + const applied = await applyUpdate(runnable, { ref: currentChannelRef(), pin: false, force: false }); return rememberUpdate({ ...applied, auto: true }); } catch (e) { return rememberUpdate({ @@ -553,6 +842,7 @@ export async function autoUpdateIfNeeded() { auto: true, hasUpdate: false, error: String(e && e.message ? e.message : e), + ...channelPublic(), }); } } diff --git a/package.json b/package.json index 5743b76..f1b3435 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.10", + "version": "1.1.11-beta.1", "description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐", "type": "module", "main": "lib/index.js",