Compare commits

..
4 Commits
13 changed files with 1031 additions and 94 deletions

No files matched your search

+1
View File
@@ -4,3 +4,4 @@ npm-debug.log*
.DS_Store .DS_Store
_archive/ _archive/
频道推广手册/ 频道推广手册/
lib/default-prompt-inject.md
+2
View File
@@ -0,0 +1,2 @@
lib/default-prompt-inject.md
频道推广手册/
+35 -26
View File
@@ -4,7 +4,7 @@
<h1 align="center">dsh-purge</h1> <h1 align="center">dsh-purge</h1>
<p align="center"><strong>Version 1.1.7</strong></p> <p align="center"><strong>Version 1.1.8</strong></p>
<p align="center"> <p align="center">
<em>DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐</em> <em>DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐</em>
@@ -92,16 +92,18 @@ 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`) 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) 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`. Web **Apply / Restart / Uninstall** affect Web only. Desktop **Apply / Restart / Uninstall** affect the desktop app only — they do not launch `dsh web`.
> 🌐 **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`) > 🌐 **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`)
>
> `dsh plugin add <url>` hands the URL to pnpm as a **remote tarball**. Use GitHub `master.tar.gz`. A `.zip` archive is ZIP, not gzip, and fails with `ERR_PNPM_TARBALL_DECODE_GZIP` ([#26](https://github.com/YuJunZhiXue/dsh-purge/issues/26)).
### Web (default) ### Web (default)
```sh ```sh
dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
If this directory is already a clone: If this directory is already a clone:
@@ -117,7 +119,7 @@ Then stop `dsh web`, start it again, and **Apply** on the Web Settings page. If
Open community [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop) and run this in the **built-in terminal** (`dsh` is the desktop wrapper; default profile is `desktop`): Open community [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop) and run this in the **built-in terminal** (`dsh` is the desktop wrapper; default profile is `desktop`):
```sh ```sh
dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
Do not use official `dsh plugin --profile desktop` on PATH (it is rejected). Do not use `dsh://` (that is the official EXE). Do not use official `dsh plugin --profile desktop` on PATH (it is rejected). Do not use `dsh://` (that is the official EXE).
@@ -127,7 +129,7 @@ Then quit the tray, reopen `DSH Desktop.exe`, and **Apply** on the **desktop** S
From a system terminal, use the app’s own CLI. Locate `DSH Desktop.exe` from the running process or the default install locations: From a system terminal, use the app’s own CLI. Locate `DSH Desktop.exe` from the running process or the default install locations:
```powershell ```powershell
$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" $zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz"
$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) $exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path)
if (-not $exe) { if (-not $exe) {
$exe = @( $exe = @(
@@ -146,7 +148,7 @@ $env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop"
& $exe --expose-internals $cli plugin add $zip & $exe --expose-internals $cli plugin add $zip
``` ```
For a custom install folder, set `$exe` to `DSH Desktop.exe` in that folder. The zip is the default source so a local path with spaces cannot split the command. For a custom install folder, set `$exe` to `DSH Desktop.exe` in that folder. The tarball URL is the default source so a local path with spaces cannot split the command.
### Hand this to an AI (install only) ### Hand this to an AI (install only)
@@ -164,7 +166,7 @@ Install the DeepSeek Harness plugin `dsh-purge`. Confirm the host first and inst
If `dsh` is not on PATH, tell the user and stop. If `dsh` is not on PATH, tell the user and stop.
```sh ```sh
dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
If this directory is already a clone, use `dsh plugin --profile web add .`. If this directory is already a clone, use `dsh plugin --profile web add .`.
@@ -176,13 +178,13 @@ Do not use official `dsh plugin --profile desktop` on PATH. Do not use `dsh://`.
Default: already inside Desktop’s built-in terminal: Default: already inside Desktop’s built-in terminal:
```sh ```sh
dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
From a system terminal: use the running `DSH Desktop` process Path, or the default locations `%LOCALAPPDATA%\Programs\DSH Desktop\DSH Desktop.exe`, `%ProgramFiles%\DSH Desktop\DSH Desktop.exe`. Do not scan the whole disk. Then: From a system terminal: use the running `DSH Desktop` process Path, or the default locations `%LOCALAPPDATA%\Programs\DSH Desktop\DSH Desktop.exe`, `%ProgramFiles%\DSH Desktop\DSH Desktop.exe`. Do not scan the whole disk. Then:
```powershell ```powershell
$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" $zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz"
$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) $exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path)
if (-not $exe) { if (-not $exe) {
$exe = @( $exe = @(
@@ -204,7 +206,7 @@ $env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop"
**Official Harness desktop EXE** **Official Harness desktop EXE**
```sh ```sh
dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
After the command finishes, tell the user to fully quit and restart the host they just installed into, then **Apply** on that host’s Settings page. Do not Apply Web from Desktop or Desktop from Web. Then stop. After the command finishes, tell the user to fully quit and restart the host they just installed into, then **Apply** on that host’s Settings page. Do not Apply Web from Desktop or Desktop from Web. Then stop.
@@ -220,19 +222,19 @@ If the **official DeepSeek Harness desktop client (EXE)** is installed, the butt
CLI equivalent: CLI equivalent:
```sh ```sh
dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
<p align="center"> <p align="center">
<a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 Open Hub page</strong></a> <a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 Open Hub page</strong></a>
&nbsp;·&nbsp; &nbsp;·&nbsp;
<a href="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.zip"><strong>🚀 Install in desktop client</strong></a> <a href="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"><strong>🚀 Install in desktop client</strong></a>
</p> </p>
🔗 **Raw protocol URL:** 🔗 **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.zip 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:** **Web trigger example:**
@@ -245,10 +247,10 @@ export function installDshPurgeToDesktop() {
const params = new URLSearchParams({ const params = new URLSearchParams({
id: 'dsh-purge', id: 'dsh-purge',
name: 'dsh-purge', name: 'dsh-purge',
version: '1.1.7', version: '1.1.8',
repo: 'YuJunZhiXue/dsh-purge', repo: 'YuJunZhiXue/dsh-purge',
permissions: '系统提示词注入, 本机补丁, 设置页', permissions: '系统提示词注入, 本机补丁, 设置页',
downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz',
}); });
const deepLink = `dsh://plugin/install?${params.toString()}`; const deepLink = `dsh://plugin/install?${params.toString()}`;
@@ -264,7 +266,7 @@ export function installDshPurgeToDesktop() {
**HTML link:** **HTML link:**
```html ```html
<a href="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.zip"> <a href="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">
🚀 Install in desktop client 🚀 Install in desktop client
</a> </a>
``` ```
@@ -275,10 +277,10 @@ export function installDshPurgeToDesktop() {
|---|---|---| |---|---|---|
| id | `dsh-purge` | Plugin id | | id | `dsh-purge` | Plugin id |
| name | `dsh-purge` | Display name | | name | `dsh-purge` | Display name |
| version | `1.1.7` | Semver | | version | `1.1.8` | Semver |
| repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo |
| permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions |
| downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | Zip URL | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub tarball (not `.zip`) |
### Manual install ### Manual install
@@ -467,7 +469,7 @@ dsh-purge/
├── lib/ ├── lib/
│ ├── child-process-hide.mjs │ ├── child-process-hide.mjs
│ ├── core.js │ ├── core.js
│ ├── default-prompt-inject.md │ ├── default-prompt-data.js
│ ├── hide-console.js │ ├── hide-console.js
│ ├── identity.js │ ├── identity.js
│ ├── index.js │ ├── index.js
@@ -492,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. - 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. - 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. - `/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. - 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`). - Skipped items are expected when a target file is absent (for example #20 / #21 without `dsh-web-fetch-http`).
@@ -533,6 +535,7 @@ node --check lib/host.js
node --check lib/rewind.js node --check lib/rewind.js
node --check client.js node --check client.js
node --test test/surface.test.js node --test test/surface.test.js
node --test test/update-spec.test.js
``` ```
--- ---
@@ -549,7 +552,7 @@ patch not applied? ──no──> skip
├─> override shim (dsh.cmd / dsh.ps1 / unix dsh; **skip Desktop sealed host-commands bins**) ├─> 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) ├─> 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 ├─> 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):** **Override (each session):**
@@ -610,15 +613,21 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change
## Changelog ## Changelog
### 1.1.7 ### 1.1.8
- Install docs split **Web / Desktop** defaults: Web uses official `dsh --profile web`; Desktop uses the built-in terminal `dsh plugin add <zip>`. - Until the user saves a different prompt, the built-in default is used. Settings can restore the default.
- 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).
<details> <details>
<summary>Earlier versions</summary> <summary>Earlier versions</summary>
### 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.
- **#26:** `dsh plugin add` / in-app update use GitHub `master.tar.gz`. A `.zip` URL is not a pnpm tarball (`ERR_PNPM_TARBALL_DECODE_GZIP`). Local overlay still downloads the zip for `tar` / Expand-Archive.
- Install docs split **Web / Desktop** defaults: Web uses official `dsh --profile web`; Desktop uses the built-in terminal `dsh plugin add <tar.gz>`.
- 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).
### 1.1.6 ### 1.1.6
- Settings **Uninstall** asks for confirmation, restores applied patches, then removes the plugin and restarts. - Settings **Uninstall** asks for confirmation, restores applied patches, then removes the plugin and restarts.
@@ -656,7 +665,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. - 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. - 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. - **#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. - **#14:** Hub `api/plugins/download` is not a tarball; install from GitHub `master.zip` only.
### 1.0.0 ### 1.0.0
+35 -26
View File
@@ -4,7 +4,7 @@
<h1 align="center">dsh-purge</h1> <h1 align="center">dsh-purge</h1>
<p align="center"><strong>Version 1.1.7</strong></p> <p align="center"><strong>Version 1.1.8</strong></p>
<p align="center"> <p align="center">
<em>DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐</em> <em>DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐</em>
@@ -89,16 +89,18 @@ Web 端和桌面端**分开装、分开清洗**,互不影响。
1. 完全退出并重启**刚装的那个宿主**(Web 关 `dsh web`;桌面端退出托盘再打开 `DSH Desktop.exe`) 1. 完全退出并重启**刚装的那个宿主**(Web 关 `dsh web`;桌面端退出托盘再打开 `DSH Desktop.exe`)
2. 在**这个宿主**的设置页出现「规则设定」后点「应用」(只写入 profile 还不会改 `@deepseek-ai`) 2. 在**这个宿主**的设置页出现「规则设定」后点「应用」(只写入 profile 还不会改 `@deepseek-ai`)
3. 启动后会自动清洗当前宿主;没有 `prompt-inject.md` 时写入默认注入(已有文件不覆盖,空文件表示不注入) 3. 启动后会自动清洗当前宿主;未自行改过提示词时使用插件内置默认,只有用户自己保存过不同内容才保留
Web 的「应用 / 重启 / 卸载」只动 Web。桌面端的「应用 / 重启 / 卸载」只动桌面应用,不会去拉 `dsh web`。 Web 的「应用 / 重启 / 卸载」只动 Web。桌面端的「应用 / 重启 / 卸载」只动桌面应用,不会去拉 `dsh web`。
> 🌐 **插件生态市场**:[DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge)(只看介绍;**不要**用 `deepseek.stream/api/plugins/download?...`,那个地址不是 pnpm 能解的 tar,会报 `ERR_PNPM_TARBALL_EXTRACT`) > 🌐 **插件生态市场**:[DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge)(只看介绍;**不要**用 `deepseek.stream/api/plugins/download?...`,那个地址不是 pnpm 能解的 tar,会报 `ERR_PNPM_TARBALL_EXTRACT`)
>
> `dsh plugin add <url>` 会把地址交给 pnpm 当 **远程 tarball**。请用 GitHub 的 `master.tar.gz`。`.zip` 是 ZIP 不是 gzip,会报 `ERR_PNPM_TARBALL_DECODE_GZIP`([#26](https://github.com/YuJunZhiXue/dsh-purge/issues/26))。
### Web 端(默认) ### Web 端(默认)
```sh ```sh
dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
当前目录已是本仓库时: 当前目录已是本仓库时:
@@ -114,7 +116,7 @@ dsh plugin --profile web add .
打开社区 [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop),在**自带终端**里执行(这里的 `dsh` 是桌面包装脚本,默认 profile 就是 `desktop`): 打开社区 [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop),在**自带终端**里执行(这里的 `dsh` 是桌面包装脚本,默认 profile 就是 `desktop`):
```sh ```sh
dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
不要用 PATH 上的官方 `dsh plugin --profile desktop`(会被拒绝)。不要用 `dsh://`(那是官方 EXE)。 不要用 PATH 上的官方 `dsh plugin --profile desktop`(会被拒绝)。不要用 `dsh://`(那是官方 EXE)。
@@ -124,7 +126,7 @@ dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/maste
从系统终端安装时,用桌面端自带 CLI。按正在运行的进程、默认安装位置定位 `DSH Desktop.exe`: 从系统终端安装时,用桌面端自带 CLI。按正在运行的进程、默认安装位置定位 `DSH Desktop.exe`:
```powershell ```powershell
$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" $zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz"
$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) $exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path)
if (-not $exe) { if (-not $exe) {
$exe = @( $exe = @(
@@ -143,7 +145,7 @@ $env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop"
& $exe --expose-internals $cli plugin add $zip & $exe --expose-internals $cli plugin add $zip
``` ```
自定义安装目录时,把 `$exe` 换成该目录下的 `DSH Desktop.exe`。默认用 zip,避免本地路径空格把命令拆开。 自定义安装目录时,把 `$exe` 换成该目录下的 `DSH Desktop.exe`。默认用 tar.gz 地址,避免本地路径空格把命令拆开。
### 交给 AI 安装(只装插件) ### 交给 AI 安装(只装插件)
@@ -161,7 +163,7 @@ $env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop"
`dsh` 不在 PATH 就告诉用户后停止。 `dsh` 不在 PATH 就告诉用户后停止。
```sh ```sh
dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
当前目录已是本仓库时改用 `dsh plugin --profile web add .`。 当前目录已是本仓库时改用 `dsh plugin --profile web add .`。
@@ -173,13 +175,13 @@ dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/re
默认:已在桌面端自带终端里时直接跑: 默认:已在桌面端自带终端里时直接跑:
```sh ```sh
dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
从系统终端安装时:用正在运行的 `DSH Desktop` 进程 Path,或默认位置 `%LOCALAPPDATA%\Programs\DSH Desktop\DSH Desktop.exe`、`%ProgramFiles%\DSH Desktop\DSH Desktop.exe`。不要全盘扫描。然后: 从系统终端安装时:用正在运行的 `DSH Desktop` 进程 Path,或默认位置 `%LOCALAPPDATA%\Programs\DSH Desktop\DSH Desktop.exe`、`%ProgramFiles%\DSH Desktop\DSH Desktop.exe`。不要全盘扫描。然后:
```powershell ```powershell
$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" $zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz"
$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) $exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path)
if (-not $exe) { if (-not $exe) {
$exe = @( $exe = @(
@@ -201,7 +203,7 @@ $env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop"
**官方 Harness 桌面 EXE** **官方 Harness 桌面 EXE**
```sh ```sh
dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
命令结束后,提醒:完全退出并重启刚装的那个宿主,再在该宿主设置页点「应用」。Web 和桌面端不要交叉点应用。然后停止。 命令结束后,提醒:完全退出并重启刚装的那个宿主,再在该宿主设置页点「应用」。Web 和桌面端不要交叉点应用。然后停止。
@@ -217,19 +219,19 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv
命令行等价: 命令行等价:
```sh ```sh
dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz
``` ```
<p align="center"> <p align="center">
<a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 打开插件市场页</strong></a> <a href="https://deepseek.stream/plugins/dsh-purge"><strong>🌐 打开插件市场页</strong></a>
&nbsp;·&nbsp; &nbsp;·&nbsp;
<a href="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.zip"><strong>🚀 唤起客户端一键安装</strong></a> <a href="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"><strong>🚀 唤起客户端一键安装</strong></a>
</p> </p>
🔗 **原生协议链接:** 🔗 **原生协议链接:**
``` ```
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.zip 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
``` ```
**网页端(前端)触发代码示例:** **网页端(前端)触发代码示例:**
@@ -242,10 +244,10 @@ export function installDshPurgeToDesktop() {
const params = new URLSearchParams({ const params = new URLSearchParams({
id: 'dsh-purge', id: 'dsh-purge',
name: 'dsh-purge', name: 'dsh-purge',
version: '1.1.7', version: '1.1.8',
repo: 'YuJunZhiXue/dsh-purge', repo: 'YuJunZhiXue/dsh-purge',
permissions: '系统提示词注入, 本机补丁, 设置页', permissions: '系统提示词注入, 本机补丁, 设置页',
downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz',
}); });
const deepLink = `dsh://plugin/install?${params.toString()}`; const deepLink = `dsh://plugin/install?${params.toString()}`;
@@ -261,7 +263,7 @@ export function installDshPurgeToDesktop() {
**HTML 静态链接方式:** **HTML 静态链接方式:**
```html ```html
<a href="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.zip"> <a href="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">
🚀 唤起客户端一键安装 🚀 唤起客户端一键安装
</a> </a>
``` ```
@@ -272,10 +274,10 @@ export function installDshPurgeToDesktop() {
|---|---|---| |---|---|---|
| id | `dsh-purge` | 插件唯一标识符 | | id | `dsh-purge` | 插件唯一标识符 |
| name | `dsh-purge` | 插件展示名称 | | name | `dsh-purge` | 插件展示名称 |
| version | `1.1.7` | 语义化版本号 | | version | `1.1.8` | 语义化版本号 |
| repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 |
| permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 |
| downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | zip 下载直链 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub tarball(不要用 `.zip`) |
### 手动配置安装 ### 手动配置安装
@@ -464,7 +466,7 @@ dsh-purge/
├── lib/ ├── lib/
│ ├── child-process-hide.mjs │ ├── child-process-hide.mjs
│ ├── core.js │ ├── core.js
│ ├── default-prompt-inject.md │ ├── default-prompt-data.js
│ ├── hide-console.js │ ├── hide-console.js
│ ├── identity.js │ ├── identity.js
│ ├── index.js │ ├── index.js
@@ -489,7 +491,7 @@ dsh-purge/
- 重启后设置页出现「规则设定」卡片(客户端半体加载成功)。有缓存时 Ctrl+F5。 - 重启后设置页出现「规则设定」卡片(客户端半体加载成功)。有缓存时 Ctrl+F5。
- 点「应用」,进度里已应用项增加;再按提示重启,补丁进入当前进程。缺可选包(如梁神、web-fetch)时对应项显示跳过/缺失,不影响「完成 → 重启」。 - 点「应用」,进度里已应用项增加;再按提示重启,补丁进入当前进程。缺可选包(如梁神、web-fetch)时对应项显示跳过/缺失,不影响「完成 → 重启」。
- 首次应用若尚无 `prompt-inject.md`,会写入内置默认提示词;已清空的文件不会再自动填回。 - 未自行改过时,`prompt-inject.md` 使用插件内置默认提示词。设置页保存不同内容后才换成用户自己的。
- 聊天里 `/purge status` 能打出 `DSH_HOME` 和补丁列表。 - 聊天里 `/purge status` 能打出 `DSH_HOME` 和补丁列表。
- 0.1.5 上选已有工作区应能恢复会话,不应被清空成空工作区。 - 0.1.5 上选已有工作区应能恢复会话,不应被清空成空工作区。
- 个别项显示跳过是正常的:例如没装 `dsh-web-fetch-http` 时 #20 / #21 会跳过。 - 个别项显示跳过是正常的:例如没装 `dsh-web-fetch-http` 时 #20 / #21 会跳过。
@@ -528,6 +530,7 @@ node --check lib/index.js
node --check lib/core.js node --check lib/core.js
node --check lib/rewind.js node --check lib/rewind.js
node --check client.js node --check client.js
node --test test/update-spec.test.js
``` ```
--- ---
@@ -544,7 +547,7 @@ node --check client.js
├─> 覆盖 shim(dsh.cmd / dsh.ps1 / unix dsh;**跳过 Desktop host-commands 密封目录**) ├─> 覆盖 shim(dsh.cmd / dsh.ps1 / unix dsh;**跳过 Desktop host-commands 密封目录**)
├─> 清掉密封目录里误放的 sibling `*.dshpurge.bak`(Desktop 启动前校验,残留会进恢复模式) ├─> 清掉密封目录里误放的 sibling `*.dshpurge.bak`(Desktop 启动前校验,残留会进恢复模式)
├─> Windows:钉 hide-console + child_process 导入钩子,并修补 subprocess-local / doctor / market / 梁神 bash ├─> Windows:钉 hide-console + child_process 导入钩子,并修补 subprocess-local / doctor / market / 梁神 bash
└─> 若 `prompt-inject.md` 尚不存在则写入默认覆盖文本(已存在的空文件不覆盖) └─> 未自行改过则写入/刷新内置默认提示词
``` ```
**覆盖(每次会话):** **覆盖(每次会话):**
@@ -597,15 +600,21 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt
## 更新记录 ## 更新记录
### 1.1.7 ### 1.1.8
- 安装文档按 **Web 端 / 桌面端** 分开写默认命令:Web 用官方 `dsh --profile web`;桌面端默认在自带终端 `dsh plugin add <zip>`。 - 未自行改过提示词时使用内置默认;设置页保存不同内容后才换成用户自己的,可「恢复默认」。
- 桌面端清洗、重启、卸载只针对当前桌面进程的安装树,不碰官方 Web / npm-global。
- 桌面端安装目录按运行中的 `DSH Desktop.exe` 定位,默认位置或自定义目录都可以。
<details> <details>
<summary>更早版本</summary> <summary>更早版本</summary>
### 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 <zip>`。
- 桌面端清洗、重启、卸载只针对当前桌面进程的安装树,不碰官方 Web / npm-global。
- 桌面端安装目录按运行中的 `DSH Desktop.exe` 定位,默认位置或自定义目录都可以。
### 1.1.6 ### 1.1.6
- 设置页「卸载」会弹窗确认;若已应用补丁则先还原回原版,再清除插件并重启。 - 设置页「卸载」会弹窗确认;若已应用补丁则先还原回原版,再清除插件并重启。
@@ -642,7 +651,7 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt
- 检测更新与下载分开:先查,有新版本按钮变成「更新」,版本号显示远端。 - 检测更新与下载分开:先查,有新版本按钮变成「更新」,版本号显示远端。
- 开机自动对照 GitHub `master` 并下载。`dsh plugin add`(zip / github)走官方 CLI;没 git 下 `master.zip` 覆盖。git 仓库本地有未提交改动时不自动覆盖。 - 开机自动对照 GitHub `master` 并下载。`dsh plugin add`(zip / github)走官方 CLI;没 git 下 `master.zip` 覆盖。git 仓库本地有未提交改动时不自动覆盖。
- **#16**:`#26` 不再对 YAML 用无缩进 identity 替换;apply 重写 `prefix`/`text` 缩进,cordis 预设能挂载。 - **#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`。 - **#14**:Hub `api/plugins/download` 不是 tar,安装只用 GitHub `master.zip`。
### 1.0.0 ### 1.0.0
+283 -6
View File
@@ -110,7 +110,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"apply.hint": "待应用=原文还在。跳过=没装或官方已改写,再点也不会变。", "apply.hint": "待应用=原文还在。跳过=没装或官方已改写,再点也不会变。",
"warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。", "warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。",
"warn.noRoot.desktop": "未定位到当前桌面应用里的 @deepseek-ai。请退出托盘后重新打开 DSH Desktop.exe,再在桌面端设置页点「应用」。安装目录不限盘符。", "warn.noRoot.desktop": "未定位到当前桌面应用里的 @deepseek-ai。请退出托盘后重新打开 DSH Desktop.exe,再在桌面端设置页点「应用」。安装目录不限盘符。",
"warn.noInject": "注入文件还不存在。重启后会写入默认提示词;空文件表示不注入。", "warn.noInject": "未自行改过时始终使用插件内置默认提示词。保存不同内容后才会换成你的;恢复默认可改回去。",
"btn.restoreInject": "恢复默认",
"saved.restoreInject": "已填入默认提示词,点保存写入",
"skip": "跳过", "skip": "跳过",
"unknown": "未知", "unknown": "未知",
"delete": "删除", "delete": "删除",
@@ -242,6 +244,20 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"rewind.once.hint": "只退当前对话上一句", "rewind.once.hint": "只退当前对话上一句",
"rewind.round": "回退上一轮", "rewind.round": "回退上一轮",
"rewind.round.hint": "退回上一轮主对话,本轮子代理一并去掉", "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 = { 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.", "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": "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.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", "skip": "Skipped",
"unknown": "Unknown", "unknown": "Unknown",
"delete": "Delete", "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.once.hint": "Drop the last turn of this chat",
"rewind.round": "Undo last round", "rewind.round": "Undo last round",
"rewind.round.hint": "Back to the previous main turn, including this round's subagents", "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"; 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-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,.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-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-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: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} .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() { function PurgifySection() {
const t = useT(); const t = useT();
const tRef = useRef(t); const tRef = useRef(t);
tRef.current = t; tRef.current = t;
const [state, setState] = useState(null); const [state, setState] = useState(null);
const [override, setOverride] = useState(""); const [override, setOverride] = useState("");
const [defaultOverride, setDefaultOverride] = useState("");
const [overrideLoaded, setOverrideLoaded] = useState(false); const [overrideLoaded, setOverrideLoaded] = useState(false);
const [patchBusy, setPatchBusy] = useState(false); const [patchBusy, setPatchBusy] = useState(false);
const [updateBusy, setUpdateBusy] = useState(false); const [updateBusy, setUpdateBusy] = useState(false);
@@ -655,7 +794,11 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
}); });
apiJson("/dsh-purge/override") apiJson("/dsh-purge/override")
.then((d) => { .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) || "" }) }); else setNotice({ kind: "error", text: tr("err.override", { error: (d && d.error) || "" }) });
}) })
.catch((e) => setNotice({ kind: "error", text: tr("err.override", { error: e.message }) })); .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((r) => r.json())
.then((d) => { .then((d) => {
if (d.ok) { if (d.ok) {
if (action === "apply" && typeof d.override_content === "string") { if (action === "apply") {
setOverride(d.override_content); if (typeof d.defaultContent === "string") setDefaultOverride(d.defaultContent);
setOverrideLoaded(true); if (typeof d.override_content === "string") {
setOverride(d.override_content);
setOverrideLoaded(true);
}
} }
if (action === "apply" && d.complete === false) { if (action === "apply" && d.complete === false) {
const parts = []; const parts = [];
@@ -727,6 +873,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
}) })
.then((r) => r.json()) .then((r) => r.json())
.then((d) => { .then((d) => {
if (d.ok && typeof d.content === "string") setOverride(d.content);
setNotice(d.ok setNotice(d.ok
? { kind: "ok", text: t("saved.override") } ? { kind: "ok", text: t("saved.override") }
: { kind: "error", text: t("err.save", { error: d.error || "" }) }); : { kind: "error", text: t("err.save", { error: d.error || "" }) });
@@ -735,6 +882,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
.finally(() => setPatchBusy(false)); .finally(() => setPatchBusy(false));
}, [override, t]); }, [override, t]);
const restoreOverride = useCallback(() => {
if (!defaultOverride) return;
setOverride(defaultOverride);
setNotice({ kind: "ok", text: t("saved.restoreInject") });
}, [defaultOverride, t]);
const waitHostAfterUninstall = useCallback((tr) => { const waitHostAfterUninstall = useCallback((tr) => {
const started = Date.now(); const started = Date.now();
const ping = () => { const ping = () => {
@@ -885,10 +1038,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
}, },
}, t("btn.restart")), }, t("btn.restart")),
) : null, ) : null,
// h(ContinueRetrySection, null),
h("div", { className: "dshp-sub" }, h("div", { className: "dshp-sub" },
h("h4", null, t("override.title")), h("h4", null, t("override.title")),
h("div", { className: "dshp-row", style: { margin: 0 } }, h("div", { className: "dshp-row", style: { margin: 0 } },
h(Btn, { kind: "primary", tiny: true, disabled: patchBusy || !overrideLoaded, onClick: saveOverride }, t("btn.saveInject")), 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", { 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 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} .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)} 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 DRAFT_KEY = "dshp-rewind-draft:";
const ARM_KEY = "dshp-rewind-arm:"; 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) { function RewindButton(props) {
const t = props.t || translate; const t = props.t || translate;
const sessions = rewindSessions; 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), t: ctx.locale.bind(NS),
}), }),
}, RewindSafe)); }, 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"); ctx.effect(() => installRewindWatch(ctx), "dsh-purge: rewind watch");
} }
+5
View File
@@ -16,3 +16,8 @@
verbose: false verbose: false
postPrompt: "" postPrompt: ""
postPromptOrder: 5100 postPromptOrder: 5100
autoRetry: true
retryMax: 3
autoContinue: true
continueMax: 3
continueText: "继续"
+386
View File
@@ -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 */ }
},
};
}
+115 -12
View File
@@ -13,6 +13,7 @@ import {
revertHideConsoleFromBin, revertHideConsoleFromBin,
} from "./hide-console.js"; } from "./hide-console.js";
import * as desktop from "./desktop.js"; import * as desktop from "./desktop.js";
import { defaultPromptInjectText } from "./default-prompt-data.js";
import { adapterFor, detectSurface } from "./surface.js"; import { adapterFor, detectSurface } from "./surface.js";
const isWindows = process.platform === "win32"; const isWindows = process.platform === "win32";
@@ -4217,41 +4218,143 @@ const DEFAULT_OVERRIDE_FILE = path.join(
"default-prompt-inject.md", "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() { 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 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) { export async function overrideStatus(dshHome) {
const fp = findOverrideFile(dshHome); const fp = findOverrideFile(dshHome);
if (!fs.existsSync(fp)) return "missing"; if (!fs.existsSync(fp)) return "missing";
try { try {
const content = await loadText(fp); const content = await loadText(fp);
if (content.trim().length === 0) return "empty"; if (!normalizeOverride(content)) return "empty";
return "edited"; if (await isUserCustomizedOverride(dshHome)) return "edited";
return "default";
} catch { } catch {
return "missing"; 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) { export async function installOverride(dshHome, force = false) {
const fp = findOverrideFile(dshHome); const fp = findOverrideFile(dshHome);
await fsp.mkdir(dshHome, { recursive: true }); await fsp.mkdir(dshHome, { recursive: true });
if (fs.existsSync(fp) && !force) { if (!force && await isUserCustomizedOverride(dshHome)) return "exists";
const existing = await loadText(fp); const bundled = defaultOverrideText();
// 空文件就是空:不注入、不改写。 await fsp.writeFile(fp, bundled, "utf8");
return existing.trim().length > 0 ? "exists" : "empty"; await markOverrideCustomized(dshHome, false, bundled);
}
await fsp.writeFile(fp, defaultOverrideText(), "utf8");
return "wrote"; 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) { export async function ensureOverrideContent(dshHome, force = false) {
const installed = await installOverride(dshHome, force); const installed = await installOverride(dshHome, force);
const fp = findOverrideFile(dshHome); const ui = await readOverrideForUi(dshHome);
const content = fs.existsSync(fp) ? await loadText(fp) : ""; return { ...ui, installed };
return { path: fp, content, installed };
} }
export function editOverride(dshHome) { export function editOverride(dshHome) {
-6
View File
@@ -188,14 +188,12 @@ function normalizeRewriteOptions(fallbackInject, options) {
fallbackInject: typeof fallbackInject.fallbackInject === "string" ? fallbackInject.fallbackInject : "", fallbackInject: typeof fallbackInject.fallbackInject === "string" ? fallbackInject.fallbackInject : "",
dropMnemon: fallbackInject.dropMnemon !== false, dropMnemon: fallbackInject.dropMnemon !== false,
dropPurgeAfterFold: fallbackInject.dropPurgeAfterFold !== false, dropPurgeAfterFold: fallbackInject.dropPurgeAfterFold !== false,
pinPersonaText: typeof fallbackInject.pinPersonaText === "string" ? fallbackInject.pinPersonaText : "",
}; };
} }
return { return {
fallbackInject: typeof fallbackInject === "string" ? fallbackInject : "", fallbackInject: typeof fallbackInject === "string" ? fallbackInject : "",
dropMnemon: options?.dropMnemon !== false, dropMnemon: options?.dropMnemon !== false,
dropPurgeAfterFold: options?.dropPurgeAfterFold !== false, dropPurgeAfterFold: options?.dropPurgeAfterFold !== false,
pinPersonaText: typeof options?.pinPersonaText === "string" ? options.pinPersonaText : "",
}; };
} }
@@ -224,10 +222,6 @@ function foldInjectIntoPersona(sections, injectText) {
export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) { export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) {
if (!assembled || !Array.isArray(assembled.sections)) return assembled; if (!assembled || !Array.isArray(assembled.sections)) return assembled;
const opts = normalizeRewriteOptions(fallbackInject, options); const opts = normalizeRewriteOptions(fallbackInject, options);
if (opts.pinPersonaText) {
assembled.sections = [{ name: "deployment:persona-prefix", text: opts.pinPersonaText }];
return assembled;
}
const rest = []; const rest = [];
const purge = []; const purge = [];
for (const section of assembled.sections) { for (const section of assembled.sections) {
+123 -13
View File
@@ -7,12 +7,12 @@ import * as rules from "./rules.js";
import * as updater from "./update.js"; import * as updater from "./update.js";
import { import {
GLOBAL_PROMPT_ORDER, GLOBAL_PROMPT_ORDER,
existingSystemPrompt,
isMnemonPluginMessage, isMnemonPluginMessage,
rewritePromptAssembly, rewritePromptAssembly,
shouldInjectPrompt, shouldInjectPrompt,
} from "./identity.js"; } from "./identity.js";
import * as rewind from "./rewind.js"; import * as rewind from "./rewind.js";
import * as continueRetry from "./continue-retry.js";
import * as uninstaller from "./uninstall.js"; import * as uninstaller from "./uninstall.js";
export const name = "dsh-purge"; export const name = "dsh-purge";
@@ -29,6 +29,11 @@ const DEFAULTS = {
postPrompt: "", postPrompt: "",
postPromptOrder: 5100, postPromptOrder: 5100,
verbose: false, verbose: false,
autoRetry: true,
retryMax: 3,
autoContinue: true,
continueMax: 3,
continueText: "继续",
}; };
const log = (config, ...args) => { const log = (config, ...args) => {
@@ -36,6 +41,33 @@ const log = (config, ...args) => {
}; };
let webTreeReady = false; 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) { function watchWebTreeReady(ctx) {
// 必须挂在 connection 上再 await,与官方打印 URL 同一时刻。 // 必须挂在 connection 上再 await,与官方打印 URL 同一时刻。
@@ -209,14 +241,12 @@ function installIdentityOverride(ctx, config = {}) {
const hook = async (_assembly, context, next) => { const hook = async (_assembly, context, next) => {
const inject = config.enabled === false ? "" : readInjectFallback(); const inject = config.enabled === false ? "" : readInjectFallback();
const allow = config.enabled !== false && shouldInjectPrompt(context, config.injectOnce !== false, inject); const allow = config.enabled !== false && shouldInjectPrompt(context, config.injectOnce !== false, inject);
const pin = !allow && existingSystemPrompt(context);
return assembleState.run({ allow }, async () => { return assembleState.run({ allow }, async () => {
const assembled = typeof next === "function" ? await next() : _assembly; const assembled = typeof next === "function" ? await next() : _assembly;
return rewritePromptAssembly(assembled, { return rewritePromptAssembly(assembled, {
fallbackInject: allow ? inject : "", fallbackInject: allow ? inject : "",
dropMnemon: config.stripMnemon !== false, dropMnemon: config.stripMnemon !== false,
dropPurgeAfterFold: true, dropPurgeAfterFold: true,
pinPersonaText: pin,
}); });
}); });
}; };
@@ -534,6 +564,12 @@ export function apply(ctx, config) {
const injectFile = core.findOverrideFile(core.findDshHome()); const injectFile = core.findOverrideFile(core.findDshHome());
registerPromptSections(ctx, cfg, injectFile); 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"); const commands = ctx.get?.("commands");
if (commands) { if (commands) {
commands.register({ commands.register({
@@ -573,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) { if (ctx.tools) {
@@ -787,6 +836,73 @@ function installWebServer(ctx, cfg) {
response.end(); response.end();
}, },
}, "dsh-purge: rewind"); }, "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({ host.webServer.register({
kind: "exact", kind: "exact",
path: "/dsh-purge/update", path: "/dsh-purge/update",
@@ -922,11 +1038,8 @@ function installWebServer(ctx, cfg) {
handler: async (request, response) => { handler: async (request, response) => {
if (request.method === "GET") { if (request.method === "GET") {
try { try {
const dshHome = core.findDshHome(); const ui = await core.ensureOverrideContent(core.findDshHome(), false);
const fp = core.findOverrideFile(dshHome); sendJson(response, 200, { ok: true, ...ui });
let content = "";
if (fs.existsSync(fp)) content = await fsp.readFile(fp, "utf8");
sendJson(response, 200, { ok: true, exists: fs.existsSync(fp), content, path: fp });
} catch (e) { } catch (e) {
sendJson(response, 500, { ok: false, error: String(e) }); sendJson(response, 500, { ok: false, error: String(e) });
} }
@@ -940,11 +1053,8 @@ function installWebServer(ctx, cfg) {
sendJson(response, 400, { ok: false, error: "content must be a string" }); sendJson(response, 400, { ok: false, error: "content must be a string" });
return; return;
} }
const dshHome = core.findDshHome(); const saved = await core.saveOverrideContent(core.findDshHome(), content);
const fp = core.findOverrideFile(dshHome); sendJson(response, 200, { ok: true, ...saved });
await fsp.mkdir(dshHome, { recursive: true });
await fsp.writeFile(fp, content, "utf8");
sendJson(response, 200, { ok: true, path: fp });
} catch (e) { } catch (e) {
sendJson(response, 500, { ok: false, error: String(e) }); sendJson(response, 500, { ok: false, error: String(e) });
} }
+5 -4
View File
@@ -11,6 +11,7 @@ import { cliInvocation } from "./desktop.js";
const REPO = "YuJunZhiXue/dsh-purge"; const REPO = "YuJunZhiXue/dsh-purge";
const BRANCH = "master"; const BRANCH = "master";
const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`; const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`;
export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.tar.gz`;
const GITHUB_SPEC = `github:${REPO}#${BRANCH}`; const GITHUB_SPEC = `github:${REPO}#${BRANCH}`;
const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), ".."); const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
const COPY_NAMES = [ const COPY_NAMES = [
@@ -204,15 +205,15 @@ export function runDshPlugin(profile, args) {
}); });
} }
function addSpecFor(spec) { export function pluginAddSpec(spec) {
const s = String(spec || ""); const s = String(spec || "");
if (/\.zip(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return ZIP_URL; if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return TARBALL_URL;
if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC; if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC;
return ""; return "";
} }
function dshReinstall(profile, spec) { function dshReinstall(profile, spec) {
const addSpec = addSpecFor(spec); const addSpec = pluginAddSpec(spec);
if (addSpec) { if (addSpec) {
runDshPlugin(profile, ["add", "--force", addSpec]); runDshPlugin(profile, ["add", "--force", addSpec]);
return; return;
@@ -220,7 +221,7 @@ function dshReinstall(profile, spec) {
try { try {
runDshPlugin(profile, ["update", "dsh-purge"]); runDshPlugin(profile, ["update", "dsh-purge"]);
} catch { } catch {
runDshPlugin(profile, ["add", "--force", ZIP_URL]); runDshPlugin(profile, ["add", "--force", TARBALL_URL]);
} }
} }
+5 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "dsh-purge", "name": "dsh-purge",
"version": "1.1.7", "version": "1.1.8",
"description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐", "description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐",
"type": "module", "type": "module",
"main": "lib/index.js", "main": "lib/index.js",
@@ -16,6 +16,7 @@
}, },
"files": [ "files": [
"lib", "lib",
"!lib/default-prompt-inject.md",
"bin", "bin",
"docs", "docs",
"client.js", "client.js",
@@ -25,6 +26,9 @@
"README.zh-CN.md", "README.zh-CN.md",
"LICENSE" "LICENSE"
], ],
"scripts": {
"embed-prompt": "node scripts/embed-default-prompt.mjs"
},
"license": "MIT", "license": "MIT",
"keywords": [ "keywords": [
"dsh", "dsh",
+36
View File
@@ -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`);