From b88706a53731bbb00d6ddb46db2babc375b9dc84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= <188421097+HunYiSage@users.noreply.github.com> Date: Sat, 19 Sep 2026 00:03:03 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.8=EF=BC=8C?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E6=8F=90=E7=A4=BA=E8=AF=8D=E5=86=85=E7=BD=AE?= =?UTF-8?q?=E8=BF=9B=E6=8F=92=E4=BB=B6=EF=BC=8C=E6=BA=90=20md=20=E4=B8=8D?= =?UTF-8?q?=E8=BF=9B=E4=BB=93=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- .gitignore | 1 + .npmignore | 2 + README.md | 33 +-- README.zh-CN.md | 34 +-- client.js | 289 ++++++++++++++++++++++- cordis.patch.yml | 5 + lib/continue-retry.js | 386 +++++++++++++++++++++++++++++++ lib/core.js | 127 +++++++++- lib/index.js | 133 ++++++++++- package.json | 6 +- scripts/embed-default-prompt.mjs | 36 +++ 11 files changed, 994 insertions(+), 58 deletions(-) create mode 100644 .npmignore create mode 100644 lib/continue-retry.js create mode 100644 scripts/embed-default-prompt.mjs diff --git a/.gitignore b/.gitignore index 7f59b8e..81209a4 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ npm-debug.log* .DS_Store _archive/ 频道推广手册/ +lib/default-prompt-inject.md diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..26d608c --- /dev/null +++ b/.npmignore @@ -0,0 +1,2 @@ +lib/default-prompt-inject.md +频道推广手册/ diff --git a/README.md b/README.md index 478bfef..e1aa30c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.7

+

Version 1.1.8

DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐ @@ -92,7 +92,7 @@ After install: 1. Fully quit and restart **the host you just installed into** (stop `dsh web`, or quit the Desktop tray and open `DSH Desktop.exe`) 2. When **Rules** appears on that host’s Settings page, click **Apply** (adding the bundle does not patch `@deepseek-ai` by itself) -3. On start the plugin auto-applies the current host and writes a default `prompt-inject.md` only if it is missing (an existing empty file means inject nothing) +3. On start the plugin auto-applies the current host and uses the built-in default prompt unless the user has saved a different one Web **Apply / Restart / Uninstall** affect Web only. Desktop **Apply / Restart / Uninstall** affect the desktop app only — they do not launch `dsh web`. @@ -228,13 +228,13 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv

🌐 Open Hub page  ·  - 🚀 Install in desktop client + 🚀 Install in desktop client

🔗 **Raw protocol URL:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.7&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.8&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz ``` **Web trigger example:** @@ -247,7 +247,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.7', + version: '1.1.8', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -266,7 +266,7 @@ export function installDshPurgeToDesktop() { **HTML link:** ```html - + 🚀 Install in desktop client ``` @@ -277,7 +277,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | Plugin id | | name | `dsh-purge` | Display name | -| version | `1.1.7` | Semver | +| version | `1.1.8` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub tarball (not `.zip`) | @@ -469,7 +469,7 @@ dsh-purge/ ├── lib/ │ ├── child-process-hide.mjs │ ├── core.js -│ ├── default-prompt-inject.md +│ ├── default-prompt-data.js │ ├── hide-console.js │ ├── identity.js │ ├── index.js @@ -494,7 +494,7 @@ Runtime user files: `$DSH_HOME/prompt-inject.md`, `$DSH_HOME/rules/`. If `DSH_HO - After restart, the **Rules** card is on the settings page. Hard-refresh (Ctrl+F5) if the client bundle is cached. - Click **Apply**, then **Restart** when prompted. Optional packages (liangshen / web-fetch) show as missing/skipped and do not block complete → restart. -- First Apply writes the built-in default into `prompt-inject.md` when the file is missing; an already-empty file is left empty. +- Until the user saves a different prompt, `prompt-inject.md` stays the built-in default. - `/purge status` prints `DSH_HOME` and the patch list. - On 0.1.5, selecting an existing workspace should restore the session — not wipe to an empty workspace. - Skipped items are expected when a target file is absent (for example #20 / #21 without `dsh-web-fetch-http`). @@ -552,7 +552,7 @@ patch not applied? ──no──> skip ├─> override shim (dsh.cmd / dsh.ps1 / unix dsh; **skip Desktop sealed host-commands bins**) ├─> scrub illegal sibling `*.dshpurge.bak` inside sealed bins (Desktop validates before plugins load) ├─> Windows: pin hide-console + child_process import hook; patch subprocess-local / doctor / market / liangshen bash - └─> if `prompt-inject.md` is missing, write the default (do not refill an empty file) + └─> if the user has not replaced the prompt, write/refresh the built-in default ``` **Override (each session):** @@ -613,6 +613,14 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change ## Changelog +### 1.1.8 + +- Default prompt is embedded in the plugin (`default-prompt-data.js`). The source `default-prompt-inject.md` is not in the repo or the package. +- Until the user saves a different prompt, the built-in default is used. Settings can restore the default. + +
+Earlier versions + ### 1.1.7 - **#25:** After the first turn, do not pin the previous full system prompt. Inject `prompt-inject.md` once; later turns leave this turn’s other sections as assembled. @@ -621,9 +629,6 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change - Desktop Apply / Restart / Uninstall only touch the running desktop install tree, not official Web / npm-global. - Desktop package root follows the running `DSH Desktop.exe` (default or custom install folder). -
-Earlier versions - ### 1.1.6 - Settings **Uninstall** asks for confirmation, restores applied patches, then removes the plugin and restarts. @@ -661,7 +666,7 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change - 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. +- **#15:** 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 diff --git a/README.zh-CN.md b/README.zh-CN.md index 55ad1db..818ddd1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.7

+

Version 1.1.8

DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐ @@ -89,7 +89,7 @@ Web 端和桌面端**分开装、分开清洗**,互不影响。 1. 完全退出并重启**刚装的那个宿主**(Web 关 `dsh web`;桌面端退出托盘再打开 `DSH Desktop.exe`) 2. 在**这个宿主**的设置页出现「规则设定」后点「应用」(只写入 profile 还不会改 `@deepseek-ai`) -3. 启动后会自动清洗当前宿主;没有 `prompt-inject.md` 时写入默认注入(已有文件不覆盖,空文件表示不注入) +3. 启动后会自动清洗当前宿主;未自行改过提示词时使用插件内置默认,只有用户自己保存过不同内容才保留 Web 的「应用 / 重启 / 卸载」只动 Web。桌面端的「应用 / 重启 / 卸载」只动桌面应用,不会去拉 `dsh web`。 @@ -225,13 +225,13 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv

🌐 打开插件市场页  ·  - 🚀 唤起客户端一键安装 + 🚀 唤起客户端一键安装

🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.7&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.8&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz ``` **网页端(前端)触发代码示例:** @@ -244,7 +244,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.7', + version: '1.1.8', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -263,7 +263,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -274,7 +274,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.7` | 语义化版本号 | +| version | `1.1.8` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub tarball(不要用 `.zip`) | @@ -466,7 +466,7 @@ dsh-purge/ ├── lib/ │ ├── child-process-hide.mjs │ ├── core.js -│ ├── default-prompt-inject.md +│ ├── default-prompt-data.js │ ├── hide-console.js │ ├── identity.js │ ├── index.js @@ -491,7 +491,7 @@ dsh-purge/ - 重启后设置页出现「规则设定」卡片(客户端半体加载成功)。有缓存时 Ctrl+F5。 - 点「应用」,进度里已应用项增加;再按提示重启,补丁进入当前进程。缺可选包(如梁神、web-fetch)时对应项显示跳过/缺失,不影响「完成 → 重启」。 -- 首次应用若尚无 `prompt-inject.md`,会写入内置默认提示词;已清空的文件不会再自动填回。 +- 未自行改过时,`prompt-inject.md` 使用插件内置默认提示词。设置页保存不同内容后才换成用户自己的。 - 聊天里 `/purge status` 能打出 `DSH_HOME` 和补丁列表。 - 0.1.5 上选已有工作区应能恢复会话,不应被清空成空工作区。 - 个别项显示跳过是正常的:例如没装 `dsh-web-fetch-http` 时 #20 / #21 会跳过。 @@ -547,7 +547,7 @@ node --test test/update-spec.test.js ├─> 覆盖 shim(dsh.cmd / dsh.ps1 / unix dsh;**跳过 Desktop host-commands 密封目录**) ├─> 清掉密封目录里误放的 sibling `*.dshpurge.bak`(Desktop 启动前校验,残留会进恢复模式) ├─> Windows:钉 hide-console + child_process 导入钩子,并修补 subprocess-local / doctor / market / 梁神 bash - └─> 若 `prompt-inject.md` 尚不存在则写入默认覆盖文本(已存在的空文件不覆盖) + └─> 未自行改过则写入/刷新内置默认提示词 ``` **覆盖(每次会话):** @@ -600,18 +600,22 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt ## 更新记录 +### 1.1.8 + +- 默认提示词打进插件(`default-prompt-data.js`),源 `default-prompt-inject.md` 不进仓库、不发包。 +- 未自行改过提示词时使用内置默认;设置页保存不同内容后才换成用户自己的,可「恢复默认」。 + +
+更早版本 + ### 1.1.7 - **#25:** 第一轮注入 `prompt-inject.md` 之后不再把上一轮整段系统提示钉回去;后续只保留本轮组装结果。 - **#26:** `dsh plugin add` / 插件内更新改用 GitHub `master.tar.gz`。`.zip` 不是 pnpm tarball,会报 `ERR_PNPM_TARBALL_DECODE_GZIP`。本地覆盖安装仍下载 zip 给 `tar` / Expand-Archive。 - - 安装文档按 **Web 端 / 桌面端** 分开写默认命令:Web 用官方 `dsh --profile web`;桌面端默认在自带终端 `dsh plugin add `。 - 桌面端清洗、重启、卸载只针对当前桌面进程的安装树,不碰官方 Web / npm-global。 - 桌面端安装目录按运行中的 `DSH Desktop.exe` 定位,默认位置或自定义目录都可以。 -
-更早版本 - ### 1.1.6 - 设置页「卸载」会弹窗确认;若已应用补丁则先还原回原版,再清除插件并重启。 @@ -648,7 +652,7 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt - 检测更新与下载分开:先查,有新版本按钮变成「更新」,版本号显示远端。 - 开机自动对照 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 段。 +- **#15**:有内容却进不了会话,是 0.1.5 `complete:true` 丢掉 section;`#41` 把注入补回 complete 段。 - **#14**:Hub `api/plugins/download` 不是 tar,安装只用 GitHub `master.zip`。 ### 1.0.0 diff --git a/client.js b/client.js index 64ead70..7245675 100644 --- a/client.js +++ b/client.js @@ -110,7 +110,9 @@ 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": "未自行改过时始终使用插件内置默认提示词。保存不同内容后才会换成你的;恢复默认可改回去。", + "btn.restoreInject": "恢复默认", + "saved.restoreInject": "已填入默认提示词,点保存写入", "skip": "跳过", "unknown": "未知", "delete": "删除", @@ -242,6 +244,20 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "rewind.once.hint": "只退当前对话上一句", "rewind.round": "回退上一轮", "rewind.round.hint": "退回上一轮主对话,本轮子代理一并去掉", + "continue.title": "失败重试 / 继续", + "continue.hint": "请求失败会自动重试;异常停止或中断可点「继续」或自动续跑。自己点停止不会自动继续。次数用完后需新开一轮。", + "continue.autoRetry": "失败自动重试", + "continue.retryMax": "重试次数", + "continue.autoContinue": "中断后自动继续", + "continue.continueMax": "继续次数", + "continue.text": "继续用语", + "saved.continue": "已保存", + "continue.label": "继续", + "continue.aria": "异常停止后继续", + "continue.busy": "继续中…", + "continue.ready": "继续(还可 {left} 次)", + "continue.limit": "已达继续上限", + "continue.fail": "继续失败: {error}", }; const en = { @@ -264,7 +280,9 @@ 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 inject file is missing. A restart writes the default prompt; an empty file means inject nothing.", + "warn.noInject": "Until you save a different prompt, the plugin keeps its built-in default. Restore default to go back.", + "btn.restoreInject": "Reset default", + "saved.restoreInject": "Default prompt loaded. Save to write.", "skip": "Skipped", "unknown": "Unknown", "delete": "Delete", @@ -396,6 +414,20 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "rewind.once.hint": "Drop the last turn of this chat", "rewind.round": "Undo last round", "rewind.round.hint": "Back to the previous main turn, including this round's subagents", + "continue.title": "Retry / Continue", + "continue.hint": "Failed requests auto-retry. After an abnormal stop or interrupt, use Continue or auto-resume. A manual stop never auto-continues. Counts reset after a completed turn.", + "continue.autoRetry": "Auto-retry on failure", + "continue.retryMax": "Retry count", + "continue.autoContinue": "Auto-continue after interrupt", + "continue.continueMax": "Continue count", + "continue.text": "Continue text", + "saved.continue": "Saved", + "continue.label": "Continue", + "continue.aria": "Continue after an abnormal stop", + "continue.busy": "Continuing…", + "continue.ready": "Continue ({left} left)", + "continue.limit": "Continue limit reached", + "continue.fail": "Continue failed: {error}", }; const THEME_KEY = "dshp-theme"; @@ -454,6 +486,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .dshp-btn-tiny{min-height:28px;padding:0 10px;font-size:12px} .dshp-field,.dshp-area{width:100%;box-sizing:border-box;font:13px/1.55 var(--dshp-mono);padding:8px 10px;background:var(--dshp-bg);color:var(--dshp-ink);border:1px solid var(--dshp-line);border-radius:8px} .dshp-field{width:auto;min-width:140px} +.dshp-cr-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:8px 0 0;font-size:13px} +.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-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} @@ -577,12 +613,115 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { }); } + function ContinueRetrySection() { + const t = useT(); + const [cfg, setCfg] = useState(null); + const [notice, setNotice] = useState({ kind: "idle", text: "" }); + const [busy, setBusy] = useState(false); + + useEffect(() => { + apiJson("/dsh-purge/continue/settings") + .then((d) => { if (d && d.ok) setCfg(d); }) + .catch(() => {}); + }, []); + + const save = (patch) => { + if (!cfg || busy) return; + const next = { ...cfg, ...patch }; + if (next.autoRetry && !(Number(next.retryMax) > 0)) next.retryMax = 3; + if (next.autoContinue && !(Number(next.continueMax) > 0)) next.continueMax = 3; + setCfg(next); + setBusy(true); + apiJson("/dsh-purge/continue/settings", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(next), + }) + .then((d) => { + if (d && d.ok) { + setCfg(d); + setNotice({ kind: "ok", text: t("saved.continue") }); + } else { + setNotice({ kind: "error", text: t("err.save", { error: (d && d.error) || "" }) }); + } + }) + .catch((e) => setNotice({ kind: "error", text: t("err.save", { error: e.message }) })) + .finally(() => setBusy(false)); + }; + + if (!cfg) return null; + return h("div", { className: "dshp-cr" }, + h("div", { className: "dshp-sub" }, + h("h4", null, t("continue.title")), + noticeNode(notice), + ), + h("p", { className: "dshp-hint", style: { margin: "0 0 4px", color: "var(--dshp-mute)", fontSize: 12 } }, t("continue.hint")), + h("div", { className: "dshp-cr-row" }, + h("label", null, + h("input", { + type: "checkbox", + checked: Boolean(cfg.autoRetry), + disabled: busy, + onChange: (e) => save({ autoRetry: e.target.checked }), + }), + t("continue.autoRetry"), + ), + h("label", null, + t("continue.retryMax"), + h("input", { + className: "dshp-field dshp-cr-num", + type: "number", + min: 0, + max: 20, + value: cfg.retryMax, + disabled: busy, + onChange: (e) => save({ retryMax: Number(e.target.value) }), + }), + ), + ), + h("div", { className: "dshp-cr-row" }, + h("label", null, + h("input", { + type: "checkbox", + checked: Boolean(cfg.autoContinue), + disabled: busy, + onChange: (e) => save({ autoContinue: e.target.checked }), + }), + t("continue.autoContinue"), + ), + h("label", null, + t("continue.continueMax"), + h("input", { + className: "dshp-field dshp-cr-num", + type: "number", + min: 0, + max: 20, + value: cfg.continueMax, + disabled: busy, + onChange: (e) => save({ continueMax: Number(e.target.value) }), + }), + ), + h("label", null, + t("continue.text"), + h("input", { + className: "dshp-field dshp-cr-text", + type: "text", + value: cfg.continueText || "", + disabled: busy, + onChange: (e) => save({ continueText: e.target.value }), + }), + ), + ), + ); + } + function PurgifySection() { const t = useT(); const tRef = useRef(t); tRef.current = t; const [state, setState] = useState(null); const [override, setOverride] = useState(""); + const [defaultOverride, setDefaultOverride] = useState(""); const [overrideLoaded, setOverrideLoaded] = useState(false); const [patchBusy, setPatchBusy] = useState(false); const [updateBusy, setUpdateBusy] = useState(false); @@ -655,7 +794,11 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { }); apiJson("/dsh-purge/override") .then((d) => { - if (d && d.ok) { setOverride(d.content || ""); setOverrideLoaded(true); } + if (d && d.ok) { + if (typeof d.defaultContent === "string") setDefaultOverride(d.defaultContent); + setOverride(d.content || d.defaultContent || ""); + setOverrideLoaded(true); + } else setNotice({ kind: "error", text: tr("err.override", { error: (d && d.error) || "" }) }); }) .catch((e) => setNotice({ kind: "error", text: tr("err.override", { error: e.message }) })); @@ -673,9 +816,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .then((r) => r.json()) .then((d) => { if (d.ok) { - if (action === "apply" && typeof d.override_content === "string") { - setOverride(d.override_content); - setOverrideLoaded(true); + if (action === "apply") { + if (typeof d.defaultContent === "string") setDefaultOverride(d.defaultContent); + if (typeof d.override_content === "string") { + setOverride(d.override_content); + setOverrideLoaded(true); + } } if (action === "apply" && d.complete === false) { const parts = []; @@ -727,6 +873,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { }) .then((r) => r.json()) .then((d) => { + if (d.ok && typeof d.content === "string") setOverride(d.content); setNotice(d.ok ? { kind: "ok", text: t("saved.override") } : { kind: "error", text: t("err.save", { error: d.error || "" }) }); @@ -735,6 +882,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .finally(() => setPatchBusy(false)); }, [override, t]); + const restoreOverride = useCallback(() => { + if (!defaultOverride) return; + setOverride(defaultOverride); + setNotice({ kind: "ok", text: t("saved.restoreInject") }); + }, [defaultOverride, t]); + const waitHostAfterUninstall = useCallback((tr) => { const started = Date.now(); const ping = () => { @@ -885,10 +1038,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { }, }, t("btn.restart")), ) : null, + // h(ContinueRetrySection, null), 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: patchBusy || !overrideLoaded, onClick: saveOverride }, t("btn.saveInject")), + h(Btn, { tiny: true, disabled: patchBusy || !overrideLoaded || !defaultOverride, onClick: restoreOverride }, t("btn.restoreInject")), ), ), h("textarea", { @@ -1265,6 +1420,11 @@ body[data-ds-dark-theme] .dshp-rewind-menu{background:var(--dsw-specific-menu,#3 .dshp-rewind-item b{font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,inherit)} .dshp-rewind-item span{color:var(--dsw-alias-label-tertiary,#9a958c);font-size:11px} body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tertiary,#a8a39a)} +.dshp-continue{appearance:none;display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 8px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary,currentColor);font:12px/1 var(--ds-font-sans,system-ui,sans-serif);cursor:pointer} +.dshp-continue:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary,currentColor)} +.dshp-continue:disabled{opacity:.4;cursor:default} +.dshp-continue.is-ready{color:var(--dsw-alias-label-primary,currentColor)} +.dshp-continue svg{display:block} `; const DRAFT_KEY = "dshp-rewind-draft:"; const ARM_KEY = "dshp-rewind-arm:"; @@ -1502,6 +1662,114 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert } } + class ContinueSafe extends Component { + constructor(p) { super(p); this.state = { failed: false }; } + static getDerivedStateFromError() { return { failed: true }; } + componentDidCatch(error) { try { console.error("[dsh-purge] continue slot:", error); } catch { /* ignore */ } } + render() { + if (this.state.failed) { + return h("button", { + type: "button", + className: "dshp-continue", + title: rewindText(translate, "continue.label", "继续"), + onMouseDown: (e) => e.preventDefault(), + onClick: async () => { + const sessionId = currentSessionId(rewindSessions); + if (!sessionId) return; + try { + const data = await apiJson("/dsh-purge/continue", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ sessionId, force: true }), + }); + if (!data || !data.ok) throw new Error((data && data.error) || "continue"); + } catch (e) { + window.alert(rewindText(translate, "continue.fail", "继续失败: {error}").replace("{error}", String((e && e.message) || e))); + } + }, + }, rewindText(translate, "continue.label", "继续")); + } + return h(ContinueButton, this.props); + } + } + + function ContinueButton(props) { + const t = props.t || translate; + const sessions = rewindSessions; + const sessionId = props.sessionId || currentSessionId(sessions); + const [busy, setBusy] = useState(false); + const [notice, setNotice] = useState(""); + const [info, setInfo] = useState(null); + + useEffect(() => { + if (!sessionId) { + setInfo(null); + return; + } + let cancelled = false; + const tick = () => { + apiJson("/dsh-purge/continue?sessionId=" + encodeURIComponent(sessionId)) + .then((data) => { if (!cancelled && data && data.ok) setInfo(data); }) + .catch(() => {}); + }; + tick(); + const timer = window.setInterval(tick, 1200); + return () => { + cancelled = true; + window.clearInterval(timer); + }; + }, [sessionId]); + + const canContinue = Boolean(info && info.canContinue); + const left = info ? Math.max(0, (info.continueMax || 0) - (info.continueUsed || 0)) : 0; + const runContinue = async () => { + if (!sessionId || busy || !canContinue) return; + setBusy(true); + setNotice(""); + try { + const data = await apiJson("/dsh-purge/continue", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ sessionId }), + }); + if (!data || !data.ok) throw new Error((data && data.error) || "continue"); + setInfo((prev) => prev ? { ...prev, ...data, canContinue: false, continueUsed: data.used } : data); + } catch (e) { + setNotice(rewindText(t, "continue.fail", "继续失败: {error}").replace("{error}", String((e && e.message) || e))); + } finally { + setBusy(false); + } + }; + + const label = busy + ? rewindText(t, "continue.busy", "继续中…") + : rewindText(t, "continue.label", "继续"); + const title = notice + || (canContinue + ? rewindText(t, "continue.ready", "继续(还可 {left} 次)").replace("{left}", String(left)) + : (info && info.reason && left <= 0 + ? rewindText(t, "continue.limit", "已达继续上限") + : rewindText(t, "continue.aria", "异常停止后继续"))); + return h("button", { + type: "button", + className: "dshp-continue" + (canContinue ? " is-ready" : ""), + title, + "aria-label": rewindText(t, "continue.aria", "异常停止后继续"), + disabled: busy || !sessionId || !canContinue, + onMouseDown: (e) => e.preventDefault(), + onClick: (e) => { + e.preventDefault(); + e.stopPropagation(); + runContinue(); + }, + }, + h("svg", { viewBox: "0 0 16 16", width: "14", height: "14", "aria-hidden": true }, + h("path", { fill: "currentColor", d: "M4.2 2.8v10.4L13 8 4.2 2.8z" }), + ), + label, + ); + } + function RewindButton(props) { const t = props.t || translate; const sessions = rewindSessions; @@ -1656,6 +1924,15 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert t: ctx.locale.bind(NS), }), }, RewindSafe)); + // ctx.slots.inject("conversation.input.right", () => ctx.slots.register({ + // name: "conversation.input.right", + // id: "dsh-purge-continue", + // order: 21, + // inject: (sessionId) => ({ + // sessionId, + // t: ctx.locale.bind(NS), + // }), + // }, ContinueSafe)); ctx.effect(() => installRewindWatch(ctx), "dsh-purge: rewind watch"); } diff --git a/cordis.patch.yml b/cordis.patch.yml index 26d1004..0c1bac0 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -16,3 +16,8 @@ verbose: false postPrompt: "" postPromptOrder: 5100 + autoRetry: true + retryMax: 3 + autoContinue: true + continueMax: 3 + continueText: "继续" diff --git a/lib/continue-retry.js b/lib/continue-retry.js new file mode 100644 index 0000000..7446df1 --- /dev/null +++ b/lib/continue-retry.js @@ -0,0 +1,386 @@ +import { promises as fsp } from "node:fs"; +import fs from "node:fs"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; + +export const DEFAULT_CONTINUE_RETRY = Object.freeze({ + autoRetry: true, + retryMax: 3, + autoContinue: true, + continueMax: 3, + continueText: "继续", +}); + +const PERMANENT_CODES = new Set([ + "AUTH", + "UNAUTHORIZED", + "FORBIDDEN", + "INVALID", + "INVALID_REQUEST", + "QUOTA", + "BILLING", + "MODEL_NOT_FOUND", + "CONTEXT_OVERFLOW", + "CONTEXT_LENGTH", +]); + +const ABNORMAL_KINDS = new Set(["error", "aborted", "interrupted", "max-tokens"]); + +export function clampCount(value, fallback = 3) { + const n = Number(value); + if (!Number.isFinite(n)) return fallback; + return Math.max(0, Math.min(20, Math.trunc(n))); +} + +export function normalizeConfig(raw = {}) { + const src = raw && typeof raw === "object" ? raw : {}; + const retryMax = clampCount(src.retryMax, DEFAULT_CONTINUE_RETRY.retryMax); + const continueMax = clampCount(src.continueMax, DEFAULT_CONTINUE_RETRY.continueMax); + const text = typeof src.continueText === "string" ? src.continueText.trim() : ""; + return { + autoRetry: src.autoRetry !== false && retryMax > 0, + retryMax, + autoContinue: src.autoContinue !== false && continueMax > 0, + continueMax, + continueText: text || DEFAULT_CONTINUE_RETRY.continueText, + }; +} + +export function settingsPath(dshHome) { + return path.join(dshHome, "dsh-purge", "continue-retry.json"); +} + +export function loadSettings(dshHome) { + const fp = settingsPath(dshHome); + try { + if (!fs.existsSync(fp)) return {}; + const parsed = JSON.parse(fs.readFileSync(fp, "utf8")); + return parsed && typeof parsed === "object" ? parsed : {}; + } catch { + return {}; + } +} + +export async function saveSettings(dshHome, raw) { + const next = normalizeConfig(raw); + const dir = path.dirname(settingsPath(dshHome)); + await fsp.mkdir(dir, { recursive: true }); + await fsp.writeFile(settingsPath(dshHome), `${JSON.stringify(next, null, 2)}\n`, "utf8"); + return next; +} + +export function mergeConfig(pluginCfg, saved) { + return normalizeConfig({ ...DEFAULT_CONTINUE_RETRY, ...pluginCfg, ...saved }); +} + +export function lastTurnEnd(events) { + const list = Array.isArray(events) ? events : []; + for (let i = list.length - 1; i >= 0; i -= 1) { + const event = list[i]; + if (event?.type === "turn/end") return event; + } + return null; +} + +export function isUserAbort(reason) { + if (!reason || reason.kind !== "aborted") return false; + const cause = reason.reason; + if (cause === "user" || cause === "cancel") return true; + if (cause && typeof cause === "object") { + return cause.kind === "user" || cause.kind === "cancel"; + } + return false; +} + +export function isAbnormalReason(reason) { + return Boolean(reason && ABNORMAL_KINDS.has(reason.kind)); +} + +export function shouldAutoContinue(reason) { + return isAbnormalReason(reason) && !isUserAbort(reason); +} + +export function isPermanentFailure(code) { + return PERMANENT_CODES.has(String(code || "").toUpperCase()); +} + +export function shouldAutoRetry(failure, signal) { + if (signal?.aborted) return false; + return !isPermanentFailure(failure?.code); +} + +export function makeContinueMessage(text) { + const body = String(text || DEFAULT_CONTINUE_RETRY.continueText).trim() || DEFAULT_CONTINUE_RETRY.continueText; + return { + id: `dsh-purge-continue-${randomUUID()}`, + role: "user", + content: [{ type: "text", text: body }], + source: { + kind: "plugin", + plugin: "dsh-purge", + form: "notice", + summary: "continue", + }, + }; +} + +export function createTracker() { + const bySession = new Map(); + + function slot(sessionId) { + const id = String(sessionId || ""); + if (!id) return null; + let cur = bySession.get(id); + if (!cur) { + cur = { retry: 0, continue: 0, lastContinueSeq: 0, lastRetryKey: "" }; + bySession.set(id, cur); + } + return cur; + } + + return { + retryUsed(sessionId) { + return slot(sessionId)?.retry || 0; + }, + continueUsed(sessionId) { + return slot(sessionId)?.continue || 0; + }, + lastContinueSeq(sessionId) { + return slot(sessionId)?.lastContinueSeq || 0; + }, + takeRetry(sessionId, key, max) { + const cur = slot(sessionId); + if (!cur || max <= 0) return false; + if (key && cur.lastRetryKey === key) return false; + if (cur.retry >= max) return false; + cur.retry += 1; + cur.lastRetryKey = key || ""; + return true; + }, + takeContinue(sessionId, seq, max) { + const cur = slot(sessionId); + if (!cur || max <= 0) return false; + if (seq && cur.lastContinueSeq === seq) return false; + if (cur.continue >= max) return false; + cur.continue += 1; + cur.lastContinueSeq = seq || 0; + return true; + }, + refundContinue(sessionId) { + const cur = slot(sessionId); + if (!cur || cur.continue <= 0) return; + cur.continue -= 1; + cur.lastContinueSeq = 0; + }, + reset(sessionId) { + const id = String(sessionId || ""); + if (id) bySession.delete(id); + }, + resetIfCompleted(sessionId, reason) { + if (reason?.kind === "completed" || reason?.kind === "blocked") this.reset(sessionId); + }, + }; +} + +function service(ctx, name) { + if (!ctx || typeof ctx.get !== "function") return undefined; + try { + return ctx.get(name); + } catch { + return undefined; + } +} + +export function sessionEventsOf(agent) { + const session = agent?.session; + if (!session) return []; + try { + if (typeof session.snapshotEvents === "function") return session.snapshotEvents() || []; + } catch { /* ignore */ } + try { + if (Array.isArray(session.events)) return session.events; + } catch { /* ignore */ } + return []; +} + +export function inspectTurn(events) { + const end = lastTurnEnd(events); + const reason = end?.data?.reason || null; + return { + seq: end?.seq || 0, + turn: end?.data?.turn || 0, + reason, + abnormal: isAbnormalReason(reason), + userAbort: isUserAbort(reason), + auto: shouldAutoContinue(reason), + }; +} + +export function resolveAgent(ctx, sessionId) { + const agents = service(ctx, "agents"); + if (!agents || typeof agents.get !== "function") return null; + try { + return agents.get(sessionId) || null; + } catch { + return null; + } +} + +export function hasFreshHumanTurn(events) { + const list = Array.isArray(events) ? events : []; + const end = lastTurnEnd(list); + const after = end ? list.filter((event) => (event?.seq || 0) > end.seq) : list; + return after.some((event) => { + if (event?.type !== "user/message") return false; + return event.data?.source?.kind !== "plugin"; + }); +} + +export function inboxBusy(agent) { + try { + const inbox = agent?.inbox; + if (!inbox) return false; + if (typeof inbox.hasPending === "function" && inbox.hasPending()) return true; + if (typeof inbox.size === "number" && inbox.size > 0) return true; + if (typeof inbox.length === "number" && inbox.length > 0) return true; + } catch { /* ignore */ } + return false; +} + +export function sendContinue(agent, text) { + if (!agent || typeof agent.followup !== "function") { + return { ok: false, error: "当前会话没有可续跑的 agent" }; + } + try { + agent.followup(makeContinueMessage(text)); + return { ok: true }; + } catch (e) { + return { ok: false, error: String(e && e.message ? e.message : e) }; + } +} + +export function installContinueRetry(ctx, options = {}) { + const getConfig = typeof options.getConfig === "function" ? options.getConfig : () => normalizeConfig(options.config); + const tracker = options.tracker || createTracker(); + const timers = new Set(); + + function sessionIdOf(agent) { + return agent?.id || agent?.session?.id || ""; + } + + function schedule(fn, ms) { + const timer = setTimeout(() => { + timers.delete(timer); + fn(); + }, ms); + timers.add(timer); + return timer; + } + + function listen(event, handler) { + if (typeof ctx?.on !== "function") return null; + try { + return ctx.on(event, handler, { global: true }); + } catch { + try { + return ctx.on(event, handler); + } catch { + return null; + } + } + } + + function maybeAutoContinue(agent) { + const cfg = getConfig(); + if (!cfg.autoContinue) return; + const id = sessionIdOf(agent); + if (!id) return; + if (agent.status === "running" || inboxBusy(agent)) return; + const events = sessionEventsOf(agent); + if (hasFreshHumanTurn(events)) return; + const info = inspectTurn(events); + if (!info.auto) return; + if (!tracker.takeContinue(id, info.seq, cfg.continueMax)) return; + const sent = sendContinue(agent, cfg.continueText); + if (!sent.ok) tracker.refundContinue(id); + } + + const offError = listen("agent/request-error", async (payload, next) => { + const downstream = typeof next === "function" ? await next() : undefined; + if (downstream?.kind === "retry") return downstream; + const cfg = getConfig(); + if (!cfg.autoRetry) return downstream; + if (!shouldAutoRetry(payload?.failure, payload?.signal)) return downstream; + const id = sessionIdOf(payload?.agent); + const key = `${payload?.turn || 0}:${payload?.step || 0}:${payload?.failure?.code || ""}`; + if (!tracker.takeRetry(id, key, cfg.retryMax)) return downstream; + return { kind: "retry" }; + }); + + const offStatus = listen("agent/status", (payload) => { + const agent = payload?.agent; + if (!agent) return; + const id = sessionIdOf(agent); + const events = sessionEventsOf(agent); + if (payload.status === "running" && hasFreshHumanTurn(events)) tracker.reset(id); + if (payload.status !== "idle") return; + tracker.resetIfCompleted(id, inspectTurn(events).reason); + schedule(() => maybeAutoContinue(agent), 280); + }); + + return { + tracker, + inspect(agentOrEvents) { + const events = Array.isArray(agentOrEvents) ? agentOrEvents : sessionEventsOf(agentOrEvents); + return inspectTurn(events); + }, + continueNow(agent, opts = {}) { + const cfg = getConfig(); + const id = sessionIdOf(agent); + const info = inspectTurn(sessionEventsOf(agent)); + if (!info.abnormal && !opts.force) return { ok: false, error: "当前不是中断或失败状态" }; + const max = opts.ignoreBudget ? Number.MAX_SAFE_INTEGER : cfg.continueMax; + if (info.seq && tracker.lastContinueSeq(id) === info.seq) { + return { ok: false, error: "这一轮已经在继续" }; + } + if (!tracker.takeContinue(id, info.seq, max)) { + return { ok: false, error: `继续次数已用完(${cfg.continueMax})` }; + } + const sent = sendContinue(agent, opts.text || cfg.continueText); + if (!sent.ok) { + tracker.refundContinue(id); + return sent; + } + return { ok: true, used: tracker.continueUsed(id), max: cfg.continueMax, reason: info.reason?.kind || "" }; + }, + status(agent) { + const cfg = getConfig(); + const id = sessionIdOf(agent); + const info = inspectTurn(sessionEventsOf(agent)); + return { + ok: true, + sessionId: id, + canContinue: Boolean( + info.abnormal + && tracker.continueUsed(id) < cfg.continueMax + && tracker.lastContinueSeq(id) !== info.seq + ), + reason: info.reason?.kind || "", + userAbort: info.userAbort, + retryUsed: tracker.retryUsed(id), + continueUsed: tracker.continueUsed(id), + retryMax: cfg.retryMax, + continueMax: cfg.continueMax, + autoRetry: cfg.autoRetry, + autoContinue: cfg.autoContinue, + continueText: cfg.continueText, + }; + }, + dispose() { + for (const timer of timers) clearTimeout(timer); + timers.clear(); + try { offError?.(); } catch { /* ignore */ } + try { offStatus?.(); } catch { /* ignore */ } + }, + }; +} diff --git a/lib/core.js b/lib/core.js index bd46dd7..24583f9 100644 --- a/lib/core.js +++ b/lib/core.js @@ -13,6 +13,7 @@ import { revertHideConsoleFromBin, } from "./hide-console.js"; import * as desktop from "./desktop.js"; +import { defaultPromptInjectText } from "./default-prompt-data.js"; import { adapterFor, detectSurface } from "./surface.js"; const isWindows = process.platform === "win32"; @@ -4217,41 +4218,143 @@ const DEFAULT_OVERRIDE_FILE = path.join( "default-prompt-inject.md", ); +export function normalizeOverride(text) { + return String(text ?? "").replace(/\r\n/g, "\n").trim(); +} + +export function hashOverride(text) { + return createHash("sha256").update(normalizeOverride(text), "utf8").digest("hex"); +} + export function defaultOverrideText() { - return fs.readFileSync(DEFAULT_OVERRIDE_FILE, "utf8"); + try { + if (fs.existsSync(DEFAULT_OVERRIDE_FILE)) { + return fs.readFileSync(DEFAULT_OVERRIDE_FILE, "utf8"); + } + } catch { + /* use embedded seed */ + } + return defaultPromptInjectText(); +} + +export function defaultOverrideHash() { + return hashOverride(defaultOverrideText()); } export const OVERRIDE_TEXT = defaultOverrideText(); +export function overrideStatePath(dshHome) { + return path.join(dshHome, "dsh-purge", "override-state.json"); +} + +export async function readOverrideState(dshHome) { + const fp = overrideStatePath(dshHome); + try { + const raw = JSON.parse(await fsp.readFile(fp, "utf8")); + return raw && typeof raw === "object" ? raw : {}; + } catch { + return {}; + } +} + +export async function writeOverrideState(dshHome, state) { + const fp = overrideStatePath(dshHome); + await fsp.mkdir(path.dirname(fp), { recursive: true }); + await fsp.writeFile(fp, `${JSON.stringify(state, null, 2)}\n`, "utf8"); +} + +export async function markOverrideCustomized(dshHome, customized, text) { + await writeOverrideState(dshHome, { + customized: Boolean(customized), + hash: hashOverride(text ?? defaultOverrideText()), + seedHash: defaultOverrideHash(), + updatedAt: new Date().toISOString(), + }); +} + +export async function isUserCustomizedOverride(dshHome) { + const fp = findOverrideFile(dshHome); + let disk = ""; + if (fs.existsSync(fp)) { + try { + disk = await loadText(fp); + } catch { + disk = ""; + } + } + if (!normalizeOverride(disk)) return false; + if (hashOverride(disk) === defaultOverrideHash()) return false; + const state = await readOverrideState(dshHome); + if (state.customized === false) return false; + if (state.customized === true) return true; + return true; +} + export async function overrideStatus(dshHome) { const fp = findOverrideFile(dshHome); if (!fs.existsSync(fp)) return "missing"; try { const content = await loadText(fp); - if (content.trim().length === 0) return "empty"; - return "edited"; + if (!normalizeOverride(content)) return "empty"; + if (await isUserCustomizedOverride(dshHome)) return "edited"; + return "default"; } catch { return "missing"; } } +/** 设置页:未自行改过就显示并维持内置默认提示词。 */ +export async function readOverrideForUi(dshHome) { + const fp = findOverrideFile(dshHome); + const defaultContent = defaultOverrideText(); + const exists = fs.existsSync(fp); + let disk = ""; + if (exists) { + try { + disk = await loadText(fp); + } catch { + disk = ""; + } + } + const customized = await isUserCustomizedOverride(dshHome); + return { + path: fp, + exists, + empty: !normalizeOverride(disk), + customized, + usingDefault: !customized, + content: customized ? disk : defaultContent, + defaultContent, + }; +} + export async function installOverride(dshHome, force = false) { const fp = findOverrideFile(dshHome); await fsp.mkdir(dshHome, { recursive: true }); - if (fs.existsSync(fp) && !force) { - const existing = await loadText(fp); - // 空文件就是空:不注入、不改写。 - return existing.trim().length > 0 ? "exists" : "empty"; - } - await fsp.writeFile(fp, defaultOverrideText(), "utf8"); + if (!force && await isUserCustomizedOverride(dshHome)) return "exists"; + const bundled = defaultOverrideText(); + await fsp.writeFile(fp, bundled, "utf8"); + await markOverrideCustomized(dshHome, false, bundled); return "wrote"; } +export async function saveOverrideContent(dshHome, content) { + const bundled = defaultOverrideText(); + const incoming = typeof content === "string" ? content : ""; + const customized = Boolean(normalizeOverride(incoming)) + && normalizeOverride(incoming) !== normalizeOverride(bundled); + const toWrite = customized ? incoming : bundled; + const fp = findOverrideFile(dshHome); + await fsp.mkdir(dshHome, { recursive: true }); + await fsp.writeFile(fp, toWrite, "utf8"); + await markOverrideCustomized(dshHome, customized, toWrite); + return { path: fp, customized, content: toWrite }; +} + export async function ensureOverrideContent(dshHome, force = false) { const installed = await installOverride(dshHome, force); - const fp = findOverrideFile(dshHome); - const content = fs.existsSync(fp) ? await loadText(fp) : ""; - return { path: fp, content, installed }; + const ui = await readOverrideForUi(dshHome); + return { ...ui, installed }; } export function editOverride(dshHome) { diff --git a/lib/index.js b/lib/index.js index 1c7ed55..918750b 100644 --- a/lib/index.js +++ b/lib/index.js @@ -12,6 +12,7 @@ import { shouldInjectPrompt, } from "./identity.js"; import * as rewind from "./rewind.js"; +import * as continueRetry from "./continue-retry.js"; import * as uninstaller from "./uninstall.js"; export const name = "dsh-purge"; @@ -28,6 +29,11 @@ const DEFAULTS = { postPrompt: "", postPromptOrder: 5100, verbose: false, + autoRetry: true, + retryMax: 3, + autoContinue: true, + continueMax: 3, + continueText: "继续", }; const log = (config, ...args) => { @@ -35,6 +41,33 @@ const log = (config, ...args) => { }; let webTreeReady = false; +let continueRuntime = null; +let savedContinueSettings = {}; +let continuePluginCfg = { ...DEFAULTS }; + +function currentContinueConfig() { + return continueRetry.mergeConfig(continuePluginCfg, savedContinueSettings); +} + +function continueStatusPayload(ctx, sessionId) { + const cfg = currentContinueConfig(); + const agent = sessionId ? continueRetry.resolveAgent(ctx, sessionId) : null; + if (agent && continueRuntime) return continueRuntime.status(agent); + return { + ok: true, + sessionId: sessionId || "", + canContinue: false, + reason: "", + userAbort: false, + retryUsed: 0, + continueUsed: 0, + retryMax: cfg.retryMax, + continueMax: cfg.continueMax, + autoRetry: cfg.autoRetry, + autoContinue: cfg.autoContinue, + continueText: cfg.continueText, + }; +} function watchWebTreeReady(ctx) { // 必须挂在 connection 上再 await,与官方打印 URL 同一时刻。 @@ -531,6 +564,12 @@ export function apply(ctx, config) { const injectFile = core.findOverrideFile(core.findDshHome()); registerPromptSections(ctx, cfg, injectFile); + // 继续/重试先关掉,需要时再打开下面这段。 + // continuePluginCfg = cfg; + // savedContinueSettings = continueRetry.loadSettings(core.findDshHome()); + // try { continueRuntime?.dispose?.(); } catch { /* ignore */ } + // continueRuntime = continueRetry.installContinueRetry(ctx, { getConfig: currentContinueConfig }); + const commands = ctx.get?.("commands"); if (commands) { commands.register({ @@ -570,6 +609,19 @@ export function apply(ctx, config) { }; }, }); + // commands.register({ + // name: "continue", + // description: "异常停止或中断后发送继续(计入继续次数)", + // input: { hint: "继续当前异常停止的会话" }, + // handler: async (invocation) => { + // const sessionId = rewind.invocationSessionId(invocation); + // const agent = continueRetry.resolveAgent(ctx, sessionId); + // if (!agent || !continueRuntime) return { kind: "error", text: "当前会话不能继续" }; + // const result = continueRuntime.continueNow(agent); + // if (!result.ok) return { kind: "error", text: result.error }; + // return { kind: "success", text: `已发送继续(${result.used}/${result.max})` }; + // }, + // }); } if (ctx.tools) { @@ -784,6 +836,73 @@ function installWebServer(ctx, cfg) { response.end(); }, }, "dsh-purge: rewind"); + // host.webServer.register({ + // kind: "exact", + // path: "/dsh-purge/continue", + // handler: async (request, response) => { + // if (request.method === "GET") { + // try { + // const url = new URL(request.url, "http://127.0.0.1"); + // const sessionId = String(url.searchParams.get("sessionId") || "").trim(); + // sendJson(response, 200, continueStatusPayload(ctx, sessionId)); + // } catch (e) { + // sendJson(response, 500, { ok: false, error: String(e) }); + // } + // return; + // } + // if (request.method === "POST") { + // try { + // const body = await readJsonBody(request); + // const sessionId = String(body?.sessionId || "").trim(); + // if (!sessionId) { + // sendJson(response, 400, { ok: false, error: "需要 sessionId" }); + // return; + // } + // const agent = continueRetry.resolveAgent(ctx, sessionId); + // if (!agent || !continueRuntime) { + // sendJson(response, 409, { ok: false, error: "当前会话不能继续" }); + // return; + // } + // const result = continueRuntime.continueNow(agent, { force: Boolean(body?.force) }); + // sendJson(response, result.ok ? 200 : 409, result); + // } catch (e) { + // sendJson(response, 500, { ok: false, error: String(e) }); + // } + // return; + // } + // response.writeHead(405, { allow: "GET, POST" }); + // response.end(); + // }, + // }, "dsh-purge: continue"); + // host.webServer.register({ + // kind: "exact", + // path: "/dsh-purge/continue/settings", + // handler: async (request, response) => { + // if (request.method === "GET") { + // try { + // sendJson(response, 200, { ok: true, ...currentContinueConfig() }); + // } catch (e) { + // sendJson(response, 500, { ok: false, error: String(e) }); + // } + // return; + // } + // if (request.method === "POST") { + // try { + // const body = await readJsonBody(request); + // savedContinueSettings = await continueRetry.saveSettings(core.findDshHome(), { + // ...currentContinueConfig(), + // ...body, + // }); + // sendJson(response, 200, { ok: true, ...currentContinueConfig() }); + // } catch (e) { + // sendJson(response, 500, { ok: false, error: String(e) }); + // } + // return; + // } + // response.writeHead(405, { allow: "GET, POST" }); + // response.end(); + // }, + // }, "dsh-purge: continue settings"); host.webServer.register({ kind: "exact", path: "/dsh-purge/update", @@ -919,11 +1038,8 @@ function installWebServer(ctx, cfg) { handler: async (request, response) => { if (request.method === "GET") { try { - const dshHome = core.findDshHome(); - const fp = core.findOverrideFile(dshHome); - let content = ""; - if (fs.existsSync(fp)) content = await fsp.readFile(fp, "utf8"); - sendJson(response, 200, { ok: true, exists: fs.existsSync(fp), content, path: fp }); + const ui = await core.ensureOverrideContent(core.findDshHome(), false); + sendJson(response, 200, { ok: true, ...ui }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } @@ -937,11 +1053,8 @@ function installWebServer(ctx, cfg) { sendJson(response, 400, { ok: false, error: "content must be a string" }); return; } - const dshHome = core.findDshHome(); - const fp = core.findOverrideFile(dshHome); - await fsp.mkdir(dshHome, { recursive: true }); - await fsp.writeFile(fp, content, "utf8"); - sendJson(response, 200, { ok: true, path: fp }); + const saved = await core.saveOverrideContent(core.findDshHome(), content); + sendJson(response, 200, { ok: true, ...saved }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } diff --git a/package.json b/package.json index 93b6760..928bab5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.7", + "version": "1.1.8", "description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐", "type": "module", "main": "lib/index.js", @@ -16,6 +16,7 @@ }, "files": [ "lib", + "!lib/default-prompt-inject.md", "bin", "docs", "client.js", @@ -25,6 +26,9 @@ "README.zh-CN.md", "LICENSE" ], + "scripts": { + "embed-prompt": "node scripts/embed-default-prompt.mjs" + }, "license": "MIT", "keywords": [ "dsh", diff --git a/scripts/embed-default-prompt.mjs b/scripts/embed-default-prompt.mjs new file mode 100644 index 0000000..01f837f --- /dev/null +++ b/scripts/embed-default-prompt.mjs @@ -0,0 +1,36 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const src = path.join(root, "lib", "default-prompt-inject.md"); +const dest = path.join(root, "lib", "default-prompt-data.js"); + +if (!fs.existsSync(src)) { + throw new Error(`missing ${src} — keep the local markdown, then run this script`); +} + +const text = fs.readFileSync(src, "utf8"); +if (!text.trim()) { + throw new Error("default-prompt-inject.md is empty"); +} + +const normalized = text.replace(/\r\n/g, "\n").trim(); +const hash = createHash("sha256").update(normalized, "utf8").digest("hex"); +const b64 = Buffer.from(text, "utf8").toString("base64"); + +const out = `// Generated by scripts/embed-default-prompt.mjs. Do not edit. +// Local source lib/default-prompt-inject.md is gitignored and not published. + +export const DEFAULT_PROMPT_INJECT_SHA256 = ${JSON.stringify(hash)}; + +const DEFAULT_PROMPT_INJECT_B64 = ${JSON.stringify(b64)}; + +export function defaultPromptInjectText() { + return Buffer.from(DEFAULT_PROMPT_INJECT_B64, "base64").toString("utf8"); +} +`; + +fs.writeFileSync(dest, out, "utf8"); +process.stdout.write(`wrote ${path.relative(root, dest)} sha256=${hash} bytes=${text.length}\n`);