Compare commits

...
12 Commits
Author SHA1 Message Date
叫我小杨同学andCursor 4f1470d6e5 feat: 发布 1.1.13
插件重装改用 GitHub tar.gz,没装 git 时不再走 git ls-remote。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 00:39:06 +08:00
叫我小杨同学andCursor b3a23dba75 fix: 插件重装改用 tar.gz,避免没装 git 时解析失败 (#30)
pnpm 解析 github: 和 git+https 会执行 git ls-remote。插件自己的更新改为 GitHub archive 包,不依赖本机 git。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 00:08:22 +08:00
叫我小杨同学andCursor d3b3bc3551 feat: 发布 1.1.12,测试版 Skill 进入正式版
正式版带上 Skill 导入,并保留不再钉上一轮全文、按提交号标当前和拒绝跨站请求。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 11:21:04 +08:00
叫我小杨同学andCursor 3b4ac0c157 feat: 测试版标出 Skill 官方调用方式(/名称与模型 skill 工具)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-21 13:30:58 +08:00
叫我小杨同学andCursor 9374ca92d4 docs: 补上非营利学习研究免责声明,去掉已下线的 1.1.11-beta 记录
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-21 12:39:48 +08:00
叫我小杨同学andCursor 4dda34588f fix: 测试版同步系统提示词只注入一次,并写清 1.1.11 变更
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-21 10:35:26 +08:00
叫我小杨同学andCursor 1caeb92f53 fix: 切换立即标当前,覆盖后刷新设置页不再强制重启
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 17:01:37 +08:00
叫我小杨同学andCursor 09c0afe611 fix: 检测更新才出现更新,点更新不再写成切换版本
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:58:41 +08:00
叫我小杨同学andCursor 8de3fdf2d8 fix: 本机只标当前,下线 1.1.11-beta,Skill 仅 1.1.12 测试版
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:55:09 +08:00
叫我小杨同学andCursor 6639031e29 feat: 发布 1.1.12-beta.1,测试版恢复 Skill 导入
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:46:55 +08:00
叫我小杨同学andCursor 2287ac4be7 feat: 发布 1.1.11-beta.2,正式/测试分栏并能切回去
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:43:26 +08:00
叫我小杨同学andCursor 24a3ff1b99 feat: 发布 1.1.11-beta.1,Skill 导入官方目录并加正式/测试通道
设置页可导入压缩包或文件夹到官方 skills;导入约束路径与符号链接,保存保留官方 frontmatter。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:02:53 +08:00
10 changed files with 1418 additions and 116 deletions

No files matched your search

+4
View File
@@ -1,3 +1,7 @@
# 外部参考仓库,禁止提交
choirboy-prompt/
/choirboy-prompt/
node_modules/
*.tgz
npm-debug.log*
+27 -9
View File
@@ -4,7 +4,7 @@
<h1 align="center">⚔️ DeepSeek Harness cybersecurity red-team tool (dsh-purge)</h1>
<p align="center"><strong>Version 1.1.11</strong></p>
<p align="center"><strong>Version 1.1.13</strong></p>
<p align="center">
<em>Local official DeepSeek Harness cybersecurity red-team plugin: evaluate and harden host safety policy in a controlled local install; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐</em>
@@ -246,13 +246,13 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv
<p align="center">
<a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 Open Hub page</strong></a>
&nbsp;·&nbsp;
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.11&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz"><strong>🚀 Install in desktop client</strong></a>
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.13&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz"><strong>🚀 Install in desktop client</strong></a>
</p>
🔗 **Raw protocol URL:**
```
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.11&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.13&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz
```
**Web trigger example:**
@@ -265,7 +265,7 @@ export function installDshPurgeToDesktop() {
const params = new URLSearchParams({
id: 'dsh-purge',
name: 'dsh-purge',
version: '1.1.11',
version: '1.1.13',
repo: 'YuJunZhiXue/dsh-purge',
permissions: '系统提示词注入, 本机补丁, 设置页',
downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz',
@@ -284,7 +284,7 @@ export function installDshPurgeToDesktop() {
**HTML link:**
```html
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.11&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.13&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz">
🚀 Install in desktop client
</a>
```
@@ -295,7 +295,7 @@ export function installDshPurgeToDesktop() {
|---|---|---|
| id | `dsh-purge` | Plugin id |
| name | `dsh-purge` | Display name |
| version | `1.1.11` | Semver |
| version | `1.1.13` | Semver |
| repo | `YuJunZhiXue/dsh-purge` | GitHub repo |
| permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions |
| downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub source archive |
@@ -588,6 +588,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/<id>/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 |
---
@@ -612,6 +613,7 @@ dsh-purge/
│ ├── restart-web.js
│ ├── rewind.js
│ ├── rules.js
│ ├── skills.js
│ ├── uninstall-restart.js
│ ├── uninstall.js
│ └── update.js
@@ -622,7 +624,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.
---
@@ -648,12 +650,13 @@ dsh-purge --edit
/purge status | apply | revert | uninstall | edit | help
/rules list | use <id> | create <id> | delete <id> | reset | help
/skills list | import <zip-or-folder> | create <id> [description] | delete <id> | help
/rewind
purge_status purge_apply purge_revert
```
Patched packages load only after a restart. Apply does not restart by itself. Under the patch title, **Stable** and **Beta** sit in two columns, each with its own version list.
Patched packages load only after a restart. Apply does not restart by itself. Under the patch title, **Stable** and **Beta** are separate: each has its own version list and switch action. A rollback is pinned; click **Update** to return to that channel's 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.
@@ -669,6 +672,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
```
@@ -697,6 +701,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/<id>/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`.
@@ -747,10 +753,20 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change
## Changelog
### 1.1.13
- In-plugin updates rewrite `github:` and `git+https` to the GitHub `master.tar.gz` archive, so a reinstall does not need a local git (#30).
- A first install from the plugin hub still uses `git+https`. Without git, use the `master.tar.gz` URL above.
### 1.1.12
- **Beta is now the stable release.** Settings and `/skills` import a zip or folder into official `$DSH_HOME/skills`. DSH still owns match and load.
- Includes the 1.1.11 system-prompt fix: do not pin the previous full prompt (#29). The version list marks「当前」by commit. Local routes reject cross-origin requests. Patch #41 no longer keeps `dsh-purge:committed`.
### 1.1.11
- Settings splits Stable / Beta into two columns, each with its own list, switch, and rollback. 1.1.10 can reach this by Check update.
- **No Skill import.** Skill stays on beta 1.1.12.
- **No Skill import in this release.** Skill joins stable in 1.1.12.
- **#29:** Stop pinning the previous full system prompt. That pin was meant to stop a new「系统提示词」card each step, but presets that append a section every assemble (梁神 `workspace-instructions`) turned it into “last full prompt + this step’s block”, so the prompt grew every step and prefix cache missed. Later turns only fold `prompt-inject` into persona, and do not fold a second copy when it is already there.
- The version list marks「当前」by commit. An older tag with the same 1.1.11 version is no longer current next to `master`.
- Local routes reject cross-origin requests, and updates only accept a known ref. Another webpage cannot apply, revert, uninstall, or switch.
@@ -760,6 +776,8 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change
- 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
+27 -9
View File
@@ -4,7 +4,7 @@
<h1 align="center">⚔️ DeepSeek Harness 网络安全红队工具(dsh-purge)</h1>
<p align="center"><strong>Version 1.1.11</strong></p>
<p align="center"><strong>Version 1.1.13</strong></p>
<p align="center">
<em>本机官方 DeepSeek Harness 网络安全红队评测插件:在受控本机环境评测并加固宿主安全策略,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐</em>
@@ -243,13 +243,13 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv
<p align="center">
<a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 打开插件市场页</strong></a>
&nbsp;·&nbsp;
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.11&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz"><strong>🚀 唤起客户端一键安装</strong></a>
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.13&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz"><strong>🚀 唤起客户端一键安装</strong></a>
</p>
🔗 **原生协议链接:**
```
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.11&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.13&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz
```
**网页端(前端)触发代码示例:**
@@ -262,7 +262,7 @@ export function installDshPurgeToDesktop() {
const params = new URLSearchParams({
id: 'dsh-purge',
name: 'dsh-purge',
version: '1.1.10',
version: '1.1.13',
repo: 'YuJunZhiXue/dsh-purge',
permissions: '系统提示词注入, 本机补丁, 设置页',
downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz',
@@ -281,7 +281,7 @@ export function installDshPurgeToDesktop() {
**HTML 静态链接方式:**
```html
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.11&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.13&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz">
🚀 唤起客户端一键安装
</a>
```
@@ -292,7 +292,7 @@ export function installDshPurgeToDesktop() {
|---|---|---|
| id | `dsh-purge` | 插件唯一标识符 |
| name | `dsh-purge` | 插件展示名称 |
| version | `1.1.11` | 语义化版本号 |
| version | `1.1.13` | 语义化版本号 |
| repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 |
| permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 |
| downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub 源码包地址 |
@@ -585,6 +585,7 @@ dsh-purge --uninstall
| 补丁 | 分组查看状态,应用、还原或卸载 |
| 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 |
| 规则集 | 多套 `AGENTS.md` / `CLAUDE.md`;启用写入 `$DSH_HOME`,删除从列表去掉 |
| Skill | 导入压缩包或文件夹到当前宿主官方目录 `$DSH_HOME/skills/<id>/SKILL.md`(Web / 桌面各用自己的主目录,不写死盘符);命中、加载、`/名称` 由 DSH 负责。也可自己删该文件夹 |
---
@@ -609,6 +610,7 @@ dsh-purge/
│ ├── restart-web.js
│ ├── rewind.js
│ ├── rules.js
│ ├── skills.js
│ ├── uninstall-restart.js
│ ├── uninstall.js
│ └── update.js
@@ -619,7 +621,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` 注入段,也不顶替提示词。
---
@@ -647,13 +649,14 @@ dsh-purge --edit
# 聊天
/purge status | apply | revert | uninstall | edit | help
/rules list | use <id> | create <id> | delete <id> | reset | help
/skills list | import <压缩包或文件夹> | create <id> [说明] | delete <id> | help
/rewind
# 模型工具
purge_status purge_apply purge_revert
```
设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。补丁标题下正式版和测试版左右分栏,各自选版本、各自切换。
设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。补丁标题下正式版和测试版分开两栏:各自看版本、各自切换;回退后会固定在该版本,要回到该通道最新再点「更新」。
输入框旁的「回退」会丢掉最近一轮对话,并把上一句填回输入框;聊天里 `/rewind` 同样可用。
@@ -665,6 +668,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
```
@@ -693,6 +697,8 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt
└─> 不写入覆盖段
```
**Skill(官方目录,不注入):** 设置页导入压缩包/文件夹,或 `/skills import`,只把内容写到官方 `$DSH_HOME/skills/<id>/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`。
@@ -734,10 +740,20 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt
## 更新记录
### 1.1.13
- 插件自己更新时,`github:` 和 `git+https` 改走 GitHub `master.tar.gz`,没装 git 也能重装(#30)。
- 第一次从插件市场安装仍会走 `git+https`。没装 git 时,直接用上面的 `master.tar.gz` 地址。
### 1.1.12
- **测试版转为正式版。** 设置页和 `/skills` 可把压缩包或文件夹导入官方 `$DSH_HOME/skills`。命中和加载仍由 DSH 负责。
- 带上 1.1.11 的系统提示修复:不再钉上一轮全文(#29)。版本列表按提交号标「当前」。本机接口拒绝跨站请求。补丁 #41 不再保留 `dsh-purge:committed`。
### 1.1.11
- 设置页把正式版和测试版左右分开,各自选版本、各自切换和回退。还在 1.1.10 的点「检测更新」就能升到这一版。
- **没有 Skill 导入。** Skill 只在测试版 1.1.12。
- **当时没有 Skill 导入。** Skill 从 1.1.12 起进入正式版。
- **#29:** 去掉「钉住上一条系统提示全文」。起初为了避免每步追加「系统提示词」,把上一轮全文钉回去;和每轮追加 section 的预设(梁神的 `workspace-instructions`)叠在一起后,系统提示每步变长,前缀缓存整段失效。现在每轮只把 `prompt-inject` 折进 persona,已经折过就不再折第二份。
- 版本列表按提交号标「当前」。同为 1.1.11 的旧标签不再和 `master` 一起显示当前。
- 本机接口拒绝跨站请求,更新只接受已知版本。任意网页不能再调用应用、还原、卸载或切换。
@@ -747,6 +763,8 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt
- 提示词和规则集都空时不能保存或应用,弹窗要求先添加提示词
- 第一轮完整注入;不再钉上一轮整篇系统提示,避免来回追加
- 设置页 / `/skills` 可把压缩包或文件夹导入官方 `$DSH_HOME/skills`;命中与加载仍由 DSH 负责
- 设置页可切换正式版 / 测试版,并从历史版本回退;回退后会固定,不再自动跟上
### 1.1.9
+481 -76
View File
@@ -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": "已填入默认提示词,点保存写入",
@@ -168,17 +185,17 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"channel.beta": "测试版",
"channel.useStable": "切换到正式版",
"channel.useBeta": "切换到测试版",
"channel.now": "当前通道",
"channel.other": "可切换",
"channel.local": "本机",
"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.done": "已更新到 {version}",
"update.switched": "已切换到 {version}",
"update.autoDone": "已自动更新到 {version}",
"update.reloading": "正在刷新设置页…",
"update.dirty": "有新版本,本地有改动未自动覆盖",
"update.fail": "更新失败: {error}",
"update.timeout": "检测超时,请再点一次检测更新",
@@ -220,6 +237,28 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"need.id": "需要 id",
"ph.content": "",
"btn.saveRule": "保存",
"skills.title": "Skill",
"skills.hint": "导入到官方目录后,由 DSH 调用:聊天输入 /名称 立即加载;任务对上 description 或 whenToUse 时模型会调 skill 工具。正文写「激活」不会触发。",
"skills.hint.desktop": "当前桌面宿主的官方 Skill 目录。聊天输入 /名称 立即加载;任务对上 description 时模型会调 skill 工具。",
"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": "官方会忽略:格式不对",
"skills.call.slash": "聊天输入 {cmd}",
"skills.call.model": "模型可调",
"skills.call.modelOff": "模型不可调",
"skills.call.userOff": "不可 /名称",
"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": "重启中…",
@@ -327,7 +366,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.",
@@ -356,17 +395,17 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"channel.beta": "Beta",
"channel.useStable": "Switch to stable",
"channel.useBeta": "Switch to beta",
"channel.now": "Current channel",
"channel.other": "Available",
"channel.local": "This copy",
"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.done": "Updated to {version}.",
"update.switched": "Switched to {version}.",
"update.autoDone": "Auto-updated to {version}.",
"update.reloading": "Refreshing settings…",
"update.dirty": "Update available; local edits were not overwritten.",
"update.fail": "Update failed: {error}",
"update.timeout": "Check timed out. Click Check update again.",
@@ -408,6 +447,28 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"need.id": "id required",
"ph.content": "",
"btn.saveRule": "Save",
"skills.title": "Skills",
"skills.hint": "After import, DSH calls it: type /name in chat to load now; the model calls the skill tool when the task matches description or whenToUse. Writing「激活」in the body does nothing.",
"skills.hint.desktop": "This desktop host’s official skill catalog. Type /name in chat to load; the model calls the skill tool when the task matches the description.",
"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",
"skills.call.slash": "Type {cmd} in chat",
"skills.call.model": "Model can load",
"skills.call.modelOff": "Hidden from model",
"skills.call.userOff": "/name disabled",
"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…",
@@ -555,23 +616,20 @@ 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{width:100%;min-width:0;max-width:none;height:34px;padding:0 10px;font-size:12px}
.dshp-lanes{display:grid;grid-template-columns:1fr 1fr;gap:1px;margin:0 0 16px;background:var(--dshp-line);border:1px solid var(--dshp-line);border-radius:8px;overflow:hidden}
.dshp-lane{display:flex;flex-direction:column;gap:0;min-width:0;padding:14px 14px 12px;background:var(--dshp-paper);transition:background .2s var(--dshp-ease)}
.dshp-lane.is-on{background:var(--dshp-bg)}
.dshp-lane-kicker{margin:0 0 4px;font-family:var(--dshp-mono);font-size:10px;letter-spacing:.16em;text-transform:uppercase;color:var(--dshp-mute)}
.dshp-lane.is-on .dshp-lane-kicker{color:var(--dshp-accent)}
.dshp-lane.is-beta .dshp-lane-kicker{color:var(--dshp-warn)}
.dshp-lane.is-on.is-beta .dshp-lane-kicker{color:var(--dshp-warn)}
.dshp-lane-h{display:flex;align-items:baseline;gap:10px;margin:0 0 12px;padding-bottom:10px;border-bottom:1px solid var(--dshp-line)}
.dshp-lane-h strong{font-family:var(--dshp-display);font-size:18px;font-weight:500;letter-spacing:.02em}
.dshp-lane-ver{margin-left:auto;font-family:var(--dshp-mono);font-size:12px;color:var(--dshp-mute);white-space:nowrap}
.dshp-lane-ops{display:flex;flex-direction:column;gap:8px}
.dshp-lane-ops .dshp-btn{width:100%}
.dshp-ver{width:100%;min-width:0;max-width:none;height:32px;padding:0 10px;font-size:12px}
.dshp-rel{margin:0 0 14px}
.dshp-now{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin:0 0 4px}
.dshp-now-label{font-family:var(--dshp-mono);font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:var(--dshp-mute)}
.dshp-now-ver{font-family:var(--dshp-display);font-size:20px;font-weight:500;letter-spacing:.01em}
.dshp-now-mark{display:inline-flex;align-items:center;margin-left:6px;padding:1px 7px;border-radius:99px;font-family:var(--dshp-mono);font-size:11px;font-style:normal;font-weight:500;line-height:1.5;color:var(--dshp-ok);border:1px solid color-mix(in srgb,var(--dshp-ok) 38%,var(--dshp-line));background:color-mix(in srgb,var(--dshp-ok) 14%,var(--dshp-bg))}
.dshp-editions{display:flex;flex-direction:column;margin:10px 0 0;border-top:1px solid var(--dshp-line)}
.dshp-edition{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:10px;padding:10px 0;border-bottom:1px solid var(--dshp-line)}
.dshp-edition-name{display:inline-flex;align-items:center;gap:0;font-family:var(--dshp-display);font-size:15px;font-weight:500;white-space:nowrap}
.dshp-edition.is-on .dshp-edition-name{color:var(--dshp-ink)}
.dshp-edition:not(.is-on) .dshp-edition-name{color:var(--dshp-mute)}
.dshp-edition .dshp-btn{min-width:118px}
.dshp-rel .dshp-notice{display:block;margin-top:8px;min-height:16px}
@media (max-width:640px){.dshp-lanes{grid-template-columns:1fr}}
@media (prefers-reduced-motion:reduce){.dshp-lane{transition:none}}
@media (max-width:560px){.dshp-edition{grid-template-columns:1fr auto;grid-template-areas:"name btn" "sel sel"}.dshp-edition-name{grid-area:name}.dshp-edition .dshp-ver{grid-area:sel}.dshp-edition .dshp-btn{grid-area:btn}}
.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}
@@ -807,6 +865,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const [overrideLoaded, setOverrideLoaded] = useState(false);
const [patchBusy, setPatchBusy] = useState(false);
const [updateBusy, setUpdateBusy] = useState(false);
const [canApplyUpdate, setCanApplyUpdate] = useState(false);
const [updateJob, setUpdateJob] = useState(null);
const [askRestart, setAskRestart] = useState(false);
const [askUninstall, setAskUninstall] = useState(false);
const [uninstallBusy, setUninstallBusy] = useState(false);
@@ -821,7 +881,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const versions = (d && d.versions) || [];
const next = { stable: "", beta: "" };
for (const id of ["stable", "beta"]) {
const list = versions.filter((item) => item.channel === id);
const list = versions.filter((item) => item.channel === id && keepListedVersion(item));
const cur = list.find((item) => item.current);
const latest = list.find((item) => item.latest);
next[id] = (cur || latest || {}).ref || "";
@@ -838,34 +898,44 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const applyUpdateInfo = useCallback((d, tr, kind) => {
if (d.channel) setChannel(d.channel);
setUpdateInfo(d);
syncPicks(d);
setUpdateInfo((prev) => {
const versions = (d.versions && d.versions.length) ? d.versions : ((prev && prev.versions) || []);
return Object.assign({}, prev || {}, d, { versions });
});
if (d.versions && d.versions.length) syncPicks(d);
if (kind === "check") setCanApplyUpdate(Boolean(d.hasUpdate) && !d.error);
else if (kind === "done" || kind === "switched" || kind === "channel") setCanApplyUpdate(false);
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 || "—" });
if (kind === "switched" || kind === "channel") text = tr("update.switched", { version: d.localVersion || d.remoteVersion || "—" });
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 });
}, []);
const checkUpdate = useCallback(() => {
const checkUpdate = useCallback((id) => {
setUpdateBusy(true);
setUpdateJob({ id: id || "", kind: "check" });
const tr = tRef.current;
setUpdateNotice({ kind: "ok", text: tr("update.checking") });
apiJson("/dsh-purge/update")
.then((d) => {
if (!d || (!d.ok && !d.channel)) throw new Error((d && d.error) || "check failed");
applyUpdateInfo(d, tr);
applyUpdateInfo(d, tr, "check");
})
.catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) }))
.finally(() => setUpdateBusy(false));
.finally(() => {
setUpdateBusy(false);
setUpdateJob(null);
});
}, [applyUpdateInfo]);
const postUpdate = useCallback((body, kind) => {
const postUpdate = useCallback((body, kind, id) => {
setUpdateBusy(true);
setUpdateJob({ id: id || "", kind });
const tr = tRef.current;
setUpdateNotice({ kind: "ok", text: kind === "switched" || kind === "channel" ? tr("update.switching") : tr("update.applying") });
return apiJson("/dsh-purge/update", {
@@ -875,28 +945,45 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
})
.then((d) => {
if (!d || (d.ok === false && d.error)) throw new Error((d && d.error) || "update failed");
applyUpdateInfo(d, tr, kind === "channel" ? "switched" : kind);
if (d.applied || d.needRestart) setAskRestart(true);
applyUpdateInfo(d, tr, kind);
if (d.applied && d.reloadClient !== false) {
setUpdateNotice({ kind: "ok", text: tr("update.reloading") });
setTimeout(() => {
try { window.location.reload(); } catch { /* ignore */ }
}, 280);
} else if (d.needRestart) {
setAskRestart(true);
}
return d;
})
.catch((e) => {
setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) });
throw e;
})
.finally(() => setUpdateBusy(false));
.finally(() => {
setUpdateBusy(false);
setUpdateJob(null);
});
}, [applyUpdateInfo]);
const doUpdate = useCallback((id) => {
const lane = id === "beta" ? "beta" : "stable";
postUpdate({ op: "apply", ref: lane === "beta" ? "beta" : "master", channel: lane }, "done").catch(() => {});
postUpdate({ op: "apply", ref: lane === "beta" ? "beta" : "master", channel: lane }, "done", id).catch(() => {});
}, [postUpdate]);
const changeChannel = useCallback((next) => {
if (!next) return;
const tr = tRef.current;
if (!window.confirm(tr("update.confirmChannel", { version: tr("channel." + next) }))) return;
postUpdate({ op: "channel", channel: next }, "channel").catch(() => {});
}, [postUpdate]);
const prevChannel = channel;
const prevInfo = updateInfo;
setChannel(next);
setUpdateInfo((cur) => Object.assign({}, cur || {}, { channel: next }));
postUpdate({ op: "channel", channel: next }, "channel", next).catch(() => {
setChannel(prevChannel);
setUpdateInfo(prevInfo);
});
}, [channel, postUpdate, updateInfo]);
const switchSelected = useCallback((id) => {
const tr = tRef.current;
@@ -906,8 +993,17 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const label = (hit && (hit.label || hit.version)) || ref;
if (!ref) return;
if (!window.confirm(tr("update.confirmSwitch", { version: label }))) return;
postUpdate({ op: "switch", ref }, "switched").catch(() => {});
}, [pick, postUpdate, updateInfo]);
const prevChannel = channel;
const prevInfo = updateInfo;
if (hit && hit.channel) {
setChannel(hit.channel);
setUpdateInfo((cur) => Object.assign({}, cur || {}, { channel: hit.channel }));
}
postUpdate({ op: "switch", ref }, "switched", id).catch(() => {
setChannel(prevChannel);
setUpdateInfo(prevInfo);
});
}, [channel, pick, postUpdate, updateInfo]);
const loadAll = useCallback(() => {
const tr = tRef.current;
@@ -1152,17 +1248,19 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const hostSurface = hostSurfaceOf(s);
const versions = (updateInfo && updateInfo.versions) || [];
const channelNow = (updateInfo && updateInfo.channel) || channel || "stable";
const renderLane = (id) => {
const localVer = (s && s.plugin_version) || (updateInfo && updateInfo.localVersion) || "";
const renderEdition = (id) => {
const lane = (updateInfo && updateInfo.lanes && updateInfo.lanes[id]) || {};
const list = versions.filter((item) => item.channel === id);
const list = versions.filter((item) => item.channel === id && keepListedVersion(item));
const selectedRef = pick[id] || "";
const hit = list.find((item) => item.ref === selectedRef) || list.find((item) => item.current) || list.find((item) => item.latest);
const onLane = channelNow === id;
const noBeta = id === "beta" && updateInfo && updateInfo.hasBeta === false && !list.length;
const pickedOther = Boolean(hit && selectedRef && !hit.current);
const thisJob = updateJob && updateJob.id === id ? updateJob : null;
let actionLabel = t("btn.checkUpdate");
let actionKind;
let actionClick = checkUpdate;
let actionClick = () => checkUpdate(id);
let actionDisabled = updateBusy || Boolean(noBeta);
if (noBeta) {
actionLabel = t("update.noBeta");
@@ -1175,43 +1273,39 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
actionLabel = id === "beta" ? t("channel.useBeta") : t("channel.useStable");
actionKind = "primary";
actionClick = () => changeChannel(id);
} else if (lane.hasUpdate) {
} else if (canApplyUpdate && lane.hasUpdate) {
actionLabel = t("btn.doUpdate");
actionKind = "primary";
actionClick = () => doUpdate(id);
}
if (updateBusy) {
if (pickedOther || !onLane) actionLabel = t("update.switching");
else if (lane.hasUpdate && onLane) actionLabel = t("btn.doUpdate.busy");
else actionLabel = t("btn.checkUpdate.busy");
if (thisJob) {
if (thisJob.kind === "check") actionLabel = t("btn.checkUpdate.busy");
else if (thisJob.kind === "done") actionLabel = t("btn.doUpdate.busy");
else actionLabel = t("update.switching");
}
const verText = lane.version ? "v" + lane.version : (hit && hit.version ? "v" + hit.version : "—");
return h("div", {
className: "dshp-lane" + (onLane ? " is-on" : "") + (id === "beta" ? " is-beta" : ""),
className: "dshp-edition" + (onLane ? " is-on" : ""),
"aria-label": t("channel." + id),
},
h("p", { className: "dshp-lane-kicker" }, onLane ? t("channel.now") : t("channel.other")),
h("div", { className: "dshp-lane-h" },
h("strong", null, t("channel." + id)),
h("span", { className: "dshp-lane-ver" }, verText),
h("span", { className: "dshp-edition-name" },
t("channel." + id),
onLane ? h("em", { className: "dshp-now-mark" }, t("update.current")) : null,
),
h("div", { className: "dshp-lane-ops" },
h("select", {
className: "dshp-field dshp-ver",
value: selectedRef || (hit && hit.ref) || "",
disabled: updateBusy || !list.length,
onChange: (e) => setPick((prev) => Object.assign({}, prev, { [id]: e.target.value })),
"aria-label": t("update.pick"),
},
list.length
? list.map((item) => h("option", {
key: item.ref + (item.sha || ""),
value: item.ref,
}, (item.version ? "v" + item.version : item.label) + (item.current ? " · " + t("update.current") : item.latest ? " · " + t("update.tip") : "")))
: h("option", { value: "" }, noBeta ? t("update.noBeta") : t("update.pick")),
),
h(Btn, { kind: actionKind, disabled: actionDisabled, onClick: actionClick }, actionLabel),
h("select", {
className: "dshp-field dshp-ver",
value: selectedRef || (hit && hit.ref) || "",
disabled: updateBusy || !list.length,
onChange: (e) => setPick((prev) => Object.assign({}, prev, { [id]: e.target.value })),
"aria-label": t("update.pick"),
},
list.length
? list.map((item) => h("option", {
key: item.ref + (item.sha || ""),
value: item.ref,
}, (item.version ? "v" + item.version : item.label) + (item.latest && !item.current ? " · " + t("update.tip") : "")))
: h("option", { value: "" }, noBeta ? t("update.noBeta") : t("update.pick")),
),
h(Btn, { tiny: true, kind: actionKind, disabled: actionDisabled, onClick: actionClick }, actionLabel),
);
};
return h("section", { className: "dshp-panel", "aria-label": t("purge.title") },
@@ -1220,9 +1314,14 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
h("span", { className: "dshp-pill" }, t("surface." + hostSurface)),
),
h("div", { className: "dshp-rel" },
h("div", { className: "dshp-lanes" },
renderLane("stable"),
renderLane("beta"),
h("div", { className: "dshp-now" },
h("span", { className: "dshp-now-label" }, t("channel.local")),
h("b", { className: "dshp-now-ver" }, localVer ? "v" + localVer : "—"),
h("em", { className: "dshp-now-mark" }, t("update.current")),
),
h("div", { className: "dshp-editions" },
renderEdition("stable"),
renderEdition("beta"),
),
noticeNode(updateNotice),
),
@@ -1520,6 +1619,311 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
);
}
function skillUiAllowed(d) {
if (!d) return false;
const ver = String(d.plugin_version || d.localVersion || "").replace(/^v/i, "");
if (/^1\.1\.11(?:-|$)/.test(ver)) return false;
const parts = ver.match(/^(\d+)\.(\d+)\.(\d+)/);
if (!parts) return false;
if (+parts[1] !== 1) return +parts[1] > 1;
if (+parts[2] !== 1) return +parts[2] > 1;
return +parts[3] >= 12;
}
function keepListedVersion(item) {
return !/^1\.1\.11-beta/i.test(String((item && item.version) || "").replace(/^v/i, ""));
}
function SkillsSection() {
const t = useT();
const tRef = useRef(t);
tRef.current = t;
const [onBeta, setOnBeta] = useState(false);
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" });
};
apiJson("/dsh-purge/status")
.then((d) => {
const allowed = skillUiAllowed(d);
setOnBeta(allowed);
if (!allowed) {
setSt(null);
return;
}
if (d.skills) {
apply({ ok: true, skills: d.skills });
return;
}
skillsApi("status").then(apply).catch(fail);
})
.catch(() => {
setOnBeta(false);
setSt(null);
});
}, []);
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));
};
if (!onBeta) return null;
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),
),
item.valid ? h("span", { className: "dshp-rule-meta" },
[
item.userInvocable ? t("skills.call.slash", { cmd: "/" + item.id }) : t("skills.call.userOff"),
item.modelInvocable ? t("skills.call.model") : t("skills.call.modelOff"),
].join(" · "),
) : null,
),
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");
@@ -1661,6 +2065,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
),
h(PurgifySection, null),
h(RulesSection, null),
h(SkillsSection, null),
);
}
+43 -4
View File
@@ -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);
+207 -3
View File
@@ -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,
@@ -398,7 +399,8 @@ async function handlePurgeCommand(rawInput, config) {
" /purge uninstall 卸载插件(已应用则先还原)\n" +
" /purge edit 编辑注入文件 prompt-inject.md\n" +
" /purge help 显示帮助\n" +
"规则集切换见 /rules(list | use <id> | create | delete | reset)",
"规则集切换见 /rules(list | use <id> | create | delete | reset)\n" +
"官方 Skill 安装见 /skills(list | import <路径> | create <id> [说明] | delete <id>)",
};
}
}
@@ -512,6 +514,106 @@ async function handleRulesCommand(rawInput) {
}
}
function renderSkillsStatus(st) {
const out = [];
out.push("官方用户 Skill / $DSH_HOME/skills");
out.push(` ${st.skills_dir}`);
out.push(" 插件只安装目录。调用走官方:任务对上 description/whenToUse 时模型调 skill 工具;聊天输入 /名称 立即加载。");
out.push(" 正文里写「激活」不会触发。官方认 name、description、whenToUse、disable-model-invocation、user-invocable。");
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 || "(无说明)";
const how = item.valid
? [
item.userInvocable ? `/${item.id}` : "不可 /名称",
item.modelInvocable ? "模型可调" : "模型不可调",
].join(" · ")
: "";
out.push(` ${mark} ${item.id} ${desc} (${skills.formatSize(item.size)})`);
if (how) out.push(` ${how}`);
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 <id> [说明]" };
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 <id>" };
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 <id> [说明] 写入 <id>/SKILL.md\n" +
" /skills import <路径> 导入压缩包或文件夹到官方目录\n" +
" /skills delete <id> 删除该目录(官方会从目录拿掉)\n" +
" 也可自己删 $DSH_HOME/skills/<id>\n" +
" 调用:聊天输入 /<id>,或让模型按 description 调 skill 工具\n" +
" 不注入 systemPrompt,不替代提示词",
};
}
}
export function apply(ctx, config) {
const cfg = { ...DEFAULTS, ...(config || {}) };
if (!cfg.enabled) return;
@@ -573,6 +675,12 @@ export function apply(ctx, config) {
input: { hint: "list | use <id> | create <id> [别名] [目标] | delete <id> | reset | help" },
handler: async (invocation) => handleRulesCommand(invocation.rawInput ?? ""),
});
commands.register({
name: "skills",
description: "官方用户 Skill($DSH_HOME/skills):list | import <路径> | create <id> [说明] | delete <id> | help",
input: { hint: "list | import <路径> | create <id> [说明] | delete <id> | help" },
handler: async (invocation) => handleSkillsCommand(invocation.rawInput ?? ""),
});
commands.register({
name: "rewind",
description: "回退:子代理直接回退一次;主代理 /rewind once 或 /rewind round",
@@ -796,6 +904,7 @@ function installWebServer(ctx, cfg) {
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) });
@@ -1131,6 +1240,7 @@ function installWebServer(ctx, cfg) {
},
}, "dsh-purge: override");
installRulesHttp(host.webServer);
installSkillsHttp(host.webServer);
registerPluginRoute({
kind: "exact",
path: "/dsh-purge/restart",
@@ -1235,6 +1345,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, {
@@ -1290,13 +1493,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();
+592
View File
@@ -0,0 +1,592 @@
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;
}
function yamlBoolField(head, key) {
const re = new RegExp(`^${key}:\\s*(.*)$`, "m");
const match = String(head || "").match(re);
if (!match) return { present: false };
let value = match[1].trim();
if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1).trim();
}
const comment = value.indexOf(" #");
if (comment >= 0) value = value.slice(0, comment).trim();
const norm = value.toLowerCase();
if (["true", "yes", "on", "1"].includes(norm)) return { present: true, value: true };
if (["false", "no", "off", "0"].includes(norm)) return { present: true, value: false };
return { present: true, invalid: true };
}
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 必填(单行)" };
const disableModel = yamlBoolField(parts.head, "disable-model-invocation");
const userInvocable = yamlBoolField(parts.head, "user-invocable");
if (disableModel.invalid) return { ok: false, error: "disable-model-invocation 必须是布尔值(true/false)" };
if (userInvocable.invalid) return { ok: false, error: "user-invocable 必须是布尔值(true/false)" };
return {
ok: true,
name,
description,
whenToUse: yamlLineField(parts.head, "whenToUse"),
modelInvocable: disableModel.value !== true,
userInvocable: userInvocable.value !== false,
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 : "",
whenToUse: parsed.ok ? parsed.whenToUse : "",
modelInvocable: parsed.ok ? parsed.modelInvocable : false,
userInvocable: parsed.ok ? parsed.userInvocable : false,
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),
})),
};
}
+29 -13
View File
@@ -70,6 +70,11 @@ function isBetaName(name) {
return /(?:^|[-._])(beta|rc|pre|preview|test)(?:\d|$|[-._])/i.test(String(name || ""));
}
function withdrawnVersion(item) {
const text = [item?.version, item?.ref, item?.id].filter(Boolean).join(" ");
return /(?:^|[\sv])1\.1\.11-beta/i.test(String(text).replace(/^v/i, " "));
}
function splitVersion(raw) {
const text = String(raw || "").trim().replace(/^v/i, "");
const cut = text.split("-");
@@ -124,7 +129,8 @@ function currentChannelRef(state = readChannelState()) {
function readHistory() {
const raw = readJson(historyPath());
return Array.isArray(raw) ? raw : [];
const rows = Array.isArray(raw) ? raw : [];
return rows.filter((item) => item && !withdrawnVersion(item));
}
function pushHistory(entry) {
@@ -147,10 +153,6 @@ function archiveTarballUrl(ref) {
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();
@@ -307,8 +309,17 @@ export function runDshPlugin(profile, args) {
export function pluginAddSpec(spec, ref = currentChannelRef()) {
const s = String(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);
// github: / git+https 会让 pnpm 跑 git ls-remote。没装 git 时就是 #30。
// 公开仓库用 archive tar.gz,不依赖本机 git。
if (
/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) ||
/^https?:\/\//i.test(s) ||
/^git\+https?:\/\//i.test(s) ||
/^github:/i.test(s) ||
/github\.com\/.+\.git/i.test(s)
) {
return archiveTarballUrl(ref);
}
return "";
}
@@ -564,9 +575,11 @@ async function listRemoteVersions() {
latest: true,
});
}
for (const tag of tags) add(tag);
for (const tag of tags) {
if (!withdrawnVersion(tag)) add(tag);
}
for (const item of readHistory()) {
if (!item || !item.ref) continue;
if (!item || !item.ref || withdrawnVersion(item)) continue;
add({
...item,
label: item.label || versionLabel(item.version, item.channel, item.sha),
@@ -577,7 +590,7 @@ async function listRemoteVersions() {
const localVer = localVersion();
const localSha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp();
return {
versions: markCurrent(out, state, localVer, localSha),
versions: markCurrent(out.filter((item) => !withdrawnVersion(item)), state, localVer, localSha),
hasBeta: Boolean(betaSha || out.some((item) => item.channel === "beta" && item.kind === "tag")),
stableSha,
betaSha,
@@ -840,7 +853,7 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
await overlayFromZip(zipDirs, ref);
vias.add("zip");
}
const sha = (await remoteHeadSha(ref)) || (gitOk() ? gitHead(PLUGIN_ROOT) : "");
const sha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || (await remoteHeadSha(ref).catch(() => ""));
if (sha) writeStamp(sha);
const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia();
const pin = options.pin === false ? "" : (options.pin || state.pin || "");
@@ -866,7 +879,8 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
remoteVersion: localVer,
localSha: sha ? String(sha).slice(0, 7) : "",
remoteSha: sha ? String(sha).slice(0, 7) : "",
needRestart: true,
needRestart: false,
reloadClient: true,
via,
versions: listed.versions,
lanes: lanesOf(listed, saved, localVer, sha),
@@ -915,7 +929,9 @@ function listedUpdateRef(target, listed) {
}
export async function switchVersion(ref) {
const target = safeUpdateRef(ref);
const raw = String(ref || "").trim();
if (withdrawnVersion({ ref: raw, version: raw })) throw new Error("该版本已下线");
const target = safeUpdateRef(raw);
if (!target) throw new Error("请选择要回退的版本");
const listed = await listRemoteVersions();
const resolved = listedUpdateRef(target, listed);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-purge",
"version": "1.1.11",
"version": "1.1.13",
"description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐",
"type": "module",
"main": "lib/index.js",
+7 -1
View File
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
import { markCurrent, safeUpdateRef } from "../lib/update.js";
import { markCurrent, pluginAddSpec, safeUpdateRef } from "../lib/update.js";
assert.equal(safeUpdateRef("master"), "master");
assert.equal(safeUpdateRef("beta"), "beta");
@@ -11,6 +11,12 @@ assert.equal(safeUpdateRef("origin/master"), "");
assert.equal(safeUpdateRef("../evil"), "");
assert.equal(safeUpdateRef("master;rm"), "");
const masterTar = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz";
assert.equal(pluginAddSpec("git+https://github.com/yujunzhixue/dsh-purge.git", "master"), masterTar);
assert.equal(pluginAddSpec("github:yujunzhixue/dsh-purge", "master"), masterTar);
assert.equal(pluginAddSpec("https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip", "master"), masterTar);
assert.equal(pluginAddSpec("dsh-purge", "master"), "");
const head = "9397203733562d6baeec9e38ac519698c619edcb";
const tag = "5e6be24acc3e5aac981c701cc34ef710ce48c4c7";
const versions = [