feat: 发布 1.1.0,自动更新并修复 #14 #15 #16

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-09-17 22:36:04 +08:00
1 parent 0d2a126205
commit a3eb5cd502
8 files changed
+564 -114

No files matched your search

+18 -8
View File
@@ -4,7 +4,7 @@
<h1 align="center">dsh-purge</h1>
<p align="center"><strong>Version 1.0.0</strong></p>
<p align="center"><strong>Version 1.1.0</strong></p>
<p align="center">
<em>DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐</em>
@@ -82,7 +82,7 @@ This is a local Harness plugin. It is not a public scanner and not an attack kit
Web and desktop install the same plugin into different profiles. After install you **must fully quit and restart** DeepSeek Harness so the **Rules** card appears. Then **Apply** — adding the bundle does not patch `@deepseek-ai` packages by itself.
> 🌐 **Plugin hub:** [DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge)
> 🌐 **Plugin hub:** [DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge) (docs only — **do not** install via `deepseek.stream/api/plugins/download?...`; that URL is not a pnpm tarball and fails with `ERR_PNPM_TARBALL_EXTRACT`)
### Method 1: Hand this to an AI agent (fastest)
@@ -103,6 +103,7 @@ Paste this README (or the block below) to a local coding agent and let it instal
- Target: **dsh 0.1.5-rc.1** (other versions may install; unmatched items skip)
- Node.js `>= 18`
- Reachable `github.com`
- Do **not** use `https://deepseek.stream/api/plugins/download?...` (not a tarball; pnpm fails with `ERR_PNPM_TARBALL_EXTRACT`)
**One-shot install (preferred, no clone)**
@@ -166,13 +167,13 @@ If the official DeepSeek Harness desktop client (EXE) is installed, the button b
<p align="center">
<a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 Open Hub page</strong></a>
&nbsp;·&nbsp;
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.0.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip"><strong>🚀 Install in desktop client</strong></a>
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip"><strong>🚀 Install in desktop client</strong></a>
</p>
🔗 **Raw protocol URL:**
```
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.0.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip
```
**Web trigger example:**
@@ -185,7 +186,7 @@ export function installDshPurgeToDesktop() {
const params = new URLSearchParams({
id: 'dsh-purge',
name: 'dsh-purge',
version: '1.0.0',
version: '1.1.0',
repo: 'YuJunZhiXue/dsh-purge',
permissions: '系统提示词注入, 本机补丁, 设置页',
downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip',
@@ -204,7 +205,7 @@ export function installDshPurgeToDesktop() {
**HTML link:**
```html
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.0.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip">
🚀 Install in desktop client
</a>
```
@@ -215,7 +216,7 @@ export function installDshPurgeToDesktop() {
|---|---|---|
| id | `dsh-purge` | Plugin id |
| name | `dsh-purge` | Display name |
| version | `1.0.0` | Semver |
| version | `1.1.0` | Semver |
| repo | `YuJunZhiXue/dsh-purge` | GitHub repo |
| permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions |
| downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | Zip URL |
@@ -345,6 +346,7 @@ Plugin config lives in `cordis.patch.yml`:
config:
enabled: true
autoApplyOnStart: true
autoUpdateOnStart: true
autoRevertOnMissing: false
verbose: false
postPromptOrder: 5100
@@ -531,10 +533,18 @@ If nothing is found, set `DSH_BASE`. No files are changed.
## Changelog
### 1.1.0
- Check update and download share one button: after a check, it becomes **Update** and the pill shows the remote version.
- Startup auto-checks GitHub `master` and downloads. `dsh plugin add` (zip / github) uses the official CLI; machines without git overlay `master.zip`. Uncommitted files in a git checkout are not auto-overwritten.
- **#16:** `#26` no longer applies bare identity replacements to YAML; apply rewrites `prefix`/`text` fold indent so the cordis preset mounts.
- **#15:** Empty prompt-inject still injects nothing. If there is text but it never reaches the model, 0.1.5 `complete:true` was dropping every section after assemble; `#41` folds inject back into the complete prompt.
- **#14:** Hub `api/plugins/download` is not a tarball; install from GitHub `master.zip` only.
### 1.0.0
- Version numbering reset.
- Settings: **Check update** reads GitHub `master`. After a push, others can install that commit (git pull, or zip overlay). Restart to load.
- Settings: **Check update** reads GitHub `master`.
### 1.3.6 (dsh 0.1.5-rc.1)
+18 -8
View File
@@ -4,7 +4,7 @@
<h1 align="center">dsh-purge</h1>
<p align="center"><strong>Version 1.0.0</strong></p>
<p align="center"><strong>Version 1.1.0</strong></p>
<p align="center">
<em>DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐</em>
@@ -79,7 +79,7 @@
Web 和桌面装的是同一个插件,只是 profile 不同。装完必须**完全退出并重启** DeepSeek Harness,设置页才会出现「规则设定」;然后再点「应用」打补丁(只装进 profile 还不会改 `@deepseek-ai` 包)。
> 🌐 **插件生态市场**:[DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge)
> 🌐 **插件生态市场**:[DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge)(只看介绍;**不要**用 `deepseek.stream/api/plugins/download?...`,那个地址不是 pnpm 能解的 tar,会报 `ERR_PNPM_TARBALL_EXTRACT`)
### 方式 1:交给 AI 安装(最快)
@@ -100,6 +100,7 @@ Web 和桌面装的是同一个插件,只是 profile 不同。装完必须**
- 目标版本:**dsh 0.1.5-rc.1**(其它版本可装,原文对不上的项会跳过)
- Node.js `>= 18`
- 能访问 `github.com`
- **禁止**用 `https://deepseek.stream/api/plugins/download?...`(不是 tar,pnpm 会 `ERR_PNPM_TARBALL_EXTRACT`)
**一步安装(优先,无需 clone)**
@@ -163,13 +164,13 @@ dsh plugin --profile default remove dsh-purge
<p align="center">
<a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 打开插件市场页</strong></a>
&nbsp;·&nbsp;
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.0.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip"><strong>🚀 唤起客户端一键安装</strong></a>
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip"><strong>🚀 唤起客户端一键安装</strong></a>
</p>
🔗 **原生协议链接:**
```
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.0.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip
dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip
```
**网页端(前端)触发代码示例:**
@@ -182,7 +183,7 @@ export function installDshPurgeToDesktop() {
const params = new URLSearchParams({
id: 'dsh-purge',
name: 'dsh-purge',
version: '1.0.0',
version: '1.1.0',
repo: 'YuJunZhiXue/dsh-purge',
permissions: '系统提示词注入, 本机补丁, 设置页',
downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip',
@@ -201,7 +202,7 @@ export function installDshPurgeToDesktop() {
**HTML 静态链接方式:**
```html
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.0.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.0&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip">
🚀 唤起客户端一键安装
</a>
```
@@ -212,7 +213,7 @@ export function installDshPurgeToDesktop() {
|---|---|---|
| id | `dsh-purge` | 插件唯一标识符 |
| name | `dsh-purge` | 插件展示名称 |
| version | `1.0.0` | 语义化版本号 |
| version | `1.1.0` | 语义化版本号 |
| repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 |
| permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 |
| downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | zip 下载直链 |
@@ -346,6 +347,7 @@ dsh plugin --profile default remove dsh-purge
config:
enabled: true
autoApplyOnStart: true
autoUpdateOnStart: true
autoRevertOnMissing: false
verbose: false
postPromptOrder: 5100
@@ -535,10 +537,18 @@ npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑
## 更新记录
### 1.1.0
- 检测更新与下载分开:先查,有新版本按钮变成「更新」,版本号显示远端。
- 开机自动对照 GitHub `master` 并下载。`dsh plugin add`(zip / github)走官方 CLI;没 git 下 `master.zip` 覆盖。git 仓库本地有未提交改动时不自动覆盖。
- **#16**:`#26` 不再对 YAML 用无缩进 identity 替换;apply 重写 `prefix`/`text` 缩进,cordis 预设能挂载。
- **#15**:空提示词仍不注入。有内容却进不了会话,是 0.1.5 `complete:true` 丢掉 section;`#41` 把注入补回 complete 段。
- **#14**:Hub `api/plugins/download` 不是 tar,安装只用 GitHub `master.zip`。
### 1.0.0
- 版本号从头计数。
- 设置页增加 **检测更新**:对照 GitHub `master`。你推送到云端后,别人点更新即可装上该提交(git 目录走 pull,zip 安装覆盖文件),然后重启。
- 设置页增加 **检测更新**:对照 GitHub `master`。
### 1.3.6(适配 dsh 0.1.5-rc.1)
+69 -29
View File
@@ -17,9 +17,19 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
function apiUrl(p) {
try { return new URL(p, window.location.origin).toString(); } catch { return p; }
}
function apiTimeoutMs(p, init) {
const path = String(p || "");
const method = String((init && init.method) || "GET").toUpperCase();
if (path.indexOf("/dsh-purge/update") !== -1) return method === "POST" ? 180000 : 45000;
return 20000;
}
function isAbortError(e) {
const msg = String((e && e.message) || e || "");
return (e && e.name === "AbortError") || /aborted|abort/i.test(msg);
}
async function apiJson(p, init) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 12000);
const timer = setTimeout(() => ctrl.abort(), apiTimeoutMs(p, init));
try {
const r = await fetch(apiUrl(p), Object.assign({ cache: "no-store", credentials: "same-origin", signal: ctrl.signal }, init || {}));
const text = await r.text();
@@ -29,6 +39,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
}
if (!r.ok) throw new Error((data && (data.error || data.message)) || (r.status + " " + r.statusText));
return data;
} catch (e) {
if (isAbortError(e)) throw new Error("timeout");
throw e;
} finally { clearTimeout(timer); }
}
@@ -38,7 +51,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
{ key: "code", ids: [6, 7, 8] },
{ key: "engine", ids: [9, 10, 11, 12, 13, 14, 15, 16, 36] },
{ key: "tools", ids: [17, 18, 19, 20, 21, 22, 23, 24, 25, 30, 31, 32, 34, 35, 37, 38] },
{ key: "compat", ids: [39, 40] },
{ key: "compat", ids: [39, 40, 41] },
];
const zh = {
@@ -72,7 +85,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"update.latest": "已是最新({version})",
"update.available": "有新版本 {remote},当前 {local}",
"update.done": "已更新到 {version},请重启",
"update.autoDone": "已自动更新到 {version},请重启",
"update.dirty": "有新版本,本地有改动未自动覆盖",
"update.fail": "更新失败: {error}",
"update.timeout": "检测超时,请再点一次检测更新",
"update.needRestart": "检测接口未加载,请先重启 dsh 再点检测更新",
"metric.version": "版本",
"action.apply": "应用",
@@ -158,6 +174,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"patch.38": "子代理 scope lock 中性化",
"patch.39": "persona text→prefix(0.1.2 预设)",
"patch.40": "会话 v0 plugin summary(mnemon)",
"patch.41": "complete 预设仍保留注入",
};
const en = {
@@ -191,7 +208,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"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.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.",
"metric.version": "Version",
"action.apply": "Apply",
@@ -277,6 +297,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"patch.38": "Subagent scope lock neutralized",
"patch.39": "persona text→prefix (0.1.2 presets)",
"patch.40": "session v0 plugin summary (mnemon)",
"patch.41": "Keep inject when a complete prompt is set",
};
const THEME_KEY = "dshp-theme";
@@ -455,57 +476,65 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const [state, setState] = useState(null);
const [override, setOverride] = useState("");
const [overrideLoaded, setOverrideLoaded] = useState(false);
const [busy, setBusy] = useState(false);
const [patchBusy, setPatchBusy] = useState(false);
const [updateBusy, setUpdateBusy] = useState(false);
const [askRestart, setAskRestart] = 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 updateErrorText = (tr, e) => {
const msg = String((e && e.message) || e || "");
if (msg === "timeout" || /aborted|abort|超时/i.test(msg)) return tr("update.timeout");
if (/\b404\b/.test(msg) || /non-json/.test(msg)) return tr("update.needRestart");
return tr("update.fail", { error: msg });
};
const checkUpdate = useCallback(() => {
setBusy(true);
setUpdateBusy(true);
const tr = tRef.current;
setNotice({ kind: "ok", text: tr("update.checking") });
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);
setNotice({
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 || "—" }),
});
})
.catch((e) => setNotice({ kind: "error", text: updateErrorText(tr, e) }))
.finally(() => setBusy(false));
.catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) }))
.finally(() => setUpdateBusy(false));
}, []);
const doUpdate = useCallback(() => {
setBusy(true);
setUpdateBusy(true);
const tr = tRef.current;
setNotice({ kind: "ok", text: tr("update.applying") });
setUpdateNotice({ kind: "ok", text: tr("update.applying") });
apiJson("/dsh-purge/update", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })
.then((d) => {
if (!d || !d.ok) throw new Error((d && d.error) || "update failed");
setUpdateInfo(d);
setNotice({ kind: "ok", text: tr("update.done", { version: d.localVersion || d.remoteVersion || "—" }) });
setCanApplyUpdate(false);
setUpdateNotice({ kind: "ok", text: tr("update.done", { version: d.localVersion || d.remoteVersion || "—" }) });
if (d.applied || d.needRestart) setAskRestart(true);
})
.catch((e) => setNotice({ kind: "error", text: updateErrorText(tr, e) }))
.finally(() => setBusy(false));
.catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) }))
.finally(() => setUpdateBusy(false));
}, []);
const loadAll = useCallback(() => {
const tr = tRef.current;
apiJson("/dsh-purge/status")
.then((d) => {
if (d && d.ok) setState(d);
else {
if (d && d.ok) {
setState(d);
if (d.update && d.update.ok && !d.update.error && !d.update.hasUpdate) 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" }) });
}
@@ -525,7 +554,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
useEffect(() => { loadAll(); }, [loadAll]);
const doAction = useCallback((action, actionKey) => {
setBusy(true);
setPatchBusy(true);
setAskRestart(false);
setNotice({ kind: "idle", text: "" });
const tr = tRef.current;
@@ -575,11 +604,11 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
}
})
.catch((e) => setNotice({ kind: "error", text: tr("err.action", { action: label, error: e.message }) }))
.finally(() => setBusy(false));
.finally(() => setPatchBusy(false));
}, [loadAll]);
const saveOverride = useCallback(() => {
setBusy(true);
setPatchBusy(true);
setNotice({ kind: "idle", text: "" });
fetch("/dsh-purge/override", {
method: "POST",
@@ -593,7 +622,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
: { kind: "error", text: t("err.save", { error: d.error || "" }) });
})
.catch((e) => setNotice({ kind: "error", text: t("err.save", { error: e.message }) }))
.finally(() => setBusy(false));
.finally(() => setPatchBusy(false));
}, [override, t]);
const s = state;
@@ -601,17 +630,28 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const applied = s && typeof s.patches_applied === "number" ? s.patches_applied : 0;
const pct = total ? Math.round((applied / total) * 100) : 0;
const version = (s && s.plugin_version) || (updateInfo && updateInfo.localVersion) || "";
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"));
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" } },
version ? h("span", { className: "dshp-pill" }, "v" + version) : null,
h(Btn, { tiny: true, disabled: busy, onClick: checkUpdate }, busy ? t("btn.checkUpdate.busy") : t("btn.checkUpdate")),
updateInfo && updateInfo.hasUpdate
? h(Btn, { tiny: true, kind: "primary", disabled: busy, onClick: doUpdate }, busy ? t("btn.doUpdate.busy") : t("btn.doUpdate"))
: null,
noticeNode(notice),
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),
),
),
s ? h("div", { className: "dshp-metrics" },
@@ -641,8 +681,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
h("div", { className: "dshp-bar", "aria-hidden": "true" }, h("i", { style: { width: pct + "%" } })),
h(PatchGroups, { state: s }),
h("div", { className: "dshp-row", style: { marginTop: 14 } },
h(Btn, { kind: "primary", disabled: busy, onClick: () => doAction("apply", "action.apply") }, busy ? t("btn.apply.busy") : t("btn.apply")),
h(Btn, { kind: "danger", disabled: busy, onClick: () => doAction("revert", "action.revert") }, t("btn.revert")),
h(Btn, { kind: "primary", disabled: patchBusy, onClick: () => doAction("apply", "action.apply") }, patchBusy ? t("btn.apply.busy") : t("btn.apply")),
h(Btn, { kind: "danger", disabled: patchBusy, onClick: () => doAction("revert", "action.revert") }, t("btn.revert")),
noticeNode(notice),
),
askRestart ? h("div", { className: "dshp-ask" },
@@ -660,7 +700,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
h("div", { className: "dshp-sub" },
h("h4", null, t("override.title")),
h("div", { className: "dshp-row", style: { margin: 0 } },
h(Btn, { kind: "primary", tiny: true, disabled: busy || !overrideLoaded, onClick: saveOverride }, t("btn.saveInject")),
h(Btn, { kind: "primary", tiny: true, disabled: patchBusy || !overrideLoaded, onClick: saveOverride }, t("btn.saveInject")),
),
),
h("textarea", {
+1
View File
@@ -9,6 +9,7 @@
config:
enabled: true
autoApplyOnStart: true
autoUpdateOnStart: true
autoRevertOnMissing: false
verbose: false
postPrompt: ""
+115 -19
View File
@@ -1164,7 +1164,31 @@ export function findDshHome(options = {}) {
const prefix = options.prefix !== undefined ? options.prefix : findNpmPrefix();
const portable = portableHomeFromLauncher(shimDir, prefix);
if (portable) return portable;
return path.join(os.homedir(), ".dsh");
const unix = path.join(os.homedir(), ".dsh");
if (isDir(unix)) return unix;
const wslWin = findWslWindowsDshHome(env);
if (wslWin) return wslWin;
return unix;
}
function findWslWindowsDshHome(env = process.env) {
if (process.platform !== "linux") return "";
const rel = env.WSL_DISTRO_NAME || env.WSLENV;
if (!rel && !isDir("/mnt/c/Users")) return "";
const users = "/mnt/c/Users";
if (!isDir(users)) return "";
let names = [];
try {
names = fs.readdirSync(users);
} catch {
return "";
}
for (const name of names) {
if (name === "Public" || name === "Default" || name === "Default User" || name === "All Users") continue;
const cand = path.join(users, name, ".dsh");
if (isDir(cand)) return path.normalize(cand);
}
return "";
}
export function findNpmPrefix() {
@@ -2095,14 +2119,12 @@ const NEW_TOOL_PATCHES = [
replace: 'prefix: ""',
},
{
// 1.3.6 把无缩进 identity+\n\n 抽掉后,行首 6 空格和下一段拼成 12 空格。
// 0.1.5 cordis:连同行首 6 空格删身份段,plane 说明缩进保持 6。
pattern:
" prefix: |-\n You can read and modify the harness you run on.",
replace:
" prefix: |-\n You can read and modify the harness you run on.",
" You are a coding agent powered by the {{model}} model, running on the DeepSeek Harness. Your working directory is {{cwd}}.\n\n",
replace: IDENTITY_STRIP,
},
{
// 0.1.5 cordis:连同行首 6 空格删身份段,plane 说明缩进保持 6。
pattern:
" You are a coding agent powered by the {{model}} model, running on the DeepSeek Harness.\n\n",
replace: IDENTITY_STRIP,
@@ -2158,6 +2180,13 @@ const NEW_TOOL_PATCHES = [
pattern: "Start every reply with the deliverable. - id: agent-instructions",
replace: "Start every reply with the deliverable.\n\n- id: agent-instructions",
},
{
// 1.3.6 无缩进 identity+\n\n 留下的 12 空格首行;sanitize 也会修。
pattern:
" prefix: |-\n You can read and modify the harness you run on.",
replace:
" prefix: |-\n You can read and modify the harness you run on.",
},
],
markersAny: true,
markers: [
@@ -2721,6 +2750,37 @@ const NEW_TOOL_PATCHES = [
],
markers: ["[dsh-purge] mnemon summary off-notice"],
},
{
// 0.1.5 assemble 在 waterfall 之后若有 complete:true,会丢掉全部 section,提示词写了也进不去。
id: 41, name: "COMPLETE_PROMPT_KEEP_INJECT", layer: "0.1.5 兼容", layer_en: "0.1.5",
desc: "complete 预设仍保留 dsh-purge 注入 / keep inject after complete prompt",
file: ["system-prompt", "system-prompt-nested"],
replacements: [
{
pattern:
"\t\treturn {\n" +
"\t\t\t...transformed,\n" +
"\t\t\tsections: completeSection === void 0 ? transformed.sections : [completeSection],\n" +
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
"\t\t};",
replace:
"\t\treturn {\n" +
"\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 inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\").trim()).filter(Boolean).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" +
"\t\t\t\tif (!inject) return [base];\n" +
"\t\t\t\tif (String(base.text || \"\").includes(inject.slice(0, Math.min(80, inject.length)))) return [base];\n" +
"\t\t\t\treturn [{ ...base, text: inject + \"\\n\\n\" + base.text }]; // [dsh-purge] complete prompt keeps inject\n" +
"\t\t\t})(completeSection, transformed),\n" +
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
"\t\t};",
},
],
markers: ["[dsh-purge] complete prompt keeps inject"],
},
];
export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES];
@@ -3101,22 +3161,50 @@ function isDisposableYamlFoldParagraph(para) {
return false;
}
function yamlDropPaddingOnlyLines(bodyLines) {
return bodyLines.filter((line) => String(line).trim() !== "" || line === "");
}
function yamlMinContentIndent(bodyLines, keyIndent) {
let min = Infinity;
for (const line of bodyLines) {
if (!String(line).trim()) continue;
const n = yamlIndentOf(line);
if (n > keyIndent && n < min) min = n;
}
return Number.isFinite(min) ? min : keyIndent + 2;
}
function yamlReindentBody(bodyLines, indent) {
const pad = " ".repeat(Math.max(0, indent));
const out = [];
for (const line of bodyLines) {
if (!String(line).trim()) {
out.push("");
continue;
}
out.push(pad + String(line).replace(/^[ \t]+/, ""));
}
return out;
}
function yamlStripDisposableFoldParas(bodyLines) {
const raw = yamlFoldBodyText(bodyLines);
if (!raw) return [];
const kept = raw.split(/\n\s*\n/).filter((para) => !isDisposableYamlFoldParagraph(para));
if (kept.length === 0) return [];
const indent = (bodyLines.find((line) => String(line).trim()) || " ").match(/^[ \t]*/)[0] || " ";
const indent = yamlMinContentIndent(bodyLines, 0);
const pad = " ".repeat(indent || 6);
const out = [];
for (let i = 0; i < kept.length; i += 1) {
if (i > 0) out.push("");
for (const line of kept[i].split("\n")) out.push(indent + line);
for (const line of kept[i].split("\n")) out.push(pad + line);
}
return out;
}
function emptyDisposableFoldedYaml(text) {
const headerRe = /^(\s*)(personaPrefix|prefix|persona):\s*[>|][-+]?\s*$/;
const headerRe = /^(\s*)(personaPrefix|prefix|persona|text|suffix):\s*[>|][-+]?\s*$/;
const lines = String(text).split("\n");
const out = [];
for (let i = 0; i < lines.length; i += 1) {
@@ -3127,14 +3215,13 @@ function emptyDisposableFoldedYaml(text) {
}
const keyIndent = m[1].length;
const end = yamlConsumeFoldBody(lines, i, keyIndent);
const body = lines.slice(i + 1, end);
let body = yamlDropPaddingOnlyLines(lines.slice(i + 1, end));
const kept = yamlStripDisposableFoldParas(body);
if (kept.length === 0) out.push(`${m[1]}${m[2]}: ""`);
else if (kept.length === body.length && kept.every((line, idx) => line === body[idx])) {
out.push(lines[i], ...body);
} else {
else {
const indent = yamlMinContentIndent(kept, keyIndent);
out.push(`${m[1]}${m[2]}: |-`);
out.push(...kept);
out.push(...yamlReindentBody(kept, indent));
}
i = end - 1;
}
@@ -3142,7 +3229,7 @@ function emptyDisposableFoldedYaml(text) {
}
function stripOrphanYamlAfterEmptyScalars(text) {
const headerRe = /^(\s*)(personaPrefix|prefix|persona):\s*(""|'')\s*$/;
const headerRe = /^(\s*)(personaPrefix|prefix|persona|text|suffix):\s*(""|'')\s*$/;
const lines = String(text).split("\n");
const out = [];
for (let i = 0; i < lines.length; i += 1) {
@@ -3215,16 +3302,26 @@ function patchReplacements(p) {
return (p.patterns ?? []).map((pat) => ({ pattern: pat, replace: p.replace }));
}
function applyReplacementsToText(text, patch) {
function isBareIdentityNeedle(pattern) {
const needle = asLf(pattern);
if (!needle) return false;
if (/^[ \t]/.test(needle)) return false;
return /^You are a coding agent powered by\b/.test(needle);
}
function applyReplacementsToText(text, patch, fp = "") {
// 插入型补丁锚点仍在,已有标记则不再 replaceAll。
if (patch.skipIfMarked && patchApplied(text, patch)) {
return { text, changed: false };
}
const crlf = typeof text === "string" && text.includes("\r\n");
const yaml = isYamlPath(fp);
let out = asLf(text);
let changed = false;
for (const { pattern, replace } of patchReplacements(patch)) {
if (!pattern || typeof replace !== "string") continue;
// YAML 块标量行首有缩进;无缩进 identity+\n\n 会留下 6 空格,再和下一段拼成 12 空格。
if (yaml && isBareIdentityNeedle(pattern)) continue;
const needle = asLf(pattern);
if (!out.includes(needle)) continue;
out = out.split(needle).join(asLf(replace));
@@ -3321,7 +3418,7 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES) {
lastError = "read_error";
continue;
}
const appliedText = applyReplacementsToText(text, p);
const appliedText = applyReplacementsToText(text, p, fp);
let textOut = appliedText.text;
let changed = appliedText.changed;
if (isYamlPath(fp)) {
@@ -3849,10 +3946,9 @@ export async function installOverride(dshHome, force = false) {
await fsp.mkdir(dshHome, { recursive: true });
if (fs.existsSync(fp) && !force) {
const existing = await loadText(fp);
// 非空保留用户内容;空文件视为故意清空。
// 空文件就是空:不注入、不改写。
return existing.trim().length > 0 ? "exists" : "empty";
}
// 文件不存在或 force 时写入默认稿。
await fsp.writeFile(fp, defaultOverrideText(), "utf8");
return "wrote";
}
+12 -1
View File
@@ -18,6 +18,7 @@ export const inject = ["systemPrompt", "tools"];
const DEFAULTS = {
enabled: true,
autoApplyOnStart: true,
autoUpdateOnStart: true,
autoRevertOnMissing: false,
postPrompt: "",
postPromptOrder: 5100,
@@ -474,6 +475,11 @@ export function apply(ctx, config) {
rules.ensureInitialState(core.findDshHome())
.then((r) => log(cfg, "rules init:", JSON.stringify(r)))
.catch((e) => console.warn("[dsh-purge] rules init error:", String(e)));
if (cfg.autoUpdateOnStart !== false) {
updater.autoUpdateIfNeeded()
.then((r) => log(cfg, "auto-update:", JSON.stringify(r)))
.catch((e) => console.warn("[dsh-purge] auto-update error:", String(e)));
}
});
installIdentityOverride(ctx);
@@ -686,6 +692,7 @@ function installWebServer(ctx, cfg) {
override_path: state.override_path,
dsh_home: state.dsh_home,
plugin_version: updater.localVersion(),
update: updater.lastUpdateResult(),
});
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
@@ -706,7 +713,11 @@ function installWebServer(ctx, cfg) {
}
if (request.method === "POST") {
try {
sendJson(response, 200, await updater.applyUpdate());
const body = await readJsonBody(request);
const result = body && body.auto
? await updater.autoUpdateIfNeeded()
: await updater.applyUpdate();
sendJson(response, 200, result);
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
}
+330 -48
View File
@@ -8,6 +8,8 @@ import { findDshHome } from "./core.js";
const REPO = "YuJunZhiXue/dsh-purge";
const BRANCH = "master";
const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`;
const GITHUB_SPEC = `github:${REPO}#${BRANCH}`;
const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
const COPY_NAMES = [
"lib",
@@ -65,10 +67,40 @@ function sameRev(a, b) {
return a === b || a.startsWith(b) || b.startsWith(a);
}
function realPath(dir) {
try {
return fs.realpathSync(dir);
} catch {
return path.resolve(dir);
}
}
function readJson(fp) {
try {
return JSON.parse(fs.readFileSync(fp, "utf8"));
} catch {
return null;
}
}
function isGitCheckout(dir) {
return fs.existsSync(path.join(dir, ".git"));
}
function canGit(dir) {
if (!isGitCheckout(dir)) return false;
try {
execFileSync("git", ["-C", dir, "rev-parse", "--is-inside-work-tree"], HIDDEN);
return true;
} catch {
return false;
}
}
function gitOk() {
return canGit(PLUGIN_ROOT);
}
function gitHead(dir) {
try {
return execFileSync("git", ["-C", dir, "rev-parse", "HEAD"], HIDDEN).trim();
@@ -77,9 +109,157 @@ function gitHead(dir) {
}
}
async function fetchText(url, ms = 10000) {
function isLinkSpec(spec) {
const s = String(spec || "");
return /^(link|file):/i.test(s) || s === "." || /^\.\.?(?:[/\\]|$)/.test(s);
}
function resolveLinkDir(profileDir, spec) {
const raw = String(spec).replace(/^(link|file):/i, "");
return path.resolve(profileDir, raw);
}
function findPurgeProfiles() {
const root = path.join(findDshHome(), "profiles");
if (!fs.existsSync(root)) return [];
let names = [];
try {
names = fs.readdirSync(root);
} catch {
return [];
}
const out = [];
for (const name of names) {
const dir = path.join(root, name);
const pkg = readJson(path.join(dir, "package.json"));
const spec = pkg?.dependencies?.["dsh-purge"] || pkg?.devDependencies?.["dsh-purge"];
if (!spec) continue;
out.push({ name, dir, spec: String(spec) });
}
return out;
}
function profilePluginDir(profileDir) {
const nm = path.join(profileDir, "node_modules", "dsh-purge");
return fs.existsSync(nm) ? realPath(nm) : "";
}
function resolveDshBin() {
try {
execFileSync(process.platform === "win32" ? "where" : "which", ["dsh"], HIDDEN);
return "dsh";
} catch {
// 桌面进程 PATH 里经常没有 dsh,再到启动器旁找。
}
const home = findDshHome();
const names = process.platform === "win32" ? ["dsh.cmd", "dsh.exe", "dsh"] : ["dsh"];
const dirs = [
path.join(home, "..", "npm-global"),
path.join(home, "..", "npm-global-0.1.5-rc.1"),
path.join(home, "bin"),
];
for (const dir of dirs) {
for (const name of names) {
const fp = path.join(dir, name);
if (fs.existsSync(fp)) return fp;
}
}
return "";
}
function runDshPlugin(profile, args) {
const bin = resolveDshBin();
if (!bin) throw new Error("找不到 dsh");
execFileSync(bin, ["plugin", "--profile", profile, ...args], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
timeout: 120000,
env: {
...process.env,
DSH_HOME: findDshHome(),
CI: "1",
},
});
}
function addSpecFor(spec) {
const s = String(spec || "");
if (/\.zip(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return ZIP_URL;
if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC;
return "";
}
function dshReinstall(profile, spec) {
const addSpec = addSpecFor(spec);
if (addSpec) {
runDshPlugin(profile, ["add", "--force", addSpec]);
return;
}
try {
runDshPlugin(profile, ["update", "dsh-purge"]);
} catch {
runDshPlugin(profile, ["add", "--force", ZIP_URL]);
}
}
function planUpdates() {
const profiles = findPurgeProfiles();
const jobs = [];
const seen = new Set();
const remember = (dir) => {
const key = realPath(dir).toLowerCase();
if (seen.has(key)) return false;
seen.add(key);
return true;
};
for (const p of profiles) {
if (isLinkSpec(p.spec)) {
const dir = resolveLinkDir(p.dir, p.spec);
if (!remember(dir)) continue;
jobs.push(canGit(dir) ? { kind: "git", dir, profile: p.name } : { kind: "zip", dir, profile: p.name });
continue;
}
const dir = profilePluginDir(p.dir) || PLUGIN_ROOT;
jobs.push({ kind: "dsh", profile: p.name, spec: p.spec, dir });
remember(dir);
}
if (!jobs.length) {
jobs.push(canGit(PLUGIN_ROOT) ? { kind: "git", dir: PLUGIN_ROOT } : { kind: "zip", dir: PLUGIN_ROOT });
return jobs;
}
if (remember(PLUGIN_ROOT)) {
jobs.push(canGit(PLUGIN_ROOT) ? { kind: "git", dir: PLUGIN_ROOT } : { kind: "zip", dir: PLUGIN_ROOT });
}
return jobs;
}
function detectVia() {
if (gitOk()) {
const extra = findPurgeProfiles().some((p) => !isLinkSpec(p.spec));
return extra ? "mixed" : "git";
}
if (findPurgeProfiles().some((p) => !isLinkSpec(p.spec))) return "dsh";
if (findPurgeProfiles().length) return "dsh";
return "zip";
}
function isAbortError(e) {
const msg = String((e && e.message) || e || "");
return (e && (e.name === "AbortError" || e.name === "TimeoutError")) || /aborted|abort/i.test(msg);
}
async function fetchRes(url, ms = 20000) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ms);
const timer = setTimeout(() => {
try {
ctrl.abort("timeout");
} catch {
ctrl.abort();
}
}, ms);
try {
const res = await fetch(url, {
headers: { "user-agent": "dsh-purge-update", accept: "*/*" },
@@ -87,50 +267,58 @@ async function fetchText(url, ms = 10000) {
signal: ctrl.signal,
});
if (!res.ok) throw new Error(`http ${res.status}`);
return res.text();
return res;
} catch (e) {
if (e && e.name === "AbortError") throw new Error("GitHub 超时");
if (isAbortError(e)) throw new Error("GitHub 超时");
throw e;
} finally {
clearTimeout(timer);
}
}
async function fetchText(url, ms = 20000) {
return (await fetchRes(url, ms)).text();
}
async function fetchJson(url) {
return JSON.parse(await fetchText(url));
}
async function remotePackageVersion() {
try {
const pkg = await fetchJson(`https://raw.githubusercontent.com/${REPO}/${BRANCH}/package.json`);
return String(pkg.version || "");
} catch {
return "";
const urls = [
`https://raw.githubusercontent.com/${REPO}/${BRANCH}/package.json`,
`https://cdn.jsdelivr.net/gh/${REPO}@${BRANCH}/package.json`,
];
for (const url of urls) {
try {
const pkg = await fetchJson(url);
if (pkg && pkg.version) return String(pkg.version);
} catch {
// 换下一个源。
}
}
return "";
}
async function remoteHeadSha() {
try {
const data = await fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`);
if (data?.sha) return String(data.sha);
} catch {
// GitHub API 失败时改走 atom。
}
try {
const atom = await fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`);
const hit = atom.match(/<id>tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/);
if (hit) return hit[1];
} catch {
// 只剩版本号对比。
}
return "";
const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`)
.then((data) => (data?.sha ? String(data.sha) : ""))
.catch(() => "");
const fromAtom = fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`)
.then((atom) => {
const hit = atom.match(/<id>tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/);
return hit ? hit[1] : "";
})
.catch(() => "");
const [apiSha, atomSha] = await Promise.all([fromApi, fromAtom]);
return apiSha || atomSha || "";
}
export async function checkUpdate() {
const localVer = localVersion();
const [remoteSha, remoteVer] = await Promise.all([remoteHeadSha(), remotePackageVersion()]);
if (!remoteSha && !remoteVer) throw new Error("无法读取 GitHub master");
const gitSha = isGitCheckout(PLUGIN_ROOT) ? gitHead(PLUGIN_ROOT) : "";
const gitSha = gitOk() ? gitHead(PLUGIN_ROOT) : "";
const stamp = readStamp();
const localRev = gitSha || stamp;
let hasUpdate = false;
@@ -139,47 +327,90 @@ export async function checkUpdate() {
} else if (remoteVer && localVer && remoteVer !== localVer) {
hasUpdate = true;
} else if (remoteSha && !localRev) {
writeStamp(remoteSha);
hasUpdate = false;
// zip / dsh 安装没有 stamp,按有更新处理,拉一次与 master 对齐。
hasUpdate = true;
}
return {
const result = {
ok: true,
hasUpdate,
localVersion: localVer,
remoteVersion: remoteVer || localVer,
localSha: localRev ? localRev.slice(0, 7) : "",
remoteSha: remoteSha ? remoteSha.slice(0, 7) : "",
via: gitSha ? "git" : "zip",
via: detectVia(),
};
rememberUpdate(result);
return result;
}
function gitPull() {
execFileSync("git", ["-C", PLUGIN_ROOT, "pull", "--ff-only", "origin", BRANCH], {
function gitTrackedDirty(dir) {
try {
const out = execFileSync(
"git",
["-C", dir, "status", "--porcelain", "--untracked-files=no", "--", ...COPY_NAMES],
HIDDEN,
).trim();
return Boolean(out);
} catch {
return true;
}
}
let lastUpdate = null;
function rememberUpdate(result) {
lastUpdate = result && typeof result === "object" ? result : lastUpdate;
return lastUpdate;
}
export function lastUpdateResult() {
return lastUpdate;
}
function gitPull(dir) {
execFileSync("git", ["-C", dir, "pull", "--ff-only", "origin", BRANCH], {
...HIDDEN,
timeout: 60000,
});
}
async function installFromZip() {
function extractZip(zip, dest) {
try {
execFileSync("tar", ["-xf", zip, "-C", dest], { ...HIDDEN, timeout: 60000 });
return;
} catch {
// Windows 10+ 自带 tar;没有或失败时改 PowerShell。
}
execFileSync(
"powershell",
["-NoProfile", "-Command", "Expand-Archive -LiteralPath $env:DSH_UPD_ZIP -DestinationPath $env:DSH_UPD_DIR -Force"],
{
...HIDDEN,
timeout: 60000,
env: { ...process.env, DSH_UPD_ZIP: zip, DSH_UPD_DIR: dest },
},
);
}
async function overlayFromZip(dests) {
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 fetch(`https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`, {
headers: { "user-agent": "dsh-purge-update" },
redirect: "follow",
});
if (!res.ok) throw new Error(`zip http ${res.status}`);
const res = await fetchRes(ZIP_URL, 45000);
await fsp.writeFile(zip, Buffer.from(await res.arrayBuffer()));
execFileSync("tar", ["-xf", zip, "-C", tmp], { ...HIDDEN, timeout: 60000 });
extractZip(zip, tmp);
const names = await fsp.readdir(tmp);
const unpacked = names
.map((n) => path.join(tmp, n))
.find((p) => fs.existsSync(path.join(p, "package.json")));
if (!unpacked) throw new Error("zip 里没有 package.json");
for (const name of COPY_NAMES) {
const from = path.join(unpacked, name);
if (!fs.existsSync(from)) continue;
const to = path.join(PLUGIN_ROOT, name);
await fsp.cp(from, to, { recursive: true, force: true });
for (const dest of unique) {
for (const name of COPY_NAMES) {
const from = path.join(unpacked, name);
if (!fs.existsSync(from)) continue;
await fsp.cp(from, path.join(dest, name), { recursive: true, force: true });
}
}
try {
await fsp.rm(tmp, { recursive: true, force: true });
@@ -188,12 +419,35 @@ async function installFromZip() {
}
}
export async function applyUpdate() {
if (isGitCheckout(PLUGIN_ROOT)) gitPull();
else await installFromZip();
const sha = (await remoteHeadSha()) || gitHead(PLUGIN_ROOT);
export async function applyUpdate(jobs = planUpdates()) {
const zipDirs = [];
const vias = new Set();
for (const job of jobs) {
if (job.kind === "git") {
gitPull(job.dir);
vias.add("git");
continue;
}
if (job.kind === "dsh") {
try {
dshReinstall(job.profile, job.spec);
vias.add("dsh");
continue;
} catch {
zipDirs.push(job.dir);
}
} else {
zipDirs.push(job.dir);
}
}
if (zipDirs.length) {
await overlayFromZip(zipDirs);
vias.add("zip");
}
const sha = (await remoteHeadSha()) || (gitOk() ? gitHead(PLUGIN_ROOT) : "");
if (sha) writeStamp(sha);
return {
const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia();
return rememberUpdate({
ok: true,
applied: true,
hasUpdate: false,
@@ -202,5 +456,33 @@ export async function applyUpdate() {
localSha: sha ? String(sha).slice(0, 7) : "",
remoteSha: sha ? String(sha).slice(0, 7) : "",
needRestart: true,
};
via,
});
}
export async function autoUpdateIfNeeded() {
try {
const check = await checkUpdate();
if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" });
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)));
if (!runnable.length && dirtyGit.length) {
return rememberUpdate({
...check,
auto: true,
skipped: "dirty",
error: "本地插件文件有未提交改动,未自动覆盖",
});
}
const applied = await applyUpdate(runnable);
return rememberUpdate({ ...applied, auto: true });
} catch (e) {
return rememberUpdate({
ok: false,
auto: true,
hasUpdate: false,
error: String(e && e.message ? e.message : e),
});
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-purge",
"version": "1.0.0",
"version": "1.1.0",
"description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐",
"type": "module",
"main": "lib/index.js",