Compare commits

..
Author SHA1 Message Date
叫我小杨同学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
叫我小杨同学andCursor ed08f0c431 fix: 桌面可补共享预设,空提示词拦截统一走一处
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 11:32:16 +08:00
10 changed files with 2037 additions and 139 deletions

No files matched your search

+4
View File
@@ -1,3 +1,7 @@
# 外部参考仓库,禁止提交
choirboy-prompt/
/choirboy-prompt/
node_modules/
*.tgz
npm-debug.log*
+26 -3
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.10</strong></p>
<p align="center"><strong>Version 1.1.12-beta.1</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>
@@ -70,6 +70,8 @@ This is a **local official DeepSeek Harness cybersecurity red-team plugin**. It
<font color="red">
**Disclaimer:** This is a non-profit open-source project. It follows applicable laws and the rules of the platforms it uses, and is intended only for learning and research. Do not use it for any illegal or non-compliant purpose; the user bears any resulting consequences.
**Zero-tolerance statement:** This project opposes and forbids any illegal activity. The authors do not support, encourage, or assist unauthorized network attacks, exploit use, data theft, unlawful intrusion into computer information systems, or generation of illegal or prohibited content. **Anyone who uses this project for crime is solely responsible under the law. The authors have no liability.**
1. **This repository contains no illegal material.** The published code, docs, patches, and default prompt are **not** malware, backdoors, unauthorized pentest kits, ransomware, credential-stuffing scripts, or attack payloads aimed at the public internet or third-party systems. The project does not supply illegal content and does not incite, organize, or assist crime.
@@ -586,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 |
---
@@ -610,6 +613,7 @@ dsh-purge/
│ ├── restart-web.js
│ ├── rewind.js
│ ├── rules.js
│ ├── skills.js
│ ├── uninstall-restart.js
│ ├── uninstall.js
│ └── update.js
@@ -620,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.
---
@@ -646,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.
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.
@@ -667,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
```
@@ -695,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`.
@@ -745,10 +753,25 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change
## Changelog
### 1.1.12-beta.1
- Skill import stays on beta: Settings and `/skills` write zip/folder into official `$DSH_HOME/skills`
- Stable / Beta columns match official 1.1.11, so you can switch both ways
- Same system-prompt fix as official 1.1.11: inject once per conversation, do not append another「系统提示词」on later steps
### 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.
- **Inject the system prompt once per conversation.** The first turn writes the full `prompt-inject`; later steps pin that committed prompt and do not fold it again.
- **Stop a new「系统提示词」card on every step.** With 0.1.5 in-history, a changed assemble appends another `system/message`, so the transcript repeats system prompt → think → tools. Refolding inject every step made later official sections look like a new prompt; emptying inject did the same. After the inject is already in history, this release pins that committed system prompt and does not append a second copy.
### 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
+25 -3
View File
@@ -4,7 +4,7 @@
<h1 align="center">⚔️ DeepSeek Harness 网络安全红队工具(dsh-purge)</h1>
<p align="center"><strong>Version 1.1.10</strong></p>
<p align="center"><strong>Version 1.1.12-beta.1</strong></p>
<p align="center">
<em>本机官方 DeepSeek Harness 网络安全红队评测插件:在受控本机环境评测并加固宿主安全策略,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐</em>
@@ -67,6 +67,8 @@
<font color="red">
**免责声明:** 本项目为非营利开源项目,遵守国家法律法规及所在平台的相关规范,仅供学习与研究使用。不得将本项目用于任何违法违规用途;由此产生的后果由使用者自行承担。
**【零容忍严正申明】**:本项目坚决反对并严禁任何形式的违法犯罪行为!本项目开发者绝不支持、不鼓励、不协助任何未授权网络攻击、漏洞利用、数据窃取、非法侵入计算机信息系统或生成违法违禁内容的活动。**任何将本项目用于违法犯罪的行为,均与开发者无关,由行为人依法独立承担全部法律责任。**
1. **本仓库不含违法内容**:`dsh-purge` 发布的代码、文档、补丁与默认提示词**不是**木马、后门、未授权渗透工具、勒索软件、撞库脚本,也**不是**针对公网或第三方系统的攻击载荷。项目本身不提供违法内容,也不教唆、组织、协助实施违法犯罪。
@@ -583,6 +585,7 @@ dsh-purge --uninstall
| 补丁 | 分组查看状态,应用、还原或卸载 |
| 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 |
| 规则集 | 多套 `AGENTS.md` / `CLAUDE.md`;启用写入 `$DSH_HOME`,删除从列表去掉 |
| Skill | 导入压缩包或文件夹到当前宿主官方目录 `$DSH_HOME/skills/<id>/SKILL.md`(Web / 桌面各用自己的主目录,不写死盘符);命中、加载、`/名称` 由 DSH 负责。也可自己删该文件夹 |
---
@@ -607,6 +610,7 @@ dsh-purge/
│ ├── restart-web.js
│ ├── rewind.js
│ ├── rules.js
│ ├── skills.js
│ ├── uninstall-restart.js
│ ├── uninstall.js
│ └── update.js
@@ -617,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` 注入段,也不顶替提示词。
---
@@ -645,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` 同样可用。
@@ -663,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
```
@@ -691,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`。
@@ -732,10 +740,24 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt
## 更新记录
### 1.1.12-beta.1
- Skill 导入继续只在测试版:设置页和 `/skills` 可导入压缩包或文件夹到官方 `$DSH_HOME/skills`
- 正式/测试分栏与 1.1.11 正式版同一套,可来回切换
- 系统提示词修复与正式版 1.1.11 相同:每个会话只注入一次,后续步骤不再追加「系统提示词」
### 1.1.11
- 设置页把正式版和测试版左右分开,各自选版本、各自切换和回退。
- **系统提示词每个会话只注入一次。** 第一轮把 `prompt-inject` 完整写进系统提示;之后钉住已经提交的那一份,不再每步重折。
- **修了聊天里每步都冒出「系统提示词」。** 0.1.5 in-history 只要本步组装结果和上一条不一样,就会再追加一条 `system/message`,时间线就会「思考 → 工具 → 系统提示词」循环。以前每步都把注入重新折进 persona,官方后半段稍有变化就会追加;把注入掏空也不行,渲染少了同样会被当成变化再追加。这一版历史里已经有完整注入后,就钉住那条已提交的系统提示,后续步骤不再追加第二份。
### 1.1.10
- 提示词和规则集都空时不能保存或应用,弹窗要求先添加提示词
- 第一轮完整注入;不再钉上一轮整篇系统提示,避免来回追加
- 设置页 / `/skills` 可把压缩包或文件夹导入官方 `$DSH_HOME/skills`;命中与加载仍由 DSH 负责
- 设置页可切换正式版 / 测试版,并从历史版本回退;回退后会固定,不再自动跟上
### 1.1.9
+617 -51
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": "已填入默认提示词,点保存写入",
@@ -163,16 +180,33 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"btn.checkUpdate.busy": "检测中…",
"btn.doUpdate": "更新",
"btn.doUpdate.busy": "更新中…",
"channel.title": "通道",
"channel.stable": "正式版",
"channel.beta": "测试版",
"channel.useStable": "切换到正式版",
"channel.useBeta": "切换到测试版",
"channel.local": "本机",
"update.checking": "正在检测更新…",
"update.applying": "正在更新…",
"update.switching": "正在切换版本…",
"update.latest": "已是最新({version})",
"update.available": "有新版本 {remote},当前 {local}",
"update.done": "已更新到 {version},请重启",
"update.autoDone": "已自动更新到 {version},请重启",
"update.pinned": "已固定在 {version},通道最新是 {remote}",
"update.done": "已更新到 {version}",
"update.switched": "已切换到 {version}",
"update.autoDone": "已自动更新到 {version}",
"update.reloading": "正在刷新设置页…",
"update.dirty": "有新版本,本地有改动未自动覆盖",
"update.fail": "更新失败: {error}",
"update.timeout": "检测超时,请再点一次检测更新",
"update.needRestart": "检测接口未加载,请先重启 dsh 再点检测更新",
"update.noBeta": "还没有测试版",
"update.switch": "切换到此版本",
"update.pick": "选择版本",
"update.tip": "最新",
"update.current": "当前",
"update.confirmSwitch": "切换到 {version}?之后可再切回另一通道或其它版本。本地未提交的插件改动不会保留。",
"update.confirmChannel": "切换到{version}?会按该通道重新安装插件,本地未提交的插件改动不会保留。",
"metric.version": "版本",
"action.apply": "应用",
"action.revert": "还原",
@@ -203,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": "重启中…",
@@ -310,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.",
@@ -334,16 +390,33 @@ 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",
"channel.useStable": "Switch to stable",
"channel.useBeta": "Switch to beta",
"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.done": "Updated to {version}. Restart to apply.",
"update.autoDone": "Auto-updated to {version}. Restart to apply.",
"update.pinned": "Pinned at {version}; channel latest is {remote}",
"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.",
"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.pick": "Select version",
"update.tip": "latest",
"update.current": "current",
"update.confirmSwitch": "Switch to {version}? You can switch back later. Uncommitted plugin edits will not be kept.",
"update.confirmChannel": "Switch to {version}? The plugin will be reinstalled from that channel. Uncommitted plugin edits will not be kept.",
"metric.version": "Version",
"action.apply": "Apply",
"action.revert": "Restore",
@@ -374,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…",
@@ -521,6 +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: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: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}
@@ -609,7 +718,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) => {
@@ -756,15 +865,30 @@ 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);
const [notice, setNotice] = useState({ kind: "idle", text: "" });
const [updateNotice, setUpdateNotice] = useState({ kind: "idle", text: "" });
const [updateInfo, setUpdateInfo] = useState(null);
const [canApplyUpdate, setCanApplyUpdate] = useState(false);
const [channel, setChannel] = useState("stable");
const [pick, setPick] = useState({ stable: "", beta: "" });
const actionTicket = useRef(0);
const syncPicks = (d) => {
const versions = (d && d.versions) || [];
const next = { stable: "", beta: "" };
for (const id of ["stable", "beta"]) {
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 || "";
}
setPick(next);
};
const updateErrorText = (tr, e) => {
const msg = String((e && e.message) || e || "");
if (msg === "timeout" || /aborted|abort|超时/i.test(msg)) return tr("update.timeout");
@@ -772,41 +896,114 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
return tr("update.fail", { error: msg });
};
const checkUpdate = useCallback(() => {
const applyUpdateInfo = useCallback((d, tr, kind) => {
if (d.channel) setChannel(d.channel);
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" || 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((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) 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, "check");
})
.catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) }))
.finally(() => setUpdateBusy(false));
}, []);
.finally(() => {
setUpdateBusy(false);
setUpdateJob(null);
});
}, [applyUpdateInfo]);
const doUpdate = useCallback(() => {
const postUpdate = useCallback((body, kind, id) => {
setUpdateBusy(true);
setUpdateJob({ id: id || "", kind });
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.applied || d.needRestart) setAskRestart(true);
if (!d || (d.ok === false && d.error)) throw new Error((d && d.error) || "update failed");
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) }))
.finally(() => setUpdateBusy(false));
}, []);
.catch((e) => {
setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) });
throw e;
})
.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", 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;
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;
const ref = pick[id];
const versions = ((updateInfo && updateInfo.versions) || []).filter((item) => item.channel === id);
const hit = versions.find((item) => item.ref === ref);
const label = (hit && (hit.label || hit.version)) || ref;
if (!ref) return;
if (!window.confirm(tr("update.confirmSwitch", { version: label }))) return;
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;
@@ -814,7 +1011,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 +1022,14 @@ 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);
syncPicks(d);
})
.catch(() => {});
apiJson("/dsh-purge/override")
.then((d) => {
if (d && d.ok) {
@@ -1040,30 +1246,84 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const pct = total ? Math.round((settled / total) * 100) : 0;
const hostSurface = hostSurfaceOf(s);
const versions = (updateInfo && updateInfo.versions) || [];
const channelNow = (updateInfo && updateInfo.channel) || channel || "stable";
const localVer = (s && s.plugin_version) || (updateInfo && updateInfo.localVersion) || "";
const remoteVer = updateInfo && (updateInfo.remoteVersion || updateInfo.remoteSha) || "";
const remoteSha = updateInfo && updateInfo.remoteSha || "";
const sameVer = remoteVer && localVer && remoteVer === localVer;
const versionText = canApplyUpdate && remoteVer
? (sameVer && remoteSha ? "v" + remoteVer + " · " + remoteSha : "v" + remoteVer)
: (localVer ? "v" + localVer : "");
const updateBtnLabel = updateBusy
? (canApplyUpdate ? t("btn.doUpdate.busy") : t("btn.checkUpdate.busy"))
: (canApplyUpdate ? t("btn.doUpdate") : t("btn.checkUpdate"));
const renderEdition = (id) => {
const lane = (updateInfo && updateInfo.lanes && updateInfo.lanes[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(id);
let actionDisabled = updateBusy || Boolean(noBeta);
if (noBeta) {
actionLabel = t("update.noBeta");
actionClick = () => {};
} else if (pickedOther) {
actionLabel = t("update.switch");
actionKind = "primary";
actionClick = () => switchSelected(id);
} else if (!onLane) {
actionLabel = id === "beta" ? t("channel.useBeta") : t("channel.useStable");
actionKind = "primary";
actionClick = () => changeChannel(id);
} else if (canApplyUpdate && lane.hasUpdate) {
actionLabel = t("btn.doUpdate");
actionKind = "primary";
actionClick = () => doUpdate(id);
}
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");
}
return h("div", {
className: "dshp-edition" + (onLane ? " is-on" : ""),
"aria-label": t("channel." + id),
},
h("span", { className: "dshp-edition-name" },
t("channel." + id),
onLane ? h("em", { className: "dshp-now-mark" }, t("update.current")) : null,
),
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") },
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)),
versionText ? h("span", { className: "dshp-pill" + (canApplyUpdate ? " is-wait" : "") }, versionText) : null,
h(Btn, {
tiny: true,
kind: canApplyUpdate ? "primary" : undefined,
disabled: updateBusy,
onClick: canApplyUpdate ? doUpdate : checkUpdate,
}, updateBtnLabel),
noticeNode(updateNotice),
h("span", { className: "dshp-pill" }, t("surface." + hostSurface)),
),
h("div", { className: "dshp-rel" },
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),
),
s ? h("div", { className: "dshp-metrics" },
h("div", { className: "dshp-metric" },
@@ -1359,6 +1619,311 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
);
}
function skillUiAllowed(d) {
if (!d || d.channel === "stable") 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");
@@ -1500,6 +2065,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
),
h(PurgifySection, null),
h(RulesSection, null),
h(SkillsSection, null),
);
}
+47 -5
View File
@@ -734,7 +734,8 @@ export function pathZone(fp) {
export function allowTargetPath(fp, surface = detectSurface()) {
const zone = pathZone(fp);
if (adapterFor(surface) === "desktop") {
return zone === "desktop-install" || zone === "desktop-profile";
// 桌面只动本机桌面树 + 共享的 $DSH_HOME/.agent-presets,不碰 Web / npm-global。
return zone === "desktop-install" || zone === "desktop-profile" || zone === "shared";
}
return zone !== "desktop-install" && zone !== "desktop-profile";
}
@@ -1317,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) {
@@ -1349,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);
@@ -2975,6 +3015,8 @@ const NEW_TOOL_PATCHES = [
"\t\t\t...transformed,\n" +
"\t\t\tsections: completeSection === void 0 ? transformed.sections : (function (complete, assembled) {\n" +
"\t\t\t\tconst sections = assembled.sections || [];\n" +
"\t\t\t\tconst committed = sections.find((s) => s && s.name === \"dsh-purge:committed\");\n" +
"\t\t\t\tif (committed && String(committed.text || \"\").trim()) return [{ ...complete, name: complete.name, text: committed.text }];\n" +
"\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\")).filter((t) => t.length > 0).join(\"\\n\\n\");\n" +
"\t\t\t\tconst folded = sections.find((s) => s && s.name === complete.name);\n" +
"\t\t\t\tconst base = folded && typeof folded.text === \"string\" ? { ...complete, text: folded.text } : { ...complete };\n" +
+38 -4
View File
@@ -175,10 +175,26 @@ export function promptAlreadyInjected(existing, injectText) {
return String(existing || "").includes(inject);
}
export function shouldInjectPrompt(_context, _injectOnce = true, _injectText = "") {
// 0.1.5 in-history:渲染少了注入就会再追加一条 system/message。
// 用「最后一条是否含注入」决定本步掏空注入,会 A/B 死循环。每步都必须留下完整注入。
return true;
export function lastInjectedSystemPrompt(context, injectText) {
const inject = String(injectText || "").trim();
if (!inject) return "";
const events = eventList(context?.agent?.session || context?.session);
let last = "";
for (const event of events) {
if (event?.type !== "system/message") continue;
const text = messageText(event.data?.message || event.data).trim();
if (text && promptAlreadyInjected(text, inject)) last = text;
}
return last;
}
export function shouldInjectPrompt(context, _injectOnce = true, injectText = "") {
const inject = String(injectText || "").trim();
if (!inject) return false;
// 历史里已经有完整注入就不要再折一份。0.1.5 in-history 只要渲染结果和上一条
// system/message 不同就会再追加,聊天里就会每步都冒出「系统提示词」。
// 掏空注入也不行:渲染少了注入同样会被当成变化再追加,形成 A/B。
return !lastInjectedSystemPrompt(context, inject);
}
export function isMnemonPluginMessage(message) {
@@ -198,15 +214,26 @@ function normalizeRewriteOptions(fallbackInject, options) {
fallbackInject: typeof fallbackInject.fallbackInject === "string" ? fallbackInject.fallbackInject : "",
dropMnemon: fallbackInject.dropMnemon !== false,
dropPurgeAfterFold: fallbackInject.dropPurgeAfterFold !== false,
context: fallbackInject.context,
};
}
return {
fallbackInject: typeof fallbackInject === "string" ? fallbackInject : "",
dropMnemon: options?.dropMnemon !== false,
dropPurgeAfterFold: options?.dropPurgeAfterFold !== false,
context: options?.context,
};
}
function pinCommittedSystemPrompt(sections, committed) {
const names = sections.map((section) => String(section?.name || ""));
const hasPrefix = names.some((name) => PERSONA_PREFIX_NAMES.has(name));
const target = hasPrefix
? names.find((name) => PERSONA_PREFIX_NAMES.has(name))
: names.find((name) => PERSONA_LEGACY_NAMES.has(name));
return [{ name: target || "dsh-purge:committed", text: committed }];
}
// 0.1.5 优先写入 persona-prefix;无 prefix 时写入 legacy persona。
function foldInjectIntoPersona(sections, injectText) {
const inject = typeof injectText === "string" ? injectText : "";
@@ -250,6 +277,13 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
}
const injectText = collectInjectText(purge, opts.fallbackInject);
if (!shouldInjectPrompt(opts.context, true, injectText)) {
const committed = lastInjectedSystemPrompt(opts.context, injectText);
if (committed) {
assembled.sections = pinCommittedSystemPrompt([...rest, ...purge], committed);
return assembled;
}
}
const folded = foldInjectIntoPersona(rest, injectText);
const extras = opts.dropPurgeAfterFold
? purge.filter((section) => section.name !== "dsh-purge")
+230 -18
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,
@@ -162,6 +163,14 @@ function injectSnapshotFromBox(dshHome, boxText) {
return { injectSource: "none", injectRuleId: ruleId, needPrompt: true };
}
const NEED_PROMPT_ERROR = "提示词和规则集都是空的,必须先添加提示词";
function rejectIfNeedPrompt(dshHome, boxText) {
const snap = injectSnapshotFromBox(dshHome, boxText);
if (!snap.needPrompt) return null;
return { ...snap, error: NEED_PROMPT_ERROR };
}
export function registerPromptSections(ctx, config, _injectFile) {
ctx.systemPrompt.section({
name: "dsh-purge",
@@ -214,7 +223,7 @@ function installIdentityOverride(ctx, config = {}) {
if (typeof ctx.on !== "function") return;
if (ctx.__dshPurgeAssembleHook) return;
ctx.__dshPurgeAssembleHook = true;
const hook = async (_assembly, _context, next) => {
const hook = async (_assembly, context, next) => {
const assembled = typeof next === "function" ? await next() : _assembly;
const enabled = config.enabled !== false;
const inject = enabled ? readInjectFallback() : "";
@@ -222,6 +231,7 @@ function installIdentityOverride(ctx, config = {}) {
fallbackInject: inject,
dropMnemon: config.stripMnemon !== false,
dropPurgeAfterFold: true,
context,
});
};
// 只挂一次:挂多次会让同一轮 assemble 折两遍,UI 也会显示两次注入。
@@ -302,9 +312,10 @@ async function handlePurgeCommand(rawInput, config) {
if (!state.ai_base) {
return { kind: "error", text: core.missingAiBaseMessage() };
}
const blocked = rejectIfNeedPrompt(state.dsh_home);
if (blocked) return { kind: "error", text: blocked.error };
await core.backupAll(state.ai_base);
const report = await core.applyPatches(state.ai_base);
await core.installOverride(state.dsh_home, false);
const shimResult = await core.patchAllShims();
const flash = core.silenceCmdFlash(state.ai_base);
const lines = report.map((r) => {
@@ -388,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>)",
};
}
}
@@ -502,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;
@@ -563,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",
@@ -646,9 +764,10 @@ export function apply(ctx, config) {
const scrubbed = core.sanitizeDesktopCommandRuntimes();
const state = await core.gatherState();
if (!state.ai_base) return { text: "ERROR: " + core.missingAiBaseMessage() };
const blocked = rejectIfNeedPrompt(state.dsh_home);
if (blocked) return { text: "ERROR: " + blocked.error };
await core.backupAll(state.ai_base);
const report = await core.applyPatches(state.ai_base);
await core.installOverride(state.dsh_home, false);
await core.patchAllShims();
const flash = core.silenceCmdFlash(state.ai_base);
const applied = report.filter((r) => r.status === "applied").length;
@@ -691,6 +810,7 @@ export function apply(ctx, config) {
}
function installWebServer(ctx, cfg) {
// 桌面端内嵌 @deepseek-ai/dsh-web-app,设置页同样走 webServer(常见 43120),不是只给官方 dsh web。
watchWebTreeReady(ctx);
ctx.inject(["webServer"], (host) => {
host.effect(() => {
@@ -733,6 +853,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) });
@@ -897,10 +1019,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) });
}
@@ -930,15 +1049,14 @@ function installWebServer(ctx, cfg) {
const body = await readJsonBody(request);
const ui = await core.readOverrideForUi(state.dsh_home);
const boxText = typeof body?.content === "string" ? body.content : ui.content;
const snap = injectSnapshotFromBox(state.dsh_home, boxText);
if (snap.needPrompt) {
const blocked = rejectIfNeedPrompt(state.dsh_home, boxText);
if (blocked) {
sendJson(response, 400, {
ok: false,
needPrompt: true,
error: "提示词和规则集都是空的,必须先添加提示词",
override_content: boxText,
defaultContent: ui.defaultContent,
...snap,
...blocked,
});
return;
}
@@ -1051,13 +1169,12 @@ function installWebServer(ctx, cfg) {
return;
}
const home = core.findDshHome();
const snap = injectSnapshotFromBox(home, content);
if (snap.needPrompt) {
const blocked = rejectIfNeedPrompt(home, content);
if (blocked) {
sendJson(response, 400, {
ok: false,
error: "提示词和规则集都是空的,必须先添加提示词",
content,
...snap,
...blocked,
});
return;
}
@@ -1073,6 +1190,7 @@ function installWebServer(ctx, cfg) {
},
}, "dsh-purge: override");
installRulesHttp(host.webServer);
installSkillsHttp(host.webServer);
host.webServer.register({
kind: "exact",
path: "/dsh-purge/restart",
@@ -1177,6 +1295,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, {
@@ -1232,13 +1443,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),
})),
};
}
+457 -54
View File
@@ -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,113 @@ 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 || ""));
}
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("-");
const core = String(cut[0] || "").split(".").map((n) => parseInt(n, 10) || 0);
return { core: [core[0] || 0, core[1] || 0, core[2] || 0], pre: cut.slice(1).join("-") };
}
export function versionIsNewer(remote, local) {
if (!remote) return false;
if (!local) return true;
if (String(remote) === String(local)) return false;
const a = splitVersion(remote);
const b = splitVersion(local);
for (let i = 0; i < 3; i += 1) {
if (a.core[i] !== b.core[i]) return a.core[i] > b.core[i];
}
if (a.pre && !b.pre) return false;
if (!a.pre && b.pre) return true;
return a.pre > b.pre;
}
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());
const rows = Array.isArray(raw) ? raw : [];
return rows.filter((item) => item && !withdrawnVersion(item));
}
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 +311,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 +327,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 +418,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 +446,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(/<id>tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/);
return hit ? hit[1] : "";
@@ -354,31 +461,214 @@ 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;
}
function markCurrent(versions, state, localVer, localSha) {
return (versions || []).map((item) => ({
...item,
shaShort: 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)
|| (!state.pin && item.version && item.version === localVer && item.channel === (isBetaName(localVer) ? "beta" : "stable")),
),
}));
}
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) {
if (!withdrawnVersion(tag)) add(tag);
}
for (const item of readHistory()) {
if (!item || !item.ref || withdrawnVersion(item)) 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: markCurrent(out.filter((item) => !withdrawnVersion(item)), state, localVer, localSha),
hasBeta: Boolean(betaSha || out.some((item) => item.channel === "beta" && item.kind === "tag")),
stableSha,
betaSha,
};
}
function alignChannelState(state, listed, localRev, localVer) {
if (state.pin) return state;
if (listed.betaSha && localRev && sameRev(localRev, listed.betaSha) && state.channel !== "beta") {
return writeChannelState({ channel: "beta", pin: "" });
}
if (listed.stableSha && localRev && sameRev(localRev, listed.stableSha) && state.channel !== "stable") {
return writeChannelState({ channel: "stable", pin: "" });
}
if (!localRev && localVer) {
const inferred = isBetaName(localVer) ? "beta" : "stable";
if (inferred !== state.channel) return writeChannelState({ channel: inferred, pin: "" });
}
return state;
}
function describeLane(id, listed, state, localVer, localRev) {
const sha = id === "beta" ? listed.betaSha : listed.stableSha;
const versions = listed.versions.filter((item) => item.channel === id);
const latest = versions.find((item) => item.latest);
const version = latest?.version || "";
const onLane = state.channel === id;
const matchesHead = Boolean(localRev && sha && sameRev(localRev, sha));
const current = versions.some((item) => item.current) || matchesHead
|| Boolean(onLane && version && localVer && version === localVer && !state.pin);
let hasUpdate = false;
if (onLane && state.pin) {
hasUpdate = Boolean(sha && localRev && !sameRev(localRev, sha));
} else if (onLane && sha && localRev) {
hasUpdate = !sameRev(localRev, sha) || versionIsNewer(version, localVer);
} else if (onLane && versionIsNewer(version, localVer)) {
hasUpdate = true;
}
return {
id,
ref: CHANNELS[id].ref,
version,
sha: sha ? String(sha).slice(0, 7) : "",
current,
hasUpdate,
hasRemote: Boolean(sha || versions.length),
};
}
function lanesOf(listed, state, localVer, localRev) {
return {
stable: describeLane("stable", listed, state, localVer, localRev),
beta: describeLane("beta", listed, state, localVer, localRev),
};
}
export async function checkUpdate() {
let state = readChannelState();
const localVer = localVersion();
const listed = await listRemoteVersions();
const gitSha = gitOk() ? gitHead(PLUGIN_ROOT) : "";
const stamp = readStamp();
const localRev = gitSha || stamp;
let hasUpdate = false;
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;
state = alignChannelState(state, listed, localRev, localVer);
listed.versions = markCurrent(listed.versions, state, localVer, localRev);
const channelRef = currentChannelRef(state);
const lanes = lanesOf(listed, state, localVer, localRev);
const lane = lanes[state.channel] || lanes.stable;
if (!lane.hasRemote && state.channel === "beta") {
return rememberUpdate({
ok: true,
hasUpdate: false,
hasBeta: false,
error: "还没有测试版",
localVersion: localVer,
remoteVersion: "",
localSha: localRev ? localRev.slice(0, 7) : "",
remoteSha: "",
updateTarget: channelRef,
via: detectVia(),
versions: listed.versions,
lanes,
...channelPublic(state),
});
}
if (!lanes.stable.hasRemote) throw new Error("无法读取 GitHub master");
const result = {
ok: true,
hasUpdate,
hasUpdate: Boolean(lane.hasUpdate),
hasBeta: listed.hasBeta,
updateTarget: channelRef,
pinned: Boolean(state.pin),
localVersion: localVer,
remoteVersion: remoteVer || (remoteSha ? remoteSha.slice(0, 7) : ""),
remoteVersion: lane.version || lane.sha,
localSha: localRev ? localRev.slice(0, 7) : "",
remoteSha: remoteSha ? remoteSha.slice(0, 7) : "",
remoteSha: lane.sha,
via: detectVia(),
versions: listed.versions,
lanes,
...channelPublic(state),
};
rememberUpdate(result);
return result;
@@ -422,21 +712,31 @@ function runGit(dir, args, timeout = 20000) {
}
}
function gitPull(dir) {
function gitResetTo(dir, ref, { force = false } = {}) {
if (!force && gitTrackedDirty(dir)) {
throw new Error("本地插件文件有未提交改动,未覆盖");
}
const target = String(ref || STABLE_REF);
try {
runGit(dir, ["pull", "--ff-only", "origin", BRANCH], 60000);
return;
} catch (pullErr) {
runGit(dir, ["fetch", "origin", "--tags"], 60000);
} catch {
runGit(dir, ["fetch", "origin", "--tags", target], 60000);
}
if (target === STABLE_REF || target === BETA_REF) {
try {
runGit(dir, ["fetch", "origin", BRANCH], 60000);
runGit(dir, ["reset", "--hard", `origin/${BRANCH}`], 60000);
runGit(dir, ["checkout", "-B", target, `origin/${target}`]);
return;
} catch {
runGit(dir, ["reset", "--hard", `origin/${target}`]);
return;
} catch (resetErr) {
throw new Error(
`git 更新失败(${dir}):${String(resetErr.message || resetErr).slice(0, 240)};${String(pullErr.message || pullErr).slice(0, 160)}`,
);
}
}
try {
runGit(dir, ["fetch", "origin", "--tags", target], 60000);
} catch {
// 上面已经 fetch 过全部分支。
}
runGit(dir, ["reset", "--hard", target]);
}
function extractZip(zip, dest) {
@@ -457,12 +757,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);
@@ -473,8 +773,16 @@ async function overlayFromZip(dests) {
for (const dest of unique) {
for (const name of COPY_NAMES) {
const from = path.join(unpacked, name);
const to = path.join(dest, name);
if (!fs.existsSync(from)) continue;
await fsp.cp(from, path.join(dest, name), { recursive: true, force: true });
if (name === "lib" || name === "docs" || name === "bin") {
try {
await fsp.rm(to, { recursive: true, force: true });
} catch {
// 目录被占用时改为覆盖写入。
}
}
await fsp.cp(from, to, { recursive: true, force: true });
}
}
try {
@@ -484,23 +792,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,29 +827,110 @@ 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 = (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 || "");
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 prev = lastUpdateResult() || {};
const listed = {
versions: Array.isArray(prev.versions) ? prev.versions : [],
hasBeta: prev.hasBeta !== false,
stableSha: prev.stableSha || "",
betaSha: prev.betaSha || "",
};
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,
needRestart: false,
reloadClient: true,
via,
versions: listed.versions,
lanes: lanesOf(listed, saved, localVer, sha),
...channelPublic(saved),
});
}
export async function switchChannel(channel, { apply = true } = {}) {
const next = normalizeChannel(channel);
if (next === "beta") {
const betaSha = await remoteHeadSha(BETA_REF);
if (!betaSha) {
const tags = await listGithubTags();
const tag = tags.find((item) => item.channel === "beta");
if (!tag) {
return rememberUpdate({
ok: false,
error: "还没有测试版",
hasBeta: false,
...channelPublic(),
versions: [],
lanes: { stable: { id: "stable", hasRemote: true }, beta: { id: "beta", hasRemote: false } },
});
}
if (apply) return applyUpdate(planUpdates(), { ref: tag.ref, channel: "beta", pin: false, force: true });
}
}
if (!apply) {
writeChannelState({ channel: next, pin: "" });
return checkUpdate();
}
return applyUpdate(planUpdates(), { ref: CHANNELS[next].ref, channel: next, pin: false, force: true });
}
export async function switchVersion(ref) {
const target = String(ref || "").trim();
if (!target) throw new Error("请选择要回退的版本");
if (withdrawnVersion({ ref: target, version: 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);
if (hit && withdrawnVersion(hit)) throw new Error("该版本已下线");
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();
const state = readChannelState();
const ref = body.ref || currentChannelRef(state);
const channel = body.channel || (ref === BETA_REF ? "beta" : ref === STABLE_REF ? "stable" : state.channel);
return applyUpdate(planUpdates(), { ref, channel, 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" });
if (check.updateTarget === BETA_REF && readChannelState().channel !== "beta") {
return rememberUpdate({ ...check, auto: true, skipped: "beta" });
}
const jobs = planUpdates();
const dirtyGit = jobs.filter((j) => j.kind === "git" && gitTrackedDirty(j.dir));
const runnable = jobs.filter((j) => !(j.kind === "git" && gitTrackedDirty(j.dir)));
@@ -545,7 +942,12 @@ export async function autoUpdateIfNeeded() {
error: "本地插件文件有未提交改动,未自动覆盖",
});
}
const applied = await applyUpdate(runnable);
const applied = await applyUpdate(runnable, {
ref: currentChannelRef(),
channel: readChannelState().channel,
pin: false,
force: false,
});
return rememberUpdate({ ...applied, auto: true });
} catch (e) {
return rememberUpdate({
@@ -553,6 +955,7 @@ export async function autoUpdateIfNeeded() {
auto: true,
hasUpdate: false,
error: String(e && e.message ? e.message : e),
...channelPublic(),
});
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-purge",
"version": "1.1.10",
"version": "1.1.12-beta.1",
"description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐",
"type": "module",
"main": "lib/index.js",