From b84582e17c7ef29b30ed24f93573148e32537f06 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: Fri, 18 Sep 2026 18:26:11 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.7=EF=BC=8CWeb?= =?UTF-8?q?=20/=20=E6=A1=8C=E9=9D=A2=E7=AB=AF=E5=88=86=E5=BC=80=E5=AE=89?= =?UTF-8?q?=E8=A3=85=E5=B9=B6=E8=B7=9F=E9=9A=8F=E5=BD=93=E5=89=8D=E6=A1=8C?= =?UTF-8?q?=E9=9D=A2=E7=9B=AE=E5=BD=95=E6=B8=85=E6=B4=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- README.md | 244 ++++++++++++++++------ README.zh-CN.md | 240 +++++++++++++++------- bin/dsh-purge.js | 2 + client.js | 69 ++++++- lib/core.js | 227 +++++++++++++-------- lib/desktop.js | 449 +++++++++++++++++++++++++++++++++++++++++ lib/host.js | 28 +++ lib/index.js | 108 +++------- lib/restart-desktop.js | 123 +++++++++++ lib/surface.js | 72 +++++++ lib/uninstall.js | 32 +-- lib/update.js | 20 ++ lib/web.js | 97 +++++++++ package.json | 4 +- 14 files changed, 1370 insertions(+), 345 deletions(-) create mode 100644 lib/desktop.js create mode 100644 lib/host.js create mode 100644 lib/restart-desktop.js create mode 100644 lib/surface.js create mode 100644 lib/web.js diff --git a/README.md b/README.md index db1e905..6b02cf8 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.6

+

Version 1.1.7

DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐ @@ -29,7 +29,7 @@ Channel t.me/LLM_PoJia

-> Aligned with **dsh 0.1.5-rc.1** (Node.js **≥18**; Windows no-flash import hooks need **Node ≥22** `registerHooks`, older Node still gets file-level `windowsHide` patches). On other versions, unmatched originals stay pending or skipped. Nothing is rewritten blindly. +> Aligned with **dsh 0.1.5-rc.2** (Node.js **≥18**; Windows no-flash import hooks need **Node ≥22** `registerHooks`, older Node still gets file-level `windowsHide` patches). On other versions, unmatched originals stay pending or skipped. Nothing is rewritten blindly. > > Also accepts the 0.1.2 community `dsh-persona text` field and `dsh-mnemon` v0 session `summary`. After install you still need **Apply + restart**. @@ -80,11 +80,75 @@ This is a local Harness plugin. It is not a public scanner and not an attack kit ## ⚡ Install -Web and desktop install the same plugin into different profiles. After install you **must fully quit and restart** DeepSeek Harness so the **Rules** card appears. Then **Apply** — adding the bundle does not patch `@deepseek-ai` packages by itself. +Web and Desktop are **installed and purged separately**. They do not touch each other. + +| Host | Profile | Default install | +|---|---|---| +| **Web** (official `dsh web`) | `web` | Official `dsh` on PATH | +| **Desktop** (community [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop)) | `desktop` | `dsh` inside the app’s built-in terminal (not official `dsh` on PATH) | +| Official Harness desktop EXE | `default` | Official `dsh`, or `dsh://` below | + +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) + +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`) -### Method 1: Hand this to an AI (install only) +### Web (default) + +```sh +dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +``` + +If this directory is already a clone: + +```sh +dsh plugin --profile web add . +``` + +Then stop `dsh web`, start it again, and **Apply** on the Web Settings page. If `dsh` is not on PATH, install the official CLI or use **Manual install** below. + +### Desktop (default) + +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 +dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +``` + +Do not use official `dsh plugin --profile desktop` on PATH (it is rejected). Do not use `dsh://` (that is the official EXE). + +Then quit the tray, reopen `DSH Desktop.exe`, and **Apply** on the **desktop** Settings page. + +From a system terminal, use the app’s own CLI. Locate `DSH Desktop.exe` from the running process or the default install locations: + +```powershell +$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" +$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) +if (-not $exe) { + $exe = @( + "$env:LOCALAPPDATA\Programs\DSH Desktop\DSH Desktop.exe", + "$env:ProgramFiles\DSH Desktop\DSH Desktop.exe", + "${env:ProgramFiles(x86)}\DSH Desktop\DSH Desktop.exe" + ) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $exe) { throw "DSH Desktop.exe not found. Start the app, or set `$exe` to the exe in the install folder." } +$cli = @( + (Join-Path (Split-Path $exe) "resources\app\lib\desktop-cli.js"), + (Join-Path (Split-Path $exe) "resources\app.asar.unpacked\lib\desktop-cli.js") +) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +$env:ELECTRON_RUN_AS_NODE = "1" +$env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop" +& $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. + +### Hand this to an AI (install only) Paste the block below to a local coding assistant and ask it to install the plugin. @@ -93,48 +157,82 @@ Paste the block below to a local coding assistant and ask it to install the plug -Install the DeepSeek Harness plugin `dsh-purge` with the official CLI. Run only the commands below. Do not search the disk, do not read or edit other files, do not apply settings, and do not restart the app. +Install the DeepSeek Harness plugin `dsh-purge`. Confirm the host first and install only that one. Do not scan the whole disk, do not read or edit other files, do not apply settings, and do not restart the app. -If `dsh` is not on `PATH`, tell the user and stop. +**Web (official `dsh web`)** -Web profile: +If `dsh` is not on PATH, tell the user and stop. ```sh dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip ``` -If the user also uses the desktop profile, run this too: +If this directory is already a clone, use `dsh plugin --profile web add .`. + +**Desktop (community DSH Desktop)** + +Do not use official `dsh plugin --profile desktop` on PATH. Do not use `dsh://`. + +Default: already inside Desktop’s built-in terminal: + +```sh +dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +``` + +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 +$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" +$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) +if (-not $exe) { + $exe = @( + "$env:LOCALAPPDATA\Programs\DSH Desktop\DSH Desktop.exe", + "$env:ProgramFiles\DSH Desktop\DSH Desktop.exe", + "${env:ProgramFiles(x86)}\DSH Desktop\DSH Desktop.exe" + ) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $exe) { Write-Host "DSH Desktop.exe not found. Start the app or give the install folder."; return } +$cli = @( + (Join-Path (Split-Path $exe) "resources\app\lib\desktop-cli.js"), + (Join-Path (Split-Path $exe) "resources\app.asar.unpacked\lib\desktop-cli.js") +) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +$env:ELECTRON_RUN_AS_NODE = "1" +$env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop" +& $exe --expose-internals $cli plugin add $zip +``` + +**Official Harness desktop EXE** ```sh dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip ``` -If this directory is already a clone of the repo, this is enough instead of the zip: - -```sh -dsh plugin --profile web add . -``` - -After the command finishes, tell the user to quit and reopen DeepSeek Harness themselves. 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. -### Method 2: `dsh://` one-click (desktop, no CLI) +### Official desktop EXE (`dsh://`) -If the official DeepSeek Harness desktop client (EXE) is installed, the button below opens a system URI scheme and loads the plugin. +If the **official DeepSeek Harness desktop client (EXE)** is installed, the button below opens a system URI. Community [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop) does **not** handle `dsh://` — use **Desktop (default)** above. + +CLI equivalent: + +```sh +dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +```

🌐 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.3&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.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 ``` **Web trigger example:** @@ -147,7 +245,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.3', + version: '1.1.7', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', @@ -166,7 +264,7 @@ export function installDshPurgeToDesktop() { **HTML link:** ```html - + 🚀 Install in desktop client ``` @@ -177,46 +275,28 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | Plugin id | | name | `dsh-purge` | Display name | -| version | `1.1.3` | Semver | +| version | `1.1.7` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | Zip URL | -### Method 3: Official CLI (`dsh plugin add`) +### Manual install -```sh -git clone https://github.com/YuJunZhiXue/dsh-purge.git -cd dsh-purge - -# Web -dsh plugin --profile web add . - -# Desktop -dsh plugin --profile default add . -``` - -Or skip clone and pass the zip: - -```sh -dsh plugin --profile web 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.zip -``` - -Run both if you use Web and desktop. Then **restart**, then Apply on the settings page or `/purge apply` in chat. - -### Method 4: Manual install - -Use this when `dsh` is not on `PATH` or you do not want `dsh plugin add`. Do **not** delete existing bundles. +Use this when `dsh` is not on `PATH` or you do not want `dsh plugin add`. Edit the profile for that host. Do **not** delete existing bundles. **1. Find the Harness home (`$DSH_HOME`)** | Layout | Typical path | |---|---| -| Env | `DSH_HOME` if set | -| Windows portable | `.dsh` next to `npm-global`, e.g. `D:\DeepSeek Harness\.dsh` | +| Env | `DSH_HOME` if set (community Desktop host-commands also set this) | +| Windows portable | `.dsh` next to `npm-global` | | User default | Windows `%USERPROFILE%\.dsh`; Linux / macOS `~/.dsh` | -Web = `profiles/web`. Desktop = `profiles/default` (or whatever profile directory the desktop client actually uses). +| Host | Profile directory | +|---|---| +| Official Web | `$DSH_HOME/profiles/web` | +| Official desktop EXE | `$DSH_HOME/profiles/default` | +| Community DSH Desktop | `$DSH_HOME/profiles/desktop` | **2. Put this repo under plugins** @@ -224,12 +304,13 @@ Web = `profiles/web`. Desktop = `profiles/default` (or whatever profile director git clone https://github.com/YuJunZhiXue/dsh-purge.git "$DSH_HOME/plugins/dsh-purge" ``` -Or copy the tree to `$DSH_HOME/plugins/dsh-purge` (folder name must be `dsh-purge`). +Or copy the tree to `$DSH_HOME/plugins/dsh-purge` (folder name must be `dsh-purge`). The `file:../../plugins/dsh-purge` relative path is enough. A junction is only needed if `plugin add` is given a local path that contains spaces. **3. Edit that profile’s `package.json`** - Web: `$DSH_HOME/profiles/web/package.json` -- Desktop: `$DSH_HOME/profiles/default/package.json` +- Official desktop EXE: `$DSH_HOME/profiles/default/package.json` +- Community DSH Desktop: `$DSH_HOME/profiles/desktop/package.json` Add to `dependencies` (keep other deps): @@ -240,7 +321,7 @@ Add to `dependencies` (keep other deps): **Append** `"dsh-purge"` at the end of `dsh.profile.bundles`: - Web: **keep** `@deepseek-ai/dsh-web-app`, only append this plugin -- Desktop: keep `@deepseek-ai/dsh-base` (and the rest), only append this plugin +- Official / community Desktop: keep `@deepseek-ai/dsh-base` (and the rest), only append this plugin Sketch (keep every other field from the file on disk): @@ -271,25 +352,31 @@ pnpm install cd "$DSH_HOME/profiles/default" pnpm install + +cd "$DSH_HOME/profiles/desktop" +pnpm install ``` -PowerShell: substitute the real path, e.g. +PowerShell: use the real Harness home: ```powershell -cd "D:\DeepSeek Harness\.dsh\profiles\web" +cd "$env:USERPROFILE\.dsh\profiles\web" # Web +# cd "$env:USERPROFILE\.dsh\profiles\desktop" # community Desktop +# cd "$env:USERPROFILE\.dsh\profiles\default" # official EXE +# portable: \.dsh\profiles\ pnpm install ``` **5. Restart, then apply patches** -1. Fully quit DeepSeek Harness (Web process or desktop tray) and start it again. +1. Fully quit the current host (Web process, or official EXE / community Desktop tray) and start it again. Community Desktop opens `DSH Desktop.exe`, not `dsh web`. 2. Settings should show **Rules**. Ctrl+F5 if cached. 3. Click **Apply**, or `/purge apply`, or `dsh-purge --apply` from the plugin dir. -4. Restart again when prompted so patched packages load in this process. +4. Restart again when prompted so patched packages load in this process. Settings **Restart / Uninstall** relaunch the desktop app when you are on Desktop. ### Uninstall -Settings → **Rules** → **Uninstall**. Confirm the dialog: uninstall restores the original Harness and removes this plugin. If patches were applied, they are reverted first. DeepSeek Harness then restarts without dsh-purge. +Settings → **Rules** → **Uninstall**. Confirm the dialog: uninstall restores the original Harness and removes this plugin. If patches were applied, they are reverted first. The current host then restarts (Web relaunches `dsh web`; community Desktop relaunches `DSH Desktop.exe`). ```sh # or from a terminal @@ -439,8 +526,13 @@ The composer **Undo** button drops the last turn and puts the last user sentence ```sh node --check lib/index.js node --check lib/core.js +node --check lib/surface.js +node --check lib/web.js +node --check lib/desktop.js +node --check lib/host.js node --check lib/rewind.js node --check client.js +node --test test/surface.test.js ``` --- @@ -476,7 +568,7 @@ prompt-inject.md has content? ──yes──> write it verbatim as the dsh-purg **DSH Desktop (anywhere-labs/dsh-desktop, issue #9):** `host-commands//bin` is sealed — no sibling extras (including `dsh.cmd.dshpurge.bak`). This plugin scrubs only (no inject, no bak writes). -**Prompt purge:** refusal / anti-roleplay wording in `minimal`, official `standard` / `code` / `cordis`, and liangshen personas becomes executable + roleplay-allowed. No fixed role name is locked in. +**Prompt purge:** refusal / anti-roleplay wording in `minimal`, official `standard` / `ptc` / `cordis`, and liangshen personas becomes executable + roleplay-allowed. No fixed role name is locked in. --- @@ -492,27 +584,47 @@ prompt-inject.md has content? ──yes──> write it verbatim as the dsh-purg ## Path detection +The host surface is detected first: `web` / `desktop` (`gui` / `tui` are reserved and still fall back to web). + +**Web:** + 1. `DSH_HOME` / `DSH_BASE` 2. `.dsh` next to the dsh launcher (portable install, any drive) -3. DSH Desktop `app.asar.unpacked/node_modules/@deepseek-ai` -4. `npm prefix -g` / `npm root -g` -5. Nested `@deepseek-ai/dsh/node_modules/@deepseek-ai` -6. `~/.dsh` +3. `npm prefix -g` / `npm root -g` +4. Nested `@deepseek-ai/dsh/node_modules/@deepseek-ai` +5. `~/.dsh` -If nothing is found, set `DSH_BASE`. No files are changed. +**Community DSH Desktop:** only the **running desktop process** install tree (`resources/app` or `app.asar.unpacked` → `@deepseek-ai`). The folder does not have to be named `DSH Desktop`, and the drive letter is not hard-coded. Order: + +1. Running `DSH Desktop.exe` / `process.resourcesPath` / `host-process-entry.js` / `desktop-cli.js` +2. A `resources/app` tree whose parent folder actually contains `DSH Desktop.exe` +3. A path whose name contains `DSH Desktop` / `dsh-desktop` +4. `DSH_DESKTOP_INSTALL` (install root) or `DSH_BASE` (`@deepseek-ai` under that tree) +5. Common NSIS locations (`%LOCALAPPDATA%\Programs\DSH Desktop`, `%ProgramFiles%\DSH Desktop`, …) + +Official npm-global is not patched. Sealed `host-commands` / `runtime-commands` are scrubbed, never injected. + +If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are changed. --- ## Changelog -### 1.1.6 +### 1.1.7 -- Settings **Uninstall** asks for confirmation, restores applied patches, then removes the plugin and restarts. -- The AI-assistant install block is install-only: official `dsh plugin add`, no disk scan, no apply. +- Install docs split **Web / Desktop** defaults: Web uses official `dsh --profile web`; Desktop uses the built-in terminal `dsh plugin add `. +- 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. +- The AI-assistant install block is install-only: no disk scan, no apply. +- Separate install commands for official Web / official EXE / community DSH Desktop. Desktop **Restart / Uninstall** relaunch `DSH Desktop.exe`. + ### 1.1.5 - Manual Update: if `git pull --ff-only` fails, fetch + reset to `origin/master`, then zip overlay. diff --git a/README.zh-CN.md b/README.zh-CN.md index bc8fb05..70662c7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.6

+

Version 1.1.7

DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐ @@ -77,11 +77,75 @@ ## ⚡ 安装方式 -Web 和桌面装的是同一个插件,只是 profile 不同。装完必须**完全退出并重启** DeepSeek Harness,设置页才会出现「规则设定」;然后再点「应用」打补丁(只装进 profile 还不会改 `@deepseek-ai` 包)。 +Web 端和桌面端**分开装、分开清洗**,互不影响。 + +| 宿主 | profile | 默认怎么装 | +|---|---|---| +| **Web 端**(官方 `dsh web`) | `web` | PATH 上的官方 `dsh` | +| **桌面端**(社区 [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop)) | `desktop` | 桌面应用自带终端里的 `dsh`(不要用 PATH 上的官方 `dsh`) | +| 官方 Harness 桌面 EXE | `default` | 官方 `dsh`,或下面的 `dsh://` | + +装完后都要: + +1. 完全退出并重启**刚装的那个宿主**(Web 关 `dsh web`;桌面端退出托盘再打开 `DSH Desktop.exe`) +2. 在**这个宿主**的设置页出现「规则设定」后点「应用」(只写入 profile 还不会改 `@deepseek-ai`) +3. 启动后会自动清洗当前宿主;没有 `prompt-inject.md` 时写入默认注入(已有文件不覆盖,空文件表示不注入) + +Web 的「应用 / 重启 / 卸载」只动 Web。桌面端的「应用 / 重启 / 卸载」只动桌面应用,不会去拉 `dsh web`。 > 🌐 **插件生态市场**:[DeepSeek Harness Hub](https://deepseek.stream/plugins/dsh-purge)(只看介绍;**不要**用 `deepseek.stream/api/plugins/download?...`,那个地址不是 pnpm 能解的 tar,会报 `ERR_PNPM_TARBALL_EXTRACT`) -### 方式 1:交给 AI 安装(只装插件) +### Web 端(默认) + +```sh +dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +``` + +当前目录已是本仓库时: + +```sh +dsh plugin --profile web add . +``` + +然后关掉 `dsh web` 再开,在 Web 设置页点「应用」。`dsh` 不在 PATH 就先装好官方 CLI,或走下面「手动配置」。 + +### 桌面端(默认) + +打开社区 [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop),在**自带终端**里执行(这里的 `dsh` 是桌面包装脚本,默认 profile 就是 `desktop`): + +```sh +dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +``` + +不要用 PATH 上的官方 `dsh plugin --profile desktop`(会被拒绝)。不要用 `dsh://`(那是官方 EXE)。 + +然后退出托盘,重新打开 `DSH Desktop.exe`,在**桌面端**设置页点「应用」。 + +从系统终端安装时,用桌面端自带 CLI。按正在运行的进程、默认安装位置定位 `DSH Desktop.exe`: + +```powershell +$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" +$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) +if (-not $exe) { + $exe = @( + "$env:LOCALAPPDATA\Programs\DSH Desktop\DSH Desktop.exe", + "$env:ProgramFiles\DSH Desktop\DSH Desktop.exe", + "${env:ProgramFiles(x86)}\DSH Desktop\DSH Desktop.exe" + ) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $exe) { throw "未找到 DSH Desktop.exe,请先打开桌面端,或把 `$exe` 设成安装目录里的 exe" } +$cli = @( + (Join-Path (Split-Path $exe) "resources\app\lib\desktop-cli.js"), + (Join-Path (Split-Path $exe) "resources\app.asar.unpacked\lib\desktop-cli.js") +) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +$env:ELECTRON_RUN_AS_NODE = "1" +$env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop" +& $exe --expose-internals $cli plugin add $zip +``` + +自定义安装目录时,把 `$exe` 换成该目录下的 `DSH Desktop.exe`。默认用 zip,避免本地路径空格把命令拆开。 + +### 交给 AI 安装(只装插件) 把下面这一块发给本机助手,让它只执行安装命令。 @@ -90,48 +154,82 @@ Web 和桌面装的是同一个插件,只是 profile 不同。装完必须** -用官方 CLI 安装 DeepSeek Harness 插件 `dsh-purge`。只跑下面的命令。不要搜索磁盘,不要读或改其它文件,不要应用设置,也不要重启应用。 +安装 DeepSeek Harness 插件 `dsh-purge`。先确认宿主,只装正在用的那一个。不要全盘搜索,不要读或改其它文件,不要应用设置,也不要重启应用。 -如果 `dsh` 不在 `PATH` 里,告诉用户后停止。 +**Web 端(官方 `dsh web`)** -Web profile: +`dsh` 不在 PATH 就告诉用户后停止。 ```sh dsh plugin --profile web add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip ``` -用户如果也用桌面端,再跑这一条: +当前目录已是本仓库时改用 `dsh plugin --profile web add .`。 + +**桌面端(社区 DSH Desktop)** + +不要用 PATH 上的官方 `dsh plugin --profile desktop`。不要用 `dsh://`。 + +默认:已在桌面端自带终端里时直接跑: + +```sh +dsh plugin add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +``` + +从系统终端安装时:用正在运行的 `DSH Desktop` 进程 Path,或默认位置 `%LOCALAPPDATA%\Programs\DSH Desktop\DSH Desktop.exe`、`%ProgramFiles%\DSH Desktop\DSH Desktop.exe`。不要全盘扫描。然后: + +```powershell +$zip = "https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip" +$exe = (Get-Process -Name "DSH Desktop" -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path) +if (-not $exe) { + $exe = @( + "$env:LOCALAPPDATA\Programs\DSH Desktop\DSH Desktop.exe", + "$env:ProgramFiles\DSH Desktop\DSH Desktop.exe", + "${env:ProgramFiles(x86)}\DSH Desktop\DSH Desktop.exe" + ) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $exe) { Write-Host "未找到 DSH Desktop.exe,请先打开桌面端或给出安装目录"; return } +$cli = @( + (Join-Path (Split-Path $exe) "resources\app\lib\desktop-cli.js"), + (Join-Path (Split-Path $exe) "resources\app.asar.unpacked\lib\desktop-cli.js") +) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +$env:ELECTRON_RUN_AS_NODE = "1" +$env:DSH_DESKTOP_DEFAULT_PROFILE = "desktop" +& $exe --expose-internals $cli plugin add $zip +``` + +**官方 Harness 桌面 EXE** ```sh dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip ``` -如果当前目录已经是本仓库的克隆,用这条即可,不必下 zip: - -```sh -dsh plugin --profile web add . -``` - -命令结束后,提醒用户自己退出并重新打开 DeepSeek Harness。然后停止。 +命令结束后,提醒:完全退出并重启刚装的那个宿主,再在该宿主设置页点「应用」。Web 和桌面端不要交叉点应用。然后停止。

-### 方式 2:dsh:// 协议联动一键安装(桌面端最快,秒级免命令行) +### 官方桌面 EXE(`dsh://`) -若已安装 DeepSeek Harness 官方桌面客户端(EXE),点下方按钮即可通过系统级 URI Scheme 唤起客户端装载。 +已安装 **DeepSeek Harness 官方桌面客户端(EXE)** 时,点下方按钮走系统 URI。社区 [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop) **不认** `dsh://`,走上面「桌面端」默认命令。 + +命令行等价: + +```sh +dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip +```

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

🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.3&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.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 ``` **网页端(前端)触发代码示例:** @@ -144,7 +242,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.3', + version: '1.1.7', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', @@ -163,7 +261,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -174,46 +272,28 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.3` | 语义化版本号 | +| version | `1.1.7` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | zip 下载直链 | -### 方式 3:官方 CLI(`dsh plugin add`) +### 手动配置安装 -```sh -git clone https://github.com/YuJunZhiXue/dsh-purge.git -cd dsh-purge - -# Web -dsh plugin --profile web add . - -# 桌面 -dsh plugin --profile default add . -``` - -不 clone、直接喂 zip 也可以: - -```sh -dsh plugin --profile web 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.zip -``` - -Web + 桌面都要用时,两条都跑。然后**重启**,再在设置页点「应用」或聊天里 `/purge apply`。 - -### 方式 4:手动配置安装 - -`dsh` 不在 PATH、或不想用 `dsh plugin add` 时,按下面做。全程不要删 profile 里原有的 bundle。 +`dsh` 不在 PATH、或不想用 `dsh plugin add` 时,按宿主改对应 profile。不要删原有 bundle。 **1. 找到 Harness 主目录(下文称 `$DSH_HOME`)** | 安装形态 | 典型路径 | |---|---| | 环境变量 | `DSH_HOME`(已设置就用它) | -| Windows 便携包 | 与 `npm-global` 同级的 `.dsh`,例如 `D:\DeepSeek Harness\.dsh` | +| Windows 便携包 | 与 `npm-global` 同级的 `.dsh` | | 用户默认 | Windows `%USERPROFILE%\.dsh`;Linux / macOS `~/.dsh` | -Web 用 `profiles/web`,桌面用 `profiles/default`(若桌面客户端实际 profile 名不同,以目录为准)。 +| 宿主 | profile 目录 | +|---|---| +| Web 端 | `$DSH_HOME/profiles/web` | +| 社区桌面端 | `$DSH_HOME/profiles/desktop` | +| 官方桌面 EXE | `$DSH_HOME/profiles/default` | **2. 把本仓库放到 plugins 目录** @@ -221,14 +301,13 @@ Web 用 `profiles/web`,桌面用 `profiles/default`(若桌面客户端实际 git clone https://github.com/YuJunZhiXue/dsh-purge.git "$DSH_HOME/plugins/dsh-purge" ``` -或把已有仓库复制为 `$DSH_HOME/plugins/dsh-purge`(目录名必须是 `dsh-purge`)。 +或把已有仓库复制为 `$DSH_HOME/plugins/dsh-purge`(目录名必须是 `dsh-purge`)。用 `file:../../plugins/dsh-purge` 相对路径即可。 **3. 改对应 profile 的 `package.json`** -文件: - - Web:`$DSH_HOME/profiles/web/package.json` -- 桌面:`$DSH_HOME/profiles/default/package.json` +- 社区桌面端:`$DSH_HOME/profiles/desktop/package.json` +- 官方桌面 EXE:`$DSH_HOME/profiles/default/package.json` 在 `dependencies` 里追加(不要删别的依赖): @@ -239,9 +318,9 @@ git clone https://github.com/YuJunZhiXue/dsh-purge.git "$DSH_HOME/plugins/dsh-pu 在 `dsh.profile.bundles` 数组**末尾追加** `"dsh-purge"`: - Web:**必须保留**原来的 `@deepseek-ai/dsh-web-app`,只追加本插件 -- 桌面:保留原来的 `@deepseek-ai/dsh-base` 等,只追加本插件 +- 桌面端:保留原来的 `@deepseek-ai/dsh-base` 等,只追加本插件 -完整示意(其它字段按你机器上的原文件保留): +完整示意(其它字段按原文件保留): ```json { @@ -265,32 +344,36 @@ git clone https://github.com/YuJunZhiXue/dsh-purge.git "$DSH_HOME/plugins/dsh-pu **4. 安装依赖** ```sh -# Web -cd "$DSH_HOME/profiles/web" +cd "$DSH_HOME/profiles/web" # Web pnpm install -# 桌面(若也改了 default) -cd "$DSH_HOME/profiles/default" +cd "$DSH_HOME/profiles/desktop" # 社区桌面端 +pnpm install + +cd "$DSH_HOME/profiles/default" # 官方 EXE pnpm install ``` -Windows PowerShell 把 `$DSH_HOME` 换成实际路径即可,例如: +Windows PowerShell: ```powershell -cd "D:\DeepSeek Harness\.dsh\profiles\web" +cd "$env:USERPROFILE\.dsh\profiles\web" +# cd "$env:USERPROFILE\.dsh\profiles\desktop" +# cd "$env:USERPROFILE\.dsh\profiles\default" +# 便携包:<安装根>\.dsh\profiles\ pnpm install ``` **5. 重启,再打补丁** -1. 完全退出 DeepSeek Harness(Web 关进程;桌面退出托盘),再启动。 +1. 完全退出刚装的那个宿主(Web 关进程;桌面端退出托盘),再启动。 2. 设置页应出现「规则设定」。有缓存就 Ctrl+F5。 -3. 点「应用」,或聊天 `/purge apply`,或在插件目录执行 `dsh-purge --apply`。 -4. 按提示再重启一次,补丁才进入当前进程。 +3. 在**这个宿主**点「应用」,或聊天 `/purge apply`。 +4. 按提示再重启一次。桌面端的「重启 / 卸载」会重启桌面应用。 ### 卸载 -设置页 →「规则设定」→「卸载」。弹窗确认:卸载将还原回原版并清除本插件。如果已经点过「应用」,会先还原补丁,再删插件文件,然后重启。 +设置页 →「规则设定」→「卸载」。弹窗确认:卸载将还原回原版并清除本插件。如果已经点过「应用」,会先还原补丁,再删插件文件,然后重启当前宿主(Web 重启 `dsh web`;桌面端重启 `DSH Desktop.exe`)。 ```sh # 也可以用命令行 @@ -496,27 +579,38 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt ## 路径探测 -1. `DSH_HOME` / `DSH_BASE`(显式指定) -2. dsh 启动器旁的 `.dsh`(便携安装,任意盘符) -3. DSH Desktop → `process.resourcesPath/app.asar.unpacked/node_modules/@deepseek-ai` -4. `npm prefix -g` / `npm root -g` -5. 嵌套 `@deepseek-ai/dsh/node_modules/@deepseek-ai` -6. 系统默认 `~/.dsh` +宿主面先判断 `web` / `desktop`(预留 `gui` / `tui`,尚未单独适配时回退 web)。 -npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑在 `dsh-sandbox/lib/index.js`。找不到目标时提示设置 `DSH_BASE`,不改文件。 +**Web:** + +1. `DSH_HOME` / `DSH_BASE` +2. dsh 启动器旁的 `.dsh` +3. `npm prefix -g` / `npm root -g` +4. 嵌套 `@deepseek-ai/dsh/node_modules/@deepseek-ai` +5. 系统默认 `~/.dsh` + +**桌面端:** 只打当前桌面进程安装包树(`resources/app` 或 `app.asar.unpacked` 下的 `@deepseek-ai`)。顺序:运行中的 `DSH Desktop.exe` / `resourcesPath` / `host-process-entry.js`,其次默认安装位置,或 `DSH_DESKTOP_INSTALL` / `DSH_BASE`。不打官方 npm-global。密封的 `host-commands` / `runtime-commands` 只清理、不注入。 + +找不到目标时提示设置 `DSH_BASE`,不改文件。 --- ## 更新记录 +### 1.1.7 + +- 安装文档按 **Web 端 / 桌面端** 分开写默认命令:Web 用官方 `dsh --profile web`;桌面端默认在自带终端 `dsh plugin add `。 +- 桌面端清洗、重启、卸载只针对当前桌面进程的安装树,不碰官方 Web / npm-global。 +- 桌面端安装目录按运行中的 `DSH Desktop.exe` 定位,默认位置或自定义目录都可以。 + +
+更早版本 + ### 1.1.6 - 设置页「卸载」会弹窗确认;若已应用补丁则先还原回原版,再清除插件并重启。 - 给 AI 的安装块只跑官方 `dsh plugin add`,不扫盘、不应用。 -
-更早版本 - ### 1.1.5 - 点「更新」时:git 快进失败会 `fetch + reset`,再不行改用 zip 覆盖,不再整次失败。 diff --git a/bin/dsh-purge.js b/bin/dsh-purge.js index 4db4a03..7fde3bc 100755 --- a/bin/dsh-purge.js +++ b/bin/dsh-purge.js @@ -7,7 +7,9 @@ const args = process.argv.slice(2); function printStatus(state) { const out = []; out.push("dsh-purge 状态 / Status"); + out.push(" 宿主 / surface " + (state.surface || "web")); out.push(" DSH_HOME " + state.dsh_home); + if (state.desktop_install) out.push(" 桌面安装 " + state.desktop_install); if (state.ai_base) { out.push(" 插件根 / root " + state.ai_base); for (const [key, fp] of Object.entries(state.files)) { diff --git a/client.js b/client.js index 15dfc09..64ead70 100644 --- a/client.js +++ b/client.js @@ -14,6 +14,29 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { function useT() { return translate; } + function clientGuessSurface() { + try { + if (typeof navigator !== "undefined" && /electron/i.test(navigator.userAgent || "")) return "desktop"; + if (typeof location !== "undefined") { + const port = String(location.port || ""); + if (port === "43120") return "desktop"; + const host = String(location.hostname || ""); + if (host && host !== "127.0.0.1" && host !== "localhost" && /dsh desktop/i.test(String(location.href || ""))) return "desktop"; + } + } catch { /* ignore */ } + return ""; + } + function hostSurfaceOf(s) { + return (s && s.surface) || clientGuessSurface() || "web"; + } + function hostText(t, key, surface) { + if (surface && surface !== "web") { + const specific = key + "." + surface; + const hit = t(specific); + if (hit && hit !== specific) return hit; + } + return t(key); + } function apiUrl(p) { try { return new URL(p, window.location.origin).toString(); } catch { return p; } } @@ -85,6 +108,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "status.pending": "待应用", "status.skipped": "跳过", "apply.hint": "待应用=原文还在。跳过=没装或官方已改写,再点也不会变。", + "warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。", + "warn.noRoot.desktop": "未定位到当前桌面应用里的 @deepseek-ai。请退出托盘后重新打开 DSH Desktop.exe,再在桌面端设置页点「应用」。安装目录不限盘符。", + "warn.noInject": "注入文件还不存在。重启后会写入默认提示词;空文件表示不注入。", "skip": "跳过", "unknown": "未知", "delete": "删除", @@ -99,6 +125,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "uninstall.cancel": "取消", "uninstall.applying": "正在卸载并还原…", "uninstall.done": "已卸载并还原,正在重启…", + "uninstall.done.desktop": "已卸载并还原,正在重启桌面应用…", "uninstall.fail": "卸载失败: {error}", "btn.checkUpdate": "检测更新", "btn.checkUpdate.busy": "检测中…", @@ -147,9 +174,15 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "btn.restart": "重启", "btn.restart.busy": "重启中…", "restarting": "重启中…", + "restarting.desktop": "正在重启桌面应用…", "restart.timeout": "超时,请刷新", "restart.fail": "失败: {error}", "restart.confirm": "清洗已完成,重启后生效。", + "restart.confirm.desktop": "清洗已完成,重启桌面应用后生效。", + "surface.web": "Web", + "surface.desktop": "桌面端", + "surface.gui": "GUI", + "surface.tui": "TUI", "restart.incomplete": "清洗未完成:{detail}", "restart.incomplete.patches": "必需补丁失败 {failed} 项(#{ids})", "restart.incomplete.flash": "CMD 无感未钉入({entry})", @@ -229,6 +262,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "status.pending": "Pending", "status.skipped": "Skipped", "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.", "skip": "Skipped", "unknown": "Unknown", "delete": "Delete", @@ -243,6 +279,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "uninstall.cancel": "Cancel", "uninstall.applying": "Uninstalling and restoring…", "uninstall.done": "Uninstalled and restored. Restarting…", + "uninstall.done.desktop": "Uninstalled and restored. Restarting the desktop app…", "uninstall.fail": "Uninstall failed: {error}", "btn.checkUpdate": "Check update", "btn.checkUpdate.busy": "Checking…", @@ -291,9 +328,15 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "btn.restart": "Restart", "btn.restart.busy": "Restarting…", "restarting": "Restarting…", + "restarting.desktop": "Restarting the desktop app…", "restart.timeout": "Timed out; refresh", "restart.fail": "Failed: {error}", "restart.confirm": "Apply finished. Restart to take effect.", + "restart.confirm.desktop": "Apply finished. Restart the desktop app to take effect.", + "surface.web": "Web", + "surface.desktop": "Desktop", + "surface.gui": "GUI", + "surface.tui": "TUI", "restart.incomplete": "Apply incomplete: {detail}", "restart.incomplete.patches": "{failed} required patch(es) failed (#{ids})", "restart.incomplete.flash": "CMD silence not pinned ({entry})", @@ -729,20 +772,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { apiJson("/dsh-purge/uninstall", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }) .then((d) => { if (!d || !d.ok) throw new Error((d && d.error) || "uninstall failed"); - setNotice({ kind: "ok", text: tr("uninstall.done") }); + setNotice({ kind: "ok", text: (d && d.note) || hostText(tr, "uninstall.done", d.surface || hostSurfaceOf(state)) }); + if ((d && d.surface) === "desktop" || (d && d.fullApp) || hostSurfaceOf(state) === "desktop") return; waitHostAfterUninstall(tr); }) .catch((e) => { const msg = String((e && e.message) || e || ""); if (/failed to fetch|networkerror|load failed/i.test(msg)) { - setNotice({ kind: "ok", text: tr("uninstall.done") }); + setNotice({ kind: "ok", text: hostText(tr, "uninstall.done", hostSurfaceOf(state)) }); + if (hostSurfaceOf(state) === "desktop" || clientGuessSurface() === "desktop") return; waitHostAfterUninstall(tr); return; } setNotice({ kind: "error", text: tr("uninstall.fail", { error: msg }) }); setUninstallBusy(false); }); - }, [waitHostAfterUninstall]); + }, [state, waitHostAfterUninstall]); const s = state; const total = s && s.patches_total ? s.patches_total : 26; @@ -751,6 +796,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const settled = Math.min(total, applied + skipped); const pct = total ? Math.round((settled / total) * 100) : 0; + const hostSurface = hostSurfaceOf(s); const localVer = (s && s.plugin_version) || (updateInfo && updateInfo.localVersion) || ""; const remoteVer = updateInfo && (updateInfo.remoteVersion || updateInfo.remoteSha) || ""; const remoteSha = updateInfo && updateInfo.remoteSha || ""; @@ -765,6 +811,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { h("div", { className: "dshp-head" }, h("h3", { className: "dshp-title" }, t("purge.title")), h("div", { className: "dshp-row", style: { margin: 0, flex: 1, justifyContent: "flex-end" } }, + h("span", { className: "dshp-pill" }, t("surface." + hostSurface)), versionText ? h("span", { className: "dshp-pill" + (canApplyUpdate ? " is-wait" : "") }, versionText) : null, h(Btn, { tiny: true, @@ -824,15 +871,17 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { ), ) : null, h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("apply.hint")), + s && !s.ai_base ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 } }, hostText(t, "warn.noRoot", hostSurface)) : null, + s && s.ai_base && s.override_status === "missing" ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("warn.noInject")) : null, askRestart ? h("div", { className: "dshp-ask" }, - h("span", null, t("restart.confirm")), + h("span", null, hostText(t, "restart.confirm", hostSurface)), h(Btn, { tiny: true, onClick: () => setAskRestart(false) }, t("restart.later")), h(Btn, { tiny: true, kind: "primary", onClick: () => { setAskRestart(false); - restartDsh(setNotice, function () {}, t); + restartDsh(setNotice, function () {}, t, hostSurface); }, }, t("btn.restart")), ) : null, @@ -1087,16 +1136,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { setTimeout(ping, 800); } - function restartDsh(setNotice, setBusy, t) { + function restartDsh(setNotice, setBusy, t, surface) { + const surf = surface || clientGuessSurface() || "web"; setBusy(true); - setNotice({ kind: "ok", text: t("restarting") }); + setNotice({ kind: "ok", text: hostText(t, "restarting", surf) }); fetch("/dsh-purge/restart", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }) .then((r) => r.json()) .then((d) => { if (!d.ok) throw new Error(d.error || "restart failed"); + const next = (d && d.surface) || surf; + setNotice({ kind: "ok", text: hostText(t, "restarting", next) }); + // 桌面端整应用会退出重开。先刷新内嵌 web 会单独重启 Host。 + if (next === "desktop" || (d && d.fullApp) || clientGuessSurface() === "desktop") return; waitForRestart(setNotice, setBusy, t); }) .catch((e) => { + if (surf === "desktop" || clientGuessSurface() === "desktop") return; if (String(e.message || e).includes("Failed to fetch") || e.name === "TypeError") { waitForRestart(setNotice, setBusy, t); return; diff --git a/lib/core.js b/lib/core.js index a696fc6..bd46dd7 100644 --- a/lib/core.js +++ b/lib/core.js @@ -12,6 +12,8 @@ import { resolveDshBinRoot, revertHideConsoleFromBin, } from "./hide-console.js"; +import * as desktop from "./desktop.js"; +import { adapterFor, detectSurface } from "./surface.js"; const isWindows = process.platform === "win32"; const SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"]; @@ -251,27 +253,14 @@ export function dirHasDshLauncher(dir) { } export function isDesktopCommandRuntimeDir(dir) { - if (!dir) return false; - const n = path.normalize(dir).replace(/\\/g, "/").toLowerCase(); - // host-commands//bin - if (n.includes("/host-commands/") && /(^|\/)bin\/?$/.test(n)) return true; - // %APPDATA%/DSH Desktop/.../bin - if (n.includes("/dsh desktop/") && /(^|\/)bin\/?$/.test(n)) return true; - return false; + return desktop.isSealedRuntimeDir(dir); } export function listDesktopCommandRuntimeDirs() { - const candidates = [...pathEnvDirs()]; - const appdata = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"); - const root = path.join(appdata, "DSH Desktop", "host-commands"); - if (isDir(root)) { - try { - for (const ent of fs.readdirSync(root, { withFileTypes: true })) { - if (ent.isDirectory()) candidates.push(path.join(root, ent.name, "bin")); - } - } catch {} - } - return collectDirs(candidates).filter(isDesktopCommandRuntimeDir); + return collectDirs([ + ...pathEnvDirs(), + ...desktop.listSealedRuntimeBins(), + ]).filter(isDesktopCommandRuntimeDir); } function ensureDirSync(dir) { @@ -722,10 +711,41 @@ export function silenceLiangshenPhase1Strip(dshHome = findDshHome()) { return hit; } +function realNorm(fp) { + if (!fp) return ""; + try { + return fs.realpathSync(fp).replace(/\\/g, "/").toLowerCase(); + } catch { + return path.resolve(fp).replace(/\\/g, "/").toLowerCase(); + } +} + +export function pathZone(fp) { + if (!fp) return "missing"; + const n = realNorm(fp); + if (desktop.isInsideDesktopInstall(fp) || desktop.isInsideDesktopInstall(n)) return "desktop-install"; + if (/\/profiles\/desktop(\/|$)/.test(n)) return "desktop-profile"; + if (/\/profiles\/web(\/|$)/.test(n)) return "web-profile"; + if (n.includes("/npm-global")) return "web-install"; + return "shared"; +} + +export function allowTargetPath(fp, surface = detectSurface()) { + const zone = pathZone(fp); + if (adapterFor(surface) === "desktop") { + return zone === "desktop-install" || zone === "desktop-profile"; + } + return zone !== "desktop-install" && zone !== "desktop-profile"; +} + +function keepSurfaceFile(fp) { + return fp && isFile(fp) && allowTargetPath(fp); +} + function listLiangshenBootstrapFiles(dshHome) { const out = []; const push = (fp) => { - if (fp && isFile(fp) && !out.includes(fp)) out.push(fp); + if (keepSurfaceFile(fp) && !out.includes(fp)) out.push(fp); }; const profilesRoot = path.join(dshHome, "profiles"); push(path.join(profilesRoot, "web", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "tool-bootstrap.mjs")); @@ -811,7 +831,7 @@ export function silenceMnemonGitFlash(dshHome = findDshHome()) { function listMnemonIndexFiles(dshHome) { const out = []; const push = (fp) => { - if (fp && isFile(fp) && !out.includes(fp)) out.push(fp); + if (keepSurfaceFile(fp) && !out.includes(fp)) out.push(fp); }; push(path.join(dshHome, "profiles", "web", "node_modules", "dsh-mnemon", "lib", "index.js")); push(path.join(dshHome, "profiles", "desktop", "node_modules", "dsh-mnemon", "lib", "index.js")); @@ -851,7 +871,7 @@ function listPiAiApiFiles(dshHome, aiBase, filename) { const out = []; const seen = new Set(); const push = (fp) => { - if (!fp || !isFile(fp)) return; + if (!keepSurfaceFile(fp)) return; let key = fp; try { key = fs.realpathSync(fp); } catch { /* keep fp */ } key = String(key).toLowerCase(); @@ -1403,6 +1423,7 @@ export function findShimDir() { } export function listShimDirsForPatch() { + if (adapterFor(detectSurface()) === "desktop") return []; return collectDirs([ findShimDir(), ...listDesktopCommandRuntimeDirs(), @@ -1413,21 +1434,61 @@ export function listShimDirsForPatch() { .filter((dir) => !isDesktopCommandRuntimeDir(dir)); } -// Electron unpacked:app.asar.unpacked/node_modules/@deepseek-ai -function findDesktopAiBase() { - const candidates = []; - if (typeof process.resourcesPath === "string" && process.resourcesPath.trim()) { - candidates.push(path.join(process.resourcesPath, "app.asar.unpacked", "node_modules", "@deepseek-ai")); +function findAiBaseDesktop() { + const env = process.env.DSH_BASE; + if (env && env.trim()) { + const p = path.normalize(env.trim()); + if (isAiBase(p) && desktop.isInsideDesktopInstall(p)) return p; + } + const resolved = desktop.resolveDesktopAiBase(); + if (resolved) return resolved; + const starts = []; + if (process.argv[1]) { + try { starts.push(path.resolve(process.argv[1])); } catch {} + } + if (process.resourcesPath) starts.push(path.normalize(process.resourcesPath)); + if (desktop.isDesktopExecutable(process.execPath)) starts.push(path.dirname(process.execPath)); + for (const start of starts) { + try { + const hit = walkAncestorsForAiBase(isDir(start) ? start : path.dirname(start)); + if (hit && desktop.isInsideDesktopInstall(hit)) return hit; + } catch {} + } + return null; +} + +function findAiBaseWeb() { + const env = process.env.DSH_BASE; + if (env && env.trim()) { + const p = path.normalize(env.trim()); + if (isAiBase(p) && !desktop.isInsideDesktopInstall(p)) return p; } - // ELECTRON_RUN_AS_NODE 无稳定 resourcesPath,从 execPath 回推 Contents/Resources。 - const contentsDir = path.dirname(path.dirname(process.execPath)); - candidates.push(path.join(contentsDir, "Resources", "app.asar.unpacked", "node_modules", "@deepseek-ai")); + const fromProcess = findAiBaseFromRunningProcess(); + if (fromProcess && !desktop.isInsideDesktopInstall(fromProcess)) return fromProcess; - for (const candidate of candidates) { - if (fs.existsSync(path.join(candidate, "dsh-agent-instructions", "lib"))) { - return path.normalize(candidate); - } + const fromHome = findAiBaseFromDshHome(findDshHome()); + if (fromHome && !desktop.isInsideDesktopInstall(fromHome)) return fromHome; + + const nested = nestedAiPath(); + const prefix = findNpmPrefix(); + const shim = findShimDir(); + const search = []; + for (const base of [prefix, ...launcherDirsOf(prefix), shim]) { + search.push(...aiBaseGuessesFor(base)); + } + for (const cand of search) { + if (cand && isAiBase(cand) && !desktop.isInsideDesktopInstall(cand)) return path.normalize(cand); + } + const npmRoot = npmQuery(["root", "-g"]); + for (const cand of [path.join(npmRoot, nested), path.join(npmRoot, "@deepseek-ai")]) { + if (cand && isAiBase(cand) && !desktop.isInsideDesktopInstall(cand)) return path.normalize(cand); + } + + const needle = path.join("node_modules", nested); + for (const sr of [findDshHome(), path.join(findDshHome(), ".."), os.homedir()]) { + const found = findAiBaseRecursive(sr, needle, 0); + if (found && !desktop.isInsideDesktopInstall(found)) return found; } return null; } @@ -1444,47 +1505,20 @@ export function missingAiBaseMessage() { if (env.set && !env.valid) { return `DSH_BASE 已设置但不是有效的插件根(需要其下有 dsh-agent-instructions/lib): ${env.path}`; } + if (adapterFor(detectSurface()) === "desktop") { + const exe = desktop.findDesktopAppExecutable(); + if (exe) { + return `已找到桌面应用 ${exe},但其 resources/app(或 app.asar.unpacked)下没有 @deepseek-ai`; + } + return "未定位到当前桌面应用的 @deepseek-ai。请在桌面端内打开设置再点「应用」(不要用官方 dsh)。安装目录可以是任意盘符;也可设置 DSH_DESKTOP_INSTALL 为安装目录,或 DSH_BASE 为该树下的 @deepseek-ai"; + } return "插件根未找到 / set DSH_BASE"; } export function findAiBase() { return remember("ai", () => { - const env = process.env.DSH_BASE; - if (env && env.trim()) { - const p = path.normalize(env.trim()); - if (isAiBase(p)) return p; - } - - const fromProcess = findAiBaseFromRunningProcess(); - if (fromProcess) return fromProcess; - - const fromHome = findAiBaseFromDshHome(findDshHome()); - if (fromHome) return fromHome; - - const desktopBase = findDesktopAiBase(); - if (desktopBase) return desktopBase; - - const nested = nestedAiPath(); - const prefix = findNpmPrefix(); - const shim = findShimDir(); - const search = []; - for (const base of [prefix, ...launcherDirsOf(prefix), shim]) { - search.push(...aiBaseGuessesFor(base)); - } - for (const cand of search) { - if (cand && isAiBase(cand)) return path.normalize(cand); - } - const npmRoot = npmQuery(["root", "-g"]); - for (const cand of [path.join(npmRoot, nested), path.join(npmRoot, "@deepseek-ai")]) { - if (cand && isAiBase(cand)) return path.normalize(cand); - } - - const needle = path.join("node_modules", nested); - for (const sr of [findDshHome(), path.join(findDshHome(), ".."), os.homedir()]) { - const found = findAiBaseRecursive(sr, needle, 0); - if (found) return found; - } - return null; + if (adapterFor(detectSurface()) === "desktop") return findAiBaseDesktop(); + return findAiBaseWeb(); }); } @@ -2217,7 +2251,7 @@ const NEW_TOOL_PATCHES = [ { id: 25, name: "PRESET_FETCH_ENABLED", layer: "代码", layer_en: "Code", desc: "preset tool-web fetch 打开 / preset fetch enabled", - file: ["preset-unrestricted", "preset-standard", "preset-code", "preset-cordis", "preset-ptc"], + file: ["preset-unrestricted", "preset-standard", "preset-cordis", "preset-ptc", "preset-liangshen", "preset-liangshen-pkg"], rel: ["agent.cordis.yml"], replacements: [ { @@ -2248,7 +2282,6 @@ const NEW_TOOL_PATCHES = [ "web-app", "headless", "preset-standard", - "preset-code", "preset-cordis", "preset-unrestricted", "preset-ptc", @@ -3034,15 +3067,15 @@ function userPresetYml(dshHome, name) { } function firstExisting(candidates) { - return candidates.find((fp) => fp && fs.existsSync(fp)) ?? candidates[0]; + return candidates.find((fp) => fp && fs.existsSync(fp) && allowTargetPath(fp)) ?? ""; } function allExisting(candidates) { const hit = []; for (const fp of candidates) { - if (fp && fs.existsSync(fp) && !hit.includes(fp)) hit.push(fp); + if (fp && fs.existsSync(fp) && allowTargetPath(fp) && !hit.includes(fp)) hit.push(fp); } - return hit.length ? hit : (candidates[0] ? [candidates[0]] : []); + return hit; } function pathsOf(files, key) { @@ -3157,9 +3190,26 @@ function removeWebFetchWorkspaceLinkIfUnused(aiBase) { } } +function filterTargetFiles(files) { + const out = {}; + for (const [key, val] of Object.entries(files)) { + if (Array.isArray(val)) { + const kept = val.filter((fp) => !fp || !fs.existsSync(fp) || allowTargetPath(fp)); + const existing = kept.filter((fp) => fp && fs.existsSync(fp) && allowTargetPath(fp)); + out[key] = existing.length ? existing : []; + } else if (val && fs.existsSync(val) && !allowTargetPath(val)) { + out[key] = ""; + } else { + out[key] = val; + } + } + return out; +} + export function targetFiles(aiBase, dshHome = findDshHome()) { const root = packageRootFromAiBase(aiBase); - return { + const desktopHost = adapterFor(detectSurface()) === "desktop"; + const files = { "agent-instructions": firstExisting([ path.join(aiBase, "dsh-agent-instructions", "lib", "index.js"), ...(root ? [path.join(root, "packages", "context", "agent-instructions", "lib", "index.js")] : []), @@ -3178,11 +3228,17 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { path.join(aiBase, "dsh-headless", "cordis.patch.yml"), ...(root ? [path.join(root, "packages", "bundle", "headless", "cordis.patch.yml")] : []), ]), - "profile-web": firstExisting([ - path.join(dshHome, "profiles", "web", "cordis.patch.yml"), - path.join(aiBase, "dsh-web-app", "cordis.patch.yml"), - ...(root ? [path.join(root, "packages", "bundle", "web-app", "cordis.patch.yml")] : []), - ]), + "profile-web": firstExisting(desktopHost + ? [ + path.join(dshHome, "profiles", "desktop", "cordis.patch.yml"), + path.join(aiBase, "dsh-web-app", "cordis.patch.yml"), + ...(root ? [path.join(root, "packages", "bundle", "web-app", "cordis.patch.yml")] : []), + ] + : [ + path.join(dshHome, "profiles", "web", "cordis.patch.yml"), + path.join(aiBase, "dsh-web-app", "cordis.patch.yml"), + ...(root ? [path.join(root, "packages", "bundle", "web-app", "cordis.patch.yml")] : []), + ]), "agent-preset": firstExisting([ ...userPresetYml(dshHome, "unrestricted"), ...shippedPresetYml(root, "standard", aiBase), @@ -3250,7 +3306,6 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { ]), "preset-unrestricted": firstExisting(userPresetYml(dshHome, "unrestricted")), "preset-standard": allExisting(shippedPresetYml(root, "standard", aiBase)), - "preset-code": allExisting(shippedPresetYml(root, "code", aiBase)), "preset-cordis": allExisting(shippedPresetYml(root, "cordis", aiBase)), "preset-minimal": allExisting(shippedPresetYml(root, "minimal", aiBase)), "preset-ptc": allExisting(shippedPresetYml(root, "ptc", aiBase)), @@ -3274,10 +3329,11 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { ...nestedPkg(aiBase, "dsh-tool-pwsh", "lib", "index.js"), ...(root ? [path.join(root, "packages", "pwsh", "tool-pwsh", "lib", "index.js")] : []), ]), - "preset-liangshen": firstExisting(userPresetYml(dshHome, "liangshen")), - "preset-liangshen-pkg": firstExisting([ + "preset-liangshen": allExisting(userPresetYml(dshHome, "liangshen")), + "preset-liangshen-pkg": allExisting([ path.join(dshHome, "profiles", "web", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"), path.join(dshHome, "profiles", "desktop", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"), + path.join(dshHome, "profiles", "web", ".dsh-module-fallback", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"), path.join(dshHome, "profiles", "web", "node_modules", "@linxin666", "dsh-web-all", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"), ]), "liangshen-tool-bootstrap": listLiangshenBootstrapFiles(dshHome), @@ -3320,6 +3376,7 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { "pi-ai-completions": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-completions.js")), "pi-ai-responses-shared": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-responses-shared.js")), }; + return filterTargetFiles(files); } function asLf(text) { @@ -4236,8 +4293,12 @@ export async function gatherState() { shim_bin = shimFileStatus(path.join(shimDir, "dsh")); } return { + surface: detectSurface(), dsh_home: dshHome, ai_base: aiBase, + desktop_install: adapterFor(detectSurface()) === "desktop" + ? (desktop.findDesktopAppExecutable() || desktop.listDesktopInstallRoots()[0] || "") + : "", shim_dir: shimDir, desktop_runtimes, files, diff --git a/lib/desktop.js b/lib/desktop.js new file mode 100644 index 0000000..79ab436 --- /dev/null +++ b/lib/desktop.js @@ -0,0 +1,449 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +function isFile(fp) { + try { + return Boolean(fp) && fs.existsSync(fp) && fs.statSync(fp).isFile(); + } catch { + return false; + } +} + +function isDir(fp) { + try { + return Boolean(fp) && fs.existsSync(fp) && fs.statSync(fp).isDirectory(); + } catch { + return false; + } +} + +function isAiBase(p) { + return Boolean(p) && isDir(path.join(p, "dsh-agent-instructions", "lib")); +} + +function uniquePaths(list) { + const seen = new Set(); + const out = []; + for (const item of list) { + if (!item) continue; + const n = path.normalize(item); + const key = n.replace(/\\/g, "/").toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push(n); + } + return out; +} + +function slashNorm(p) { + return path.normalize(String(p || "")).replace(/\\/g, "/").toLowerCase(); +} + +function isSubPath(child, root) { + const c = slashNorm(child).replace(/\/+$/, ""); + const r = slashNorm(root).replace(/\/+$/, ""); + if (!c || !r || r === "/") return false; + if (/^[a-z]:$/.test(r)) return false; + return c === r || c.startsWith(`${r}/`); +} + +/** 文件夹名带 DSH Desktop / dsh-desktop 时,任意盘符都算桌面安装树。 */ +export function looksLikeDesktopName(p) { + const n = slashNorm(p); + if (!n) return false; + return ( + n.includes("/dsh desktop/") || + n.includes("/dsh desktop.app/") || + n.endsWith("/dsh desktop") || + n.endsWith("/dsh desktop.app") || + n.includes("dsh-desktop") || + /\/dsh desktop\.exe$/i.test(n) + ); +} + +export function isDesktopExecutable(fp) { + const base = path.basename(String(fp || "")).toLowerCase(); + return base === "dsh desktop.exe" || base === "dsh desktop"; +} + +function exeCandidatesBeside(dir) { + if (!dir) return []; + return [ + path.join(dir, "DSH Desktop.exe"), + path.join(dir, "DSH Desktop"), + path.join(dir, "MacOS", "DSH Desktop"), + path.join(dir, "Contents", "MacOS", "DSH Desktop"), + ]; +} + +function firstExistingExe(dirs) { + for (const dir of dirs) { + if (!dir) continue; + for (const cand of exeCandidatesBeside(dir)) { + if (isFile(cand)) return path.normalize(cand); + } + } + return ""; +} + +const APP_SCRIPT_RE = /(desktop-cli|host-process-entry)\.js$/i; + +function installDirsFromAppScript(scriptPath) { + if (!scriptPath) return []; + const abs = path.resolve(scriptPath); + const lib = path.dirname(abs); + const app = path.dirname(lib); + const resources = path.dirname(app); + const install = path.dirname(resources); + return uniquePaths([lib, app, resources, install]); +} + +/** 从任意 `.../resources/app/...` 树反推安装目录(不要求文件夹叫 DSH Desktop)。 */ +export function inferDesktopInstallDir(p) { + const raw = path.normalize(String(p || "")).replace(/\\/g, "/"); + const n = raw.toLowerCase(); + if (!n) return ""; + const markers = [ + "/resources/app.asar.unpacked/", + "/resources/app/", + "/contents/resources/", + ]; + for (const marker of markers) { + const i = n.indexOf(marker); + if (i <= 0) continue; + return path.normalize(raw.slice(0, i)); + } + return ""; +} + +function extraInstallsFromEnv(env = process.env) { + return String(env.DSH_DESKTOP_INSTALL || "") + .split(path.delimiter) + .map((item) => item.trim()) + .filter(Boolean); +} + +function trustedInstallDir(dir) { + if (!dir) return false; + if (looksLikeDesktopName(dir)) return true; + if (firstExistingExe([dir])) return true; + return ( + isAiBase(path.join(dir, "resources", "app", "node_modules", "@deepseek-ai")) || + isAiBase(path.join(dir, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai")) + ); +} + +/** NSIS / 商店默认位置;不是全盘扫描。自定义目录靠进程或 DSH_DESKTOP_INSTALL。 */ +export function commonDesktopInstallDirs(env = process.env) { + const home = os.homedir(); + const local = env.LOCALAPPDATA || path.join(home, "AppData", "Local"); + const pf = env.ProgramFiles || "C:\\Program Files"; + const pf86 = env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; + return uniquePaths([ + ...extraInstallsFromEnv(env).filter(trustedInstallDir), + path.join(local, "Programs", "DSH Desktop"), + path.join(pf, "DSH Desktop"), + path.join(pf86, "DSH Desktop"), + "/Applications/DSH Desktop.app", + path.join(home, "Applications", "DSH Desktop.app"), + ]); +} + +export function listDesktopInstallRoots(input = {}) { + const execPath = input.execPath ?? process.execPath; + const resourcesPath = input.resourcesPath ?? process.resourcesPath; + const argv = input.argv ?? process.argv; + const env = input.env ?? process.env; + const roots = []; + + if (isDesktopExecutable(execPath)) { + const dir = path.dirname(path.normalize(execPath)); + roots.push(dir); + if (path.basename(dir) === "MacOS") { + const contents = path.dirname(dir); + roots.push(contents, path.join(contents, "Resources"), path.dirname(contents)); + } + } + + if (resourcesPath) { + const res = path.normalize(resourcesPath); + roots.push(res, path.dirname(res), path.join(res, "app"), path.join(res, "app.asar.unpacked")); + } + + for (const arg of argv) { + if (typeof arg === "string" && APP_SCRIPT_RE.test(arg)) { + roots.push(...installDirsFromAppScript(arg)); + } + } + + for (const extra of extraInstallsFromEnv(env)) { + if (trustedInstallDir(extra)) roots.push(extra); + } + return uniquePaths(roots); +} + +/** + * 是否落在社区 Desktop 安装树。 + * 不依赖盘符、也不要求文件夹叫 “DSH Desktop”: + * 当前进程的 exe / resources / host-process-entry、旁边真有 DSH Desktop.exe、或名字启发式。 + */ +export function isInsideDesktopInstall(p, input = {}) { + if (!p) return false; + if (looksLikeDesktopName(p)) return true; + const roots = listDesktopInstallRoots(input); + if (roots.some((root) => isSubPath(p, root))) return true; + const inferred = inferDesktopInstallDir(p); + if (!inferred) return false; + if (roots.some((root) => isSubPath(inferred, root) || isSubPath(root, inferred))) return true; + return Boolean(firstExistingExe([inferred])); +} + +export function findDesktopAppExecutable(input = {}) { + const execPath = input.execPath ?? process.execPath; + const resourcesPath = input.resourcesPath ?? process.resourcesPath; + const argv = input.argv ?? process.argv; + const env = input.env ?? process.env; + + if (isDesktopExecutable(execPath) && isFile(execPath)) return path.normalize(execPath); + + if (resourcesPath) { + const hit = firstExistingExe([path.dirname(path.normalize(resourcesPath))]); + if (hit) return hit; + } + + for (const arg of argv) { + if (typeof arg !== "string" || !APP_SCRIPT_RE.test(arg)) continue; + const hit = firstExistingExe(installDirsFromAppScript(arg)); + if (hit) return hit; + } + + const guessed = firstExistingExe([ + ...extraInstallsFromEnv(env), + ...commonDesktopInstallDirs(env), + ]); + return guessed || ""; +} + +function packageRootsFromInstall(installDir) { + if (!installDir) return []; + const bases = [installDir]; + const name = path.basename(installDir); + if (name === "MacOS") bases.push(path.join(path.dirname(installDir), "Resources")); + if (name === "Contents") bases.push(path.join(installDir, "Resources")); + if (name.toLowerCase().endsWith(".app")) bases.push(path.join(installDir, "Contents", "Resources")); + const out = []; + for (const base of bases) { + out.push( + path.join(base, "resources", "app", "node_modules", "@deepseek-ai"), + path.join(base, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"), + path.join(base, "app", "node_modules", "@deepseek-ai"), + path.join(base, "app.asar.unpacked", "node_modules", "@deepseek-ai"), + ); + } + return out; +} + +export function listDesktopPackageRoots(input = {}) { + const execPath = input.execPath ?? process.execPath; + const resourcesPath = input.resourcesPath ?? process.resourcesPath; + const argv = input.argv ?? process.argv; + const env = input.env ?? process.env; + const cands = []; + + if (resourcesPath) { + cands.push( + path.join(resourcesPath, "app", "node_modules", "@deepseek-ai"), + path.join(resourcesPath, "app.asar.unpacked", "node_modules", "@deepseek-ai"), + ); + } + + if (isDesktopExecutable(execPath)) { + cands.push(...packageRootsFromInstall(path.dirname(execPath))); + } + + const exe = findDesktopAppExecutable(input); + if (exe) cands.push(...packageRootsFromInstall(path.dirname(exe))); + + for (const arg of argv) { + if (typeof arg !== "string" || !APP_SCRIPT_RE.test(arg)) continue; + const appDir = path.dirname(path.dirname(path.resolve(arg))); + cands.push(path.join(appDir, "node_modules", "@deepseek-ai")); + cands.push(...packageRootsFromInstall(path.dirname(path.dirname(appDir)))); + } + + for (const install of commonDesktopInstallDirs(env)) { + cands.push(...packageRootsFromInstall(install)); + } + + return uniquePaths(cands).filter(isAiBase); +} + +export function resolveDesktopAiBase(input = {}) { + return listDesktopPackageRoots(input)[0] || null; +} + +export function resolveDesktopCliScript(input = {}) { + const exe = findDesktopAppExecutable(input); + if (exe) { + const install = path.dirname(exe); + const packed = path.join(install, "resources", "app", "lib", "desktop-cli.js"); + if (isFile(packed)) return path.normalize(packed); + const unpacked = path.join(install, "resources", "app.asar.unpacked", "lib", "desktop-cli.js"); + if (isFile(unpacked)) return path.normalize(unpacked); + if (path.basename(install) === "MacOS") { + const macPacked = path.join(path.dirname(install), "Resources", "app", "lib", "desktop-cli.js"); + if (isFile(macPacked)) return path.normalize(macPacked); + } + } + for (const arg of input.argv ?? process.argv) { + if (typeof arg === "string" && /desktop-cli\.js$/i.test(arg) && isFile(arg)) { + return path.normalize(path.resolve(arg)); + } + } + return ""; +} + +export function cliInvocation(input = {}) { + const exe = findDesktopAppExecutable(input); + const cli = resolveDesktopCliScript(input); + if (!exe || !cli) return null; + return { + execPath: exe, + argvPrefix: ["--expose-internals", cli], + env: { + ELECTRON_RUN_AS_NODE: "1", + DSH_DESKTOP_DEFAULT_PROFILE: "desktop", + }, + }; +} + +export function isSealedRuntimeDir(dir) { + if (!dir) return false; + const n = path.normalize(dir).replace(/\\/g, "/").toLowerCase(); + if (!/(^|\/)bin\/?$/.test(n)) return false; + return ( + n.includes("/host-commands/") || + n.includes("/runtime-commands/") || + n.includes("/dsh desktop/") + ); +} + +export function sealedRuntimeRoots(env = process.env) { + const home = os.homedir(); + const appdata = env.APPDATA || path.join(home, "AppData", "Roaming"); + const localapp = env.LOCALAPPDATA || path.join(home, "AppData", "Local"); + return uniquePaths([ + path.join(appdata, "DSH Desktop", "host-commands"), + path.join(appdata, "DSH Desktop", "runtime-commands"), + path.join(localapp, "DSH Desktop", "host-commands"), + path.join(localapp, "DSH Desktop", "runtime-commands"), + path.join(home, "Library", "Application Support", "DSH Desktop", "host-commands"), + ]); +} + +function walkBinDirs(dir, out, depth) { + if (depth < 0 || !isDir(dir)) return; + const n = dir.replace(/\\/g, "/").toLowerCase(); + if (/(^|\/)bin$/.test(n)) { + out.push(path.normalize(dir)); + return; + } + let ents = []; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const ent of ents) { + if (ent.isDirectory()) walkBinDirs(path.join(dir, ent.name), out, depth - 1); + } +} + +export function listSealedRuntimeBins(env = process.env) { + const out = []; + for (const root of sealedRuntimeRoots(env)) walkBinDirs(root, out, 5); + return uniquePaths(out).filter(isSealedRuntimeDir); +} + +export function restartNote() { + return "正在重启桌面应用…"; +} + +export function restartPlan(input = {}) { + const exe = findDesktopAppExecutable(input); + if (!exe) { + return { kind: "desktop", execPath: "", argv: [], cwd: "", error: "未找到 DSH Desktop.exe,无法重启桌面应用" }; + } + return { + kind: "desktop", + execPath: exe, + argv: [], + cwd: path.dirname(exe), + }; +} + +function helperEnv(payload) { + const env = { ...process.env }; + delete env.DSH_PERMISSION_MODE; + env.ELECTRON_RUN_AS_NODE = "1"; + env.DSH_PURGE_RESTART = JSON.stringify(payload); + return env; +} + +function spawnHelper(helper, payload, opts = {}) { + const plan = restartPlan(); + if (!plan.execPath) throw new Error(plan.error || "未找到 DSH Desktop.exe,无法重启桌面应用"); + const child = spawn(process.execPath, [helper], { + detached: true, + stdio: "ignore", + windowsHide: true, + shell: false, + env: helperEnv({ + kind: "desktop", + execPath: plan.execPath, + argv: plan.argv, + cwd: plan.cwd, + pid: process.pid, + ...payload, + }), + }); + child.unref(); + if (opts.exit !== false) setTimeout(() => process.exit(0), opts.exitAfter ?? 250); +} + +function desktopRuntimeOf(ctx) { + if (!ctx || typeof ctx.get !== "function") return null; + const runtime = ctx.get("desktopRuntime") || ctx.get("desktopActions"); + return runtime && typeof runtime.requestRestart === "function" ? runtime : null; +} + +export function scheduleRestart(request, ctx) { + const runtime = desktopRuntimeOf(ctx); + if (runtime) { + // 只走桌面整应用 relaunch,不要 exit Host(那会先把内嵌 web 单独拉起来)。 + Promise.resolve(runtime.requestRestart()).catch((err) => { + console.warn("[dsh-purge] desktop requestRestart failed:", err); + }); + return; + } + const helper = fileURLToPath(new URL("./restart-desktop.js", import.meta.url)); + spawnHelper(helper, { respawn: true, killApp: true }, { exit: false }); +} + +export function scheduleCleanupRestart({ cleanup = [], ctx } = {}) { + const src = fileURLToPath(new URL("./restart-desktop.js", import.meta.url)); + const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`); + fs.copyFileSync(src, dest); + const runtime = desktopRuntimeOf(ctx); + if (runtime) { + spawnHelper(dest, { cleanup, helper: dest, respawn: false }, { exit: false }); + Promise.resolve(runtime.requestRestart()).catch((err) => { + console.warn("[dsh-purge] desktop uninstall restart failed:", err); + }); + return; + } + spawnHelper(dest, { cleanup, helper: dest, respawn: true, killApp: true }, { exit: false }); +} diff --git a/lib/host.js b/lib/host.js new file mode 100644 index 0000000..302f7db --- /dev/null +++ b/lib/host.js @@ -0,0 +1,28 @@ +import { adapterFor, detectSurface } from "./surface.js"; +import * as desktop from "./desktop.js"; +import * as web from "./web.js"; + +const ADAPTERS = { + web, + desktop, +}; + +export function currentSurface(input) { + return detectSurface(input); +} + +export function hostAdapter(kind = detectSurface()) { + return ADAPTERS[adapterFor(kind)] || web; +} + +export function scheduleRestart(request, ctx) { + return hostAdapter().scheduleRestart(request, ctx); +} + +export function scheduleCleanupRestart(opts) { + return hostAdapter().scheduleCleanupRestart(opts); +} + +export function restartNote() { + return hostAdapter().restartNote(); +} diff --git a/lib/index.js b/lib/index.js index 0465b79..673c1c5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,10 +1,8 @@ import fs from "node:fs"; import { promises as fsp } from "node:fs"; -import path from "node:path"; -import { spawn } from "node:child_process"; import { AsyncLocalStorage } from "node:async_hooks"; -import { fileURLToPath } from "node:url"; import * as core from "./core.js"; +import * as hostctl from "./host.js"; import * as rules from "./rules.js"; import * as updater from "./update.js"; import { @@ -77,7 +75,9 @@ function line(title, value, ok = null) { function renderStatus(state) { const out = []; out.push("dsh-purge 状态 / Status"); + out.push(line("宿主 / surface", state.surface || hostctl.currentSurface())); out.push(line("DSH_HOME", state.dsh_home)); + if (state.desktop_install) out.push(line("桌面安装 / desktop", state.desktop_install)); if (state.ai_base) { out.push(line("插件根 / plugin root", state.ai_base)); for (const [key, fp] of Object.entries(state.files)) { @@ -224,23 +224,12 @@ function installIdentityOverride(ctx, config = {}) { ctx.on("system-prompt/assemble", hook, { global: true, prepend: true }); } -const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"]; - -function desktopShimNeedsPatch(dirs) { - for (const dir of dirs || []) { - for (const name of LAUNCHER_SHIM_NAMES) { - if (core.shimFileStatus(path.join(dir, name)) === "original") return true; - } - } - return false; -} - function shimNeedsPatch(state) { + if (hostctl.currentSurface() === "desktop") return false; return ( state.shim_cmd === "original" || state.shim_ps1 === "original" || - state.shim_bin === "original" || - desktopShimNeedsPatch(state.desktop_runtimes) + state.shim_bin === "original" ); } @@ -673,71 +662,6 @@ export function apply(ctx, config) { installWebServer(ctx, cfg); } -function portFromRequest(request) { - const hostHeader = String(request.headers?.host || ""); - const match = hostHeader.match(/:(\d+)$/); - if (match) return Number(match[1]); - return 3080; -} - -function hostFromRequest(request) { - const hostHeader = String(request.headers?.host || "127.0.0.1"); - return hostHeader.replace(/:\d+$/, "") || "127.0.0.1"; -} - -function restartArgv() { - const root = core.findDshBinRoot(); - const binJs = root ? path.join(root, "lib", "bin.js") : null; - if (binJs && fs.existsSync(binJs)) { - const args = [binJs]; - // 复用当前 argv 的 profile/子命令,入口改走 node + bin.js。 - const rest = process.argv.slice(2).filter((arg) => arg !== "--no-open"); - if (!rest.includes("web") && !rest.includes("desktop")) { - const port = Number(process.env.PORT) || 3080; - rest.unshift("web", "--port", String(port)); - } - rest.push("--no-open"); - return [...args, ...rest]; - } - const argv = process.argv.slice(1).filter((arg) => arg !== "--no-open"); - if (argv[0] && /\.(cmd|bat)$/i.test(argv[0])) { - const dir = path.dirname(argv[0]); - const candidates = [ - path.resolve(dir, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"), - path.resolve(dir, "..", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"), - ]; - const hit = candidates.find((p) => fs.existsSync(p)); - if (hit) argv[0] = hit; - } - argv.push("--no-open"); - return argv; -} - -function scheduleWebRestart(request) { - try { - core.silenceCmdFlash(); - } catch {} - const helper = fileURLToPath(new URL("./restart-web.js", import.meta.url)); - const child = spawn(process.execPath, [helper], { - detached: true, - stdio: "ignore", - windowsHide: true, - shell: false, - env: { - ...core.envForDetachedSpawn(), - DSH_PURGE_RESTART: JSON.stringify({ - execPath: process.execPath, - argv: restartArgv(), - cwd: process.cwd(), - host: hostFromRequest(request), - port: portFromRequest(request), - }), - }, - }); - child.unref(); - setTimeout(() => process.exit(0), 250); -} - function installWebServer(ctx, cfg) { watchWebTreeReady(ctx); ctx.inject(["webServer"], (host) => { @@ -762,7 +686,10 @@ function installWebServer(ctx, cfg) { sendJson(response, 200, { ok: true, ready: true, + surface: state.surface || hostctl.currentSurface(), ai_base: state.ai_base, + desktop_install: state.desktop_install || "", + missing_ai_base: state.ai_base ? "" : core.missingAiBaseMessage(), patches_applied: state.patches_applied, patches_pending: state.patches_pending, patches_skipped: state.patches_skipped || 0, @@ -971,12 +898,17 @@ function installWebServer(ctx, cfg) { } try { const result = await uninstaller.uninstallPurge(); - sendJson(response, result.ok ? 200 : 500, result); + sendJson(response, result.ok ? 200 : 500, { + ...result, + surface: hostctl.currentSurface(), + fullApp: hostctl.currentSurface() === "desktop", + note: result.ok ? hostctl.restartNote() : undefined, + }); if (result.ok) { uninstaller.scheduleCleanupRestart({ request, - restartArgv: restartArgv(), cleanup: result.cleanup, + ctx, }); } } catch (e) { @@ -1033,8 +965,14 @@ function installWebServer(ctx, cfg) { return; } try { - scheduleWebRestart(request); - sendJson(response, 200, { ok: true, note: "正在重启 dsh web…" }); + const surface = hostctl.currentSurface(); + hostctl.scheduleRestart(request, ctx); + sendJson(response, 200, { + ok: true, + surface, + fullApp: surface === "desktop", + note: hostctl.restartNote(), + }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } diff --git a/lib/restart-desktop.js b/lib/restart-desktop.js new file mode 100644 index 0000000..44f6050 --- /dev/null +++ b/lib/restart-desktop.js @@ -0,0 +1,123 @@ +import fs from "node:fs"; +import { execFileSync, spawn } from "node:child_process"; + +const encoded = process.env.DSH_PURGE_RESTART; +if (!encoded) process.exit(1); + +let info; +try { + info = JSON.parse(encoded); +} catch { + process.exit(1); +} + +const cleanup = Array.isArray(info.cleanup) ? info.cleanup : []; + +function spawnEnv() { + const env = { ...process.env }; + delete env.DSH_PERMISSION_MODE; + delete env.DSH_PURGE_RESTART; + for (const key of Object.keys(env)) { + if (key.toUpperCase() === "ELECTRON_RUN_AS_NODE") delete env[key]; + } + return env; +} + +function pidAlive(pid) { + const n = Number(pid); + if (!n) return false; + try { + process.kill(n, 0); + return true; + } catch { + return false; + } +} + +async function waitPidGone(pid) { + if (!pid) { + await new Promise((r) => setTimeout(r, 400)); + return true; + } + for (let i = 0; i < 80; i++) { + if (!pidAlive(pid)) return true; + await new Promise((r) => setTimeout(r, 120)); + } + return !pidAlive(pid); +} + +function rmTree(dir) { + if (!dir) return; + try { + fs.rmSync(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 120 }); + } catch { + // 锁着就留下 + } +} + +function listDesktopPids() { + if (process.platform !== "win32") return []; + try { + const out = execFileSync("tasklist", ["/FI", "IMAGENAME eq DSH Desktop.exe", "/FO", "CSV", "/NH"], { + encoding: "utf8", + windowsHide: true, + timeout: 8000, + }); + const pids = []; + for (const line of String(out || "").split(/\r?\n/)) { + const cols = line.split(","); + const pid = Number(String(cols[1] || "").replace(/"/g, "").trim()); + if (pid) pids.push(pid); + } + return pids; + } catch { + return []; + } +} + +function killOtherDesktopProcesses(keepPid) { + for (const pid of listDesktopPids()) { + if (pid === keepPid || pid === process.pid) continue; + try { + process.kill(pid); + } catch { + // 已经退了 + } + } +} + +if (info.killApp) { + await new Promise((r) => setTimeout(r, 400)); + for (const dir of cleanup) rmTree(dir); + if (info.helper) { + try { fs.unlinkSync(info.helper); } catch { /* ignore */ } + } + killOtherDesktopProcesses(process.pid); + await new Promise((r) => setTimeout(r, 500)); +} else { + const gone = await waitPidGone(info.pid); + if (!gone) process.exit(1); + for (const dir of cleanup) rmTree(dir); + if (info.helper) { + try { fs.unlinkSync(info.helper); } catch { /* ignore */ } + } +} + +if (info.respawn === false) { + process.exit(0); +} + +if (!info.execPath) process.exit(1); + +const child = spawn(info.execPath, Array.isArray(info.argv) ? info.argv : [], { + detached: true, + stdio: "ignore", + cwd: info.cwd || process.cwd(), + env: spawnEnv(), + windowsHide: true, + shell: false, +}); +child.on("error", () => process.exit(1)); +child.unref(); +await new Promise((r) => setTimeout(r, 400)); +process.exit(0); diff --git a/lib/surface.js b/lib/surface.js new file mode 100644 index 0000000..bf499e2 --- /dev/null +++ b/lib/surface.js @@ -0,0 +1,72 @@ +import path from "node:path"; + +/** 当前已接线的宿主面。gui / tui 先能识别,适配仍回退 web。 */ +export const SURFACES = Object.freeze(["web", "desktop", "gui", "tui"]); + +function norm(value) { + return String(value || "").trim().toLowerCase(); +} + +function slash(value) { + return String(value || "").replace(/\\/g, "/").toLowerCase(); +} + +function exeName(execPath) { + return path.basename(String(execPath || "")).toLowerCase(); +} + +export function pathLooksDesktop(p) { + const n = slash(p); + if (!n) return false; + return ( + n.includes("/dsh desktop/") || + n.includes("/dsh desktop.app/") || + n.includes("dsh-desktop") || + n.includes("dsh-plugin-desktop") || + /\/dsh desktop\.exe$/i.test(n) || + n.endsWith("/host-process-entry.js") || + n.endsWith("/desktop-cli.js") + ); +} + +export function isDesktopSurface(input = {}) { + const env = input.env ?? process.env; + const forced = norm(env.DSH_SURFACE); + if (forced === "desktop") return true; + if (forced && SURFACES.includes(forced)) return false; + + const execPath = input.execPath ?? process.execPath; + const name = exeName(execPath); + if (name === "dsh desktop.exe" || name === "dsh desktop") return true; + if (pathLooksDesktop(execPath)) return true; + + const resourcesPath = input.resourcesPath ?? process.resourcesPath; + if (pathLooksDesktop(resourcesPath)) return true; + + const argv = input.argv ?? process.argv; + if ((Array.isArray(argv) ? argv : []).some((arg) => pathLooksDesktop(arg))) return true; + + const parentPort = input.parentPort !== undefined ? input.parentPort : process.parentPort; + if (parentPort && (pathLooksDesktop(execPath) || pathLooksDesktop(resourcesPath))) return true; + + if (env.ELECTRON_RUN_AS_NODE && pathLooksDesktop(execPath)) return true; + return false; +} + +function forcedSurface(env) { + const forced = norm(env.DSH_SURFACE); + return SURFACES.includes(forced) ? forced : ""; +} + +export function detectSurface(input = {}) { + const env = input.env ?? process.env; + const forced = forcedSurface(env); + if (forced) return forced; + if (isDesktopSurface(input)) return "desktop"; + return "web"; +} + +/** gui / tui 尚未单独适配,先走 web 重启与探测。 */ +export function adapterFor(kind) { + return kind === "desktop" ? "desktop" : "web"; +} diff --git a/lib/uninstall.js b/lib/uninstall.js index 7ebc08c..b1c8996 100644 --- a/lib/uninstall.js +++ b/lib/uninstall.js @@ -1,10 +1,8 @@ import fs from "node:fs"; import { promises as fsp } from "node:fs"; -import os from "node:os"; import path from "node:path"; -import { spawn } from "node:child_process"; -import { fileURLToPath } from "node:url"; import * as core from "./core.js"; +import * as hostctl from "./host.js"; import * as rules from "./rules.js"; import * as updater from "./update.js"; @@ -265,30 +263,6 @@ export async function uninstallPurge() { return report; } -export function scheduleCleanupRestart({ request, restartArgv, cleanup = [] } = {}) { - const src = fileURLToPath(new URL("./uninstall-restart.js", import.meta.url)); - const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`); - fs.copyFileSync(src, dest); - const hostHeader = String(request?.headers?.host || "127.0.0.1"); - const portMatch = hostHeader.match(/:(\d+)$/); - const child = spawn(process.execPath, [dest], { - detached: true, - stdio: "ignore", - windowsHide: true, - shell: false, - env: { - ...core.envForDetachedSpawn(), - DSH_PURGE_RESTART: JSON.stringify({ - execPath: process.execPath, - argv: restartArgv || [process.argv[1], "--no-open"], - cwd: process.cwd(), - host: hostHeader.replace(/:\d+$/, "") || "127.0.0.1", - port: portMatch ? Number(portMatch[1]) : 3080, - cleanup, - helper: dest, - }), - }, - }); - child.unref(); - setTimeout(() => process.exit(0), 400); +export function scheduleCleanupRestart(opts = {}) { + hostctl.scheduleCleanupRestart(opts); } diff --git a/lib/update.js b/lib/update.js index f63098f..0a858c6 100644 --- a/lib/update.js +++ b/lib/update.js @@ -5,6 +5,8 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { findDshHome } from "./core.js"; +import { adapterFor, detectSurface } from "./surface.js"; +import { cliInvocation } from "./desktop.js"; const REPO = "YuJunZhiXue/dsh-purge"; const BRANCH = "master"; @@ -156,6 +158,7 @@ function resolveDshBin() { const names = process.platform === "win32" ? ["dsh.cmd", "dsh.exe", "dsh"] : ["dsh"]; const dirs = [ path.join(home, "..", "npm-global"), + path.join(home, "..", "npm-global-0.1.5-rc.2"), path.join(home, "..", "npm-global-0.1.5-rc.1"), path.join(home, "bin"), ]; @@ -169,6 +172,23 @@ function resolveDshBin() { } export function runDshPlugin(profile, args) { + if (adapterFor(detectSurface()) === "desktop") { + const inv = cliInvocation(); + if (!inv) throw new Error("找不到 DSH Desktop CLI"); + execFileSync(inv.execPath, [...inv.argvPrefix, "plugin", "--profile", profile, ...args], { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + timeout: 120000, + env: { + ...process.env, + ...inv.env, + DSH_HOME: findDshHome(), + CI: "1", + }, + }); + return; + } const bin = resolveDshBin(); if (!bin) throw new Error("找不到 dsh"); execFileSync(bin, ["plugin", "--profile", profile, ...args], { diff --git a/lib/web.js b/lib/web.js new file mode 100644 index 0000000..91ad548 --- /dev/null +++ b/lib/web.js @@ -0,0 +1,97 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import * as core from "./core.js"; + +export function restartNote() { + return "正在重启 dsh web…"; +} + +export function portFromRequest(request) { + const host = String(request?.headers?.host || ""); + const m = host.match(/:(\d+)$/); + if (m) return Number(m[1]); + return Number(process.env.PORT) || 3080; +} + +export function hostFromRequest(request) { + const hostHeader = String(request?.headers?.host || "127.0.0.1"); + return hostHeader.replace(/:\d+$/, "") || "127.0.0.1"; +} + +export function restartArgv({ + argv = process.argv, + findBinRoot = core.findDshBinRoot, +} = {}) { + const root = findBinRoot(); + const binJs = root ? path.join(root, "lib", "bin.js") : null; + if (binJs && fs.existsSync(binJs)) { + const rest = argv.slice(2).filter((arg) => arg !== "--no-open"); + if (!rest.includes("web") && !rest.includes("desktop")) { + const port = Number(process.env.PORT) || 3080; + rest.unshift("web", "--port", String(port)); + } + rest.push("--no-open"); + return [binJs, ...rest]; + } + const next = argv.slice(1).filter((arg) => arg !== "--no-open"); + if (next[0] && /\.(cmd|bat)$/i.test(next[0])) { + const dir = path.dirname(next[0]); + const candidates = [ + path.resolve(dir, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"), + path.resolve(dir, "..", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"), + ]; + const hit = candidates.find((p) => fs.existsSync(p)); + if (hit) next[0] = hit; + } + next.push("--no-open"); + return next; +} + +function spawnRestartHelper(helper, payload, exitAfter = 250) { + try { + core.silenceCmdFlash(); + } catch {} + const child = spawn(process.execPath, [helper], { + detached: true, + stdio: "ignore", + windowsHide: true, + shell: false, + env: { + ...core.envForDetachedSpawn(), + DSH_PURGE_RESTART: JSON.stringify(payload), + }, + }); + child.unref(); + setTimeout(() => process.exit(0), exitAfter); +} + +export function scheduleRestart(request) { + const helper = fileURLToPath(new URL("./restart-web.js", import.meta.url)); + spawnRestartHelper(helper, { + kind: "web", + execPath: process.execPath, + argv: restartArgv(), + cwd: process.cwd(), + host: hostFromRequest(request), + port: portFromRequest(request), + }); +} + +export function scheduleCleanupRestart({ request, restartArgv: argv, cleanup = [] } = {}) { + const src = fileURLToPath(new URL("./uninstall-restart.js", import.meta.url)); + const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`); + fs.copyFileSync(src, dest); + spawnRestartHelper(dest, { + kind: "web", + execPath: process.execPath, + argv: argv || restartArgv(), + cwd: process.cwd(), + host: hostFromRequest(request), + port: portFromRequest(request), + cleanup, + helper: dest, + }, 400); +} diff --git a/package.json b/package.json index bb41e76..93b6760 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.6", + "version": "1.1.7", "description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐", "type": "module", "main": "lib/index.js", @@ -70,5 +70,5 @@ "engines": { "node": ">=18" }, - "dshTarget": "0.1.5-rc.1" + "dshTarget": "0.1.5-rc.2" }