Compare commits

...
12 Commits
Author SHA1 Message Date
叫我小杨同学andCursor c711311c34 fix: 发布 1.1.44,回退后下一句按新消息发,启动就注入默认提示词。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 20:36:12 +08:00
叫我小杨同学andCursor b8d9b4db9a fix: 发布 1.1.44,提示词按模式注入并让子代理吃到同一份。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 19:18:54 +08:00
叫我小杨同学andCursor c29d78b291 fix: 发布 1.1.44,提示词按模式注入并让子代理吃到同一份。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 19:18:15 +08:00
Cracer 075839af86 fix: permissionPresetsOf 未 inject 时不再抛错。(#52)
直访和 ctx.get 都放进 try。
2026-10-01 16:25:07 +08:00
叫我小杨同学andCursor 0f91546cc0 fix: 解包失败时放回升级前的目录。
升级脚本先挪走旧目录后,解开中途失败会把那一份放回去。补丁没写完不清除升级标记,下次启动再试。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 13:30:45 +08:00
叫我小杨同学andCursor 10a597d6ff fix: 回退只撤最后一轮,提示词只保留一份。
解包改到旁边的目录,失败时放回上一份。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 13:10:15 +08:00
叫我小杨同学andCursor 3cede10253 fix: 发布 1.1.43,没定位到宿主时不再把补丁全部显示成跳过。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 12:20:44 +08:00
叫我小杨同学andCursor 9ab3b0fb9a fix: 发布 1.1.42,写明自己的服务器怎么登记。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 02:00:05 +08:00
叫我小杨同学andCursor 7181ae5750 fix: 已登记的 IP 或主机名不再被地区拦截。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 22:26:54 +08:00
叫我小杨同学 59d176eac8 merge: 合入 #51,保留 0.2.0 旧锚点并补上 0.1.x 入口。 2026-09-30 22:12:03 +08:00
叫我小杨同学andCursor 7c3eb548c0 fix: 新对话把提示词放到系统提示最前,面板改为白墨玻璃。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 21:45:44 +08:00
qianxuno ce279104d6 fix: 修正 escalation 目标解析、desktop-shell 入口探测,并重新对齐 0.1.x 锚点
1) targetFiles 的 "escalation" 用 firstExisting,只认 lib/types/escalation.js(编译残留),
   而运行时加载的是包入口 lib/index.js —— escalation 实现被 bundle 内联进了它。
   结果 #13/#14/#34/#35 的替换全部落在不被执行的文件上:设置页显示「已应用」,
   运行行为零变化(可对照 lib/index.js 里仍留着原版
   `[sandbox: escalation available ...]` 与 `[sandbox: file access denied ...]`)。
   改为 allExisting 并让 lib/index.js 排前,两个文件都覆盖。

2) officialShellMain() 只找 <app>/lib/main.js;官方桌面壳 0.1.3 起入口直接在
   <app>/main.js,于是 desktop-shell 永远未定位、#45/#46 被误报成「文件缺失」。
   两种布局都探测。

3) #15 补 dsh-sandbox-local 新版 confine(argv, policy) 锚点(去掉 async/signal 与
   policy 规范化),旧签名保留。
4) #23 file 补 tool-subagent(0.1.7 起深度默认在工具参数上),新增
   z.union([...z.const("provider-managed")]).default(3) 锚点,旧锚点保留。
5) #47 补 pi-ai 新版 context.systemPrompt 锚点,旧 initialSystemText 锚点保留。

所有旧锚点全部保留,向后兼容 0.1.5 / 0.1.6 / 0.1.7 / 0.2.0 环境。

实测环境:DSH Desktop 0.1.3.0 + harness 包 0.1.2-rc.1(安装形态
resources/app.asar.unpacked/dsh/node_modules/@deepseek-ai,与 resources/runtime
是 junction 同一份文件)。
修复前 30/45 已清洗、9 条 skipped/missing;修复后 36/45、0 待清洗,
涉及改写的文件全部 node --check 通过。
2026-09-30 11:07:28 +08:00
17 changed files with 1814 additions and 322 deletions

No files matched your search

+34 -8
View File
@@ -37,6 +37,7 @@
- [Install](#install)
- [Preview](#preview)
- [Usage](#usage)
- [Own servers](#own-servers)
- [How it works](#how-it-works)
- [Restore](#restore)
- [Releases](#releases)
@@ -63,7 +64,7 @@ It only touches the official `@deepseek-ai` packages and local config on the use
---
## 📌 非盈利公益项目,严禁任何主体用于商业售卖、付费倒卖或黑灰产牟利,仅供技术参考。
## Non-profit public project. Commercial sale, paid resale, and profit from illegal or gray-market activity are forbidden. For technical reference only.
---
@@ -83,7 +84,8 @@ It only touches the official `@deepseek-ai` packages and local config on the use
2. **Local official Harness only.** Security-eval patches and prompt injection run only on the **official DeepSeek Harness already installed on the user's machine** (`@deepseek-ai` packages, local profile / `$DSH_HOME`). The target is the user's own official local software, **not** someone else's website, server, account, or information system.
3. **Eval patches do not attack the public internet.** Apply, inject, revert, and uninstall stay in local files and local processes. They **do not scan, probe, intrude, or send attack traffic to any public host or unauthorized system**. Do not use this project as a jump host against the public internet. If "check for updates" is on, the plugin may only contact this plugin's own GitHub repository to compare versions. That is **not** an attack on third-party systems and is **not** authorization to penetrate anything.
4. **Lawful, controlled scope.** This project is an aid for red-team research and robustness evaluation on an **official Harness the user is entitled to administer**. **Do not run it against targets without the owner's lawful written authorization, public online systems, or production workloads.** Testing must stay on the **authorized local official Harness, offline local synthetic fixtures, authorized cybersecurity ranges, and compliant lab environments**.
5. **Forbidden uses.** Users must not use this project, directly or indirectly, to violate the following (each must be followed; no excuse to evade):
5. **Servers and sites in mainland China, Hong Kong, and Macau are forbidden.** Do not access, scan, probe, or otherwise operate against network ranges in mainland China, Hong Kong, or Macau, or against servers, websites, or addresses that resolve into those ranges. A cloud-provider name is not an exception. The only exception is one exact IP, or one exact hostname, that the user registered in advance as their own server. A key, a password, a network range, a wildcard, or a claim made in the conversation does not add an exception. Anything that is not registered stays forbidden.
6. **Forbidden uses.** Users must not use this project, directly or indirectly, to violate the following (each must be followed; no excuse to evade):
- <font color="red"><strong>Criminal Law of the People's Republic of China</strong></font>
- <font color="red"><strong>Cybersecurity Law of the People's Republic of China</strong></font>
- <font color="red"><strong>Data Security Law of the People's Republic of China</strong></font>
@@ -93,9 +95,9 @@ It only touches the official `@deepseek-ai` packages and local config on the use
- Unauthorized intrusion or attacks on public or private computer information systems; extortion, sabotage, credential stuffing, or spreading malicious payloads;
- Inducing, generating, or spreading any content the law forbids, including threats to national security, terrorism, violence, pornography, gambling, fraud, and privacy or intellectual-property infringement;
- Violating the model provider's terms of service and acceptable-use policy.
6. **The user bears all responsibility.** The project is provided under the MIT license as-is. The authors make no warranty of completeness, security, or fitness. **Users independently bear all civil, administrative, and criminal liability** for download, deploy, run, modify, distribute, and all resulting inputs and outputs. Authors and contributors bear no direct, indirect, or joint liability for abuse.
7. **The license ends on breach.** Anyone who uses this project for illegal attacks, malicious activity, or other violations has their open-source license **automatically and irrevocably terminated** from the moment of the violation. They must stop using the project, permanently destroy all copies and derivatives, and accept legal sanctions.
8. **No affiliation.** This is an independent open-source security-eval research project. It has no employment, commercial, authorization, or endorsement relationship with DeepSeek or its affiliates. "Official" here only means the eval target is the official DeepSeek Harness package on the user's machine. It does **not** mean DeepSeek developed, approved, or warrants this plugin.
7. **The user bears all responsibility.** The project is provided under the MIT license as-is. The authors make no warranty of completeness, security, or fitness. **Users independently bear all civil, administrative, and criminal liability** for download, deploy, run, modify, distribute, and all resulting inputs and outputs. Authors and contributors bear no direct, indirect, or joint liability for abuse.
8. **The license ends on breach.** Anyone who uses this project for illegal attacks, malicious activity, or other violations has their open-source license **automatically and irrevocably terminated** from the moment of the violation. They must stop using the project, permanently destroy all copies and derivatives, and accept legal sanctions.
9. **No affiliation.** This is an independent open-source security-eval research project. It has no employment, commercial, authorization, or endorsement relationship with DeepSeek or its affiliates. "Official" here only means the eval target is the official DeepSeek Harness package on the user's machine. It does **not** mean DeepSeek developed, approved, or warrants this plugin.
</font>
@@ -601,9 +603,11 @@ The first time you open Drill you read the notice, wait out the countdown, scrol
![Patches](docs/preview/settings.png)
**Rule sets**
**Own servers**
![Rule sets](docs/preview/rules.png)
On the Clean page, under Prompt. One host per line, then Save list. Steps are in [Own servers](#own-servers).
![Own servers](docs/preview/own-servers-en.png)
| Area | What it shows |
|---|---|
@@ -613,6 +617,7 @@ The first time you open Drill you read the notice, wait out the countdown, scrol
| Light / Ink | card appearance |
| Patches | grouped status, Apply, Restore, or Uninstall |
| Prompt | edit `prompt-inject.md` as the session override |
| Own servers | one IP or exact hostname per line, saved to `$DSH_HOME/net-scope-allow.txt` |
| Rule sets | multiple `AGENTS.md` / `CLAUDE.md`; Enable writes under `$DSH_HOME`, Delete removes the row |
| Skills | import a zip or folder into this host’s official `$DSH_HOME/skills/<id>/SKILL.md` (web and desktop each use their own home; no drive letter is hardcoded); DSH owns match, load, and `/name`. You can also delete that folder yourself |
@@ -631,6 +636,8 @@ dsh-purge/
│ ├── dock-auth.png
│ ├── dock-clean.png
│ ├── dock-drill.png
│ ├── own-servers.png
│ ├── own-servers-en.png
│ ├── rules.png
│ └── settings.png
├── lib/
@@ -656,7 +663,7 @@ dsh-purge/
└── README.zh-CN.md
```
Runtime user files: `$DSH_HOME/prompt-inject.md`, `$DSH_HOME/rules/`, `$DSH_HOME/skills/`. If `DSH_HOME` is unset, the launcher-adjacent `.dsh` wins over `~/.dsh`. Skills are not part of the `dsh-purge` inject section and do not replace the prompt.
Runtime user files: `$DSH_HOME/prompt-inject.md`, `$DSH_HOME/rules/`, `$DSH_HOME/skills/`, `$DSH_HOME/net-scope-allow.txt`. If `DSH_HOME` is unset, the launcher-adjacent `.dsh` wins over `~/.dsh`. Skills are not part of the `dsh-purge` inject section and do not replace the prompt.
---
@@ -681,6 +688,25 @@ After a successful Apply, the host restarts so patched packages load; you can al
The composer **Undo** button drops the last turn and puts the last user sentence back in the input. On the main agent you can rewind once or the whole last round (including subagents). After rewind, send only what is in the box now. `/rewind` does the same. The host cannot truncate a session in place, so rewind opens another session for the shortened transcript and removes the old one from the sidebar. Repeating undo does not leave a stack of branches in the list.
### Own servers
Addresses in mainland China, Hong Kong, and Macau stay forbidden unless that one host was registered first. Saying “this is my server” in chat does not allow it. A key or a password does not allow it either.
The box sits under Prompt. If the dock does not show it yet, quit DeepSeek Harness completely and open it again.
1. Click **dsh-purge** beside the session title and stay on **Clean**.
2. Scroll past **Prompt**. **Own servers** is the next block.
3. Put one host on each line, in one of these forms:
- `203.0.113.10` — one IP.
- `my-vps.example.com` — one exact hostname. After you save, the addresses that hostname resolves to at lookup time are allowed too.
- `alice@my-vps.example.com` — the account only identifies this form. It does not prove the machine is yours.
4. Click **Save list**. The list is written to `$DSH_HOME/net-scope-allow.txt`.
5. Keys, passwords, ranges, and wildcards are dropped on save. Unlisted mainland China, Hong Kong, and Macau addresses stay forbidden.
`203.0.113.10` and `example.com` above are only examples of the form. Replace them with your own host before you save.
![Own servers](docs/preview/own-servers-en.png)
---
## Local checks
+35 -5
View File
@@ -37,6 +37,7 @@
- [安装](#安装)
- [界面](#界面预览)
- [使用](#使用)
- [自己的服务器](#自己的服务器)
- [工作原理](#工作原理)
- [还原](#还原)
- [更新](#更新)
@@ -83,7 +84,8 @@ Harness 不只是把问题交给模型。它还会在运行时改提示词、审
2. **只作用于本机官方 Harness**:安全评测补丁、提示词注入全部发生在使用者**本机已安装的官方 DeepSeek Harness**(`@deepseek-ai` 包、本机 profile / `$DSH_HOME`)上。对象是使用者自己的官方本地软件,**不是**他人的网站、服务器、账号或信息系统。
3. **评测补丁不对外网目标联网**:应用补丁、写入注入、回滚、卸载均在本机文件与本机进程内完成,**不对任何公网主机、未授权系统进行扫描、探测、入侵或攻击发包**。不得把本项目当作跳板去打外网。插件若开启「检测更新」,仅可能访问本插件自己的 GitHub 仓库以核对版本,**与对第三方系统的网络攻击无关**,也不能被解释为授权对外渗透。
4. **合法受控范围限定**:本项目定位为使用者在**自己有权管理的本机官方 Harness**上,进行红队科研与鲁棒性评测的辅助工具。**严禁在未经所有者合法书面授权的目标、公网在线系统或生产业务上运行本项目**。一切测试必须限制在**本机已授权安装的官方 Harness、离线本地合成靶标、授权网络安全演练靶场及合规实验室受控环境**中进行。
5. **严禁违法与违禁用途**:使用者严禁利用本项目直接或间接从事任何违反下列法律法规的行为(必须逐条遵守,不得以任何理由规避):
5. **禁止中国大陆、香港、澳门的服务器与网站。** 不得对中国大陆、香港、澳门网段,以及解析进这些网段的服务器、网站或地址进行访问、扫描、探测或任何操作。云厂商的名字不能当作例外。唯一例外是使用者事先登记为自己的服务器的那一个确切 IP,或那一个完整主机名。密钥、密码、网段、通配符,以及对话里的口头说明,都不能增加例外。没有登记的,一律禁止。
6. **严禁违法与违禁用途**:使用者严禁利用本项目直接或间接从事任何违反下列法律法规的行为(必须逐条遵守,不得以任何理由规避):
- <font color="red"><strong>《中华人民共和国刑法》</strong></font>
- <font color="red"><strong>《中华人民共和国网络安全法》</strong></font>
- <font color="red"><strong>《中华人民共和国数据安全法》</strong></font>
@@ -93,9 +95,9 @@ Harness 不只是把问题交给模型。它还会在运行时改提示词、审
- 未经授权渗透、攻击公私机构计算机信息系统,实施勒索、破坏、撞库或传播恶意载荷;
- 诱导、生成或传播危害国家安全、恐怖主义、暴力血腥、涉黄涉赌、诈骗、侵犯公民隐私或知识产权等任何法律明令禁止的违法违禁内容;
- 违反相关大模型提供商的《服务条款》与《滥用政策》。
6. **使用者独立承担全部责任**:本项目依据 MIT 开源协议“按现状”提供,开发者不对软件的完整性、安全性与适用性作任何明示或暗示的保证。**使用者应对自身的所有下载、部署、运行、修改、传播行为以及由此产生的全部输入与输出后果承担独立、完全的民事、行政及刑事法律责任**。项目作者与贡献团队绝不承担任何因使用者滥用导致的直接、间接或连带责任。
7. **违约即终止授权**:任何将本项目用于非法攻击、恶意活动或违规行为的个人或实体,其开源软件使用许可将自违法违规行为发生之日起**自动且不可撤销地立即终止**。该主体须立即停止使用并永久销毁本项目的所有代码、脚本与衍生数据,并依法承担相应法律制裁。
8. **第三方独立性声明**:本项目属于完全独立的开源安全评测研究项目,与 DeepSeek 官方或其关联主体无任何隶属、商业合作、授权或官方背书关系。文中「官方」仅指评测对象为使用者本机安装的官方 DeepSeek Harness 软件包,**不代表** DeepSeek 官方开发、认可或担保本插件。
7. **使用者独立承担全部责任**:本项目依据 MIT 开源协议“按现状”提供,开发者不对软件的完整性、安全性与适用性作任何明示或暗示的保证。**使用者应对自身的所有下载、部署、运行、修改、传播行为以及由此产生的全部输入与输出后果承担独立、完全的民事、行政及刑事法律责任**。项目作者与贡献团队绝不承担任何因使用者滥用导致的直接、间接或连带责任。
8. **违约即终止授权**:任何将本项目用于非法攻击、恶意活动或违规行为的个人或实体,其开源软件使用许可将自违法违规行为发生之日起**自动且不可撤销地立即终止**。该主体须立即停止使用并永久销毁本项目的所有代码、脚本与衍生数据,并依法承担相应法律制裁。
9. **第三方独立性声明**:本项目属于完全独立的开源安全评测研究项目,与 DeepSeek 官方或其关联主体无任何隶属、商业合作、授权或官方背书关系。文中「官方」仅指评测对象为使用者本机安装的官方 DeepSeek Harness 软件包,**不代表** DeepSeek 官方开发、认可或担保本插件。
</font>
@@ -605,6 +607,12 @@ dsh-purge --uninstall
![规则集](docs/preview/rules.png)
**自己的服务器**
在清洗页,提示词下面。每行一台,点保存名单。步骤见 [自己的服务器](#自己的服务器)。
![自己的服务器](docs/preview/own-servers.png)
| 区域 | 说明 |
|---|---|
| dsh-purge | 会话标题旁的按钮,打开或收起右侧栏 |
@@ -613,6 +621,7 @@ dsh-purge --uninstall
| 白 / 墨 | 设置卡片外观 |
| 补丁 | 分组查看状态,应用、还原或卸载 |
| 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 |
| 自己的服务器 | 每行登记一个 IP 或完整主机名,保存后写入 `$DSH_HOME/net-scope-allow.txt` |
| 规则集 | 多套 `AGENTS.md` / `CLAUDE.md`;启用写入 `$DSH_HOME`,删除从列表去掉 |
| Skill | 导入压缩包或文件夹到当前宿主官方目录 `$DSH_HOME/skills/<id>/SKILL.md`(Web / 桌面各用自己的主目录,不写死盘符);命中、加载、`/名称` 由 DSH 负责。也可自己删该文件夹 |
@@ -631,6 +640,8 @@ dsh-purge/
│ ├── dock-auth.png
│ ├── dock-clean.png
│ ├── dock-drill.png
│ ├── own-servers.png
│ ├── own-servers-en.png
│ ├── rules.png
│ └── settings.png
├── lib/
@@ -656,7 +667,7 @@ dsh-purge/
└── README.zh-CN.md
```
运行时用户文件:`$DSH_HOME/prompt-inject.md`、`$DSH_HOME/rules/`、`$DSH_HOME/skills/`。未设 `DSH_HOME` 时,优先用 dsh 安装目录旁边的 `.dsh`,再退回 `~/.dsh`。Skill 不进 `dsh-purge` 注入段,也不顶替提示词。
运行时用户文件:`$DSH_HOME/prompt-inject.md`、`$DSH_HOME/rules/`、`$DSH_HOME/skills/`、`$DSH_HOME/net-scope-allow.txt`。未设 `DSH_HOME` 时,优先用 dsh 安装目录旁边的 `.dsh`,再退回 `~/.dsh`。Skill 不进 `dsh-purge` 注入段,也不顶替提示词。
---
@@ -684,6 +695,25 @@ purge_status purge_apply purge_revert
输入框旁的「回退」会丢掉最近一轮对话,并把上一句填回输入框;聊天里 `/rewind` 同样可用。宿主不能在原会话里截断,所以回退会另开一条承载截断后的内容,并把原来那条从侧边栏移出。多退几次不会在列表里堆出一串分支。
### 自己的服务器
中国大陆、香港、澳门的地址默认禁止。只有事先登记的那一台可以例外。在对话里说「这是我的服务器」不会放行。密钥和密码也不会。
这一栏在提示词下面。若侧栏里还没有它,先完全退出 DeepSeek Harness,再重新打开。
1. 点会话标题旁的 **dsh-purge**,停在 **清洗**。
2. 往下滚过 **提示词**,下面就是 **自己的服务器**。
3. 每行只写一台,用下面三种写法之一:
- `203.0.113.10`:一个 IP。
- `my-vps.example.com`:一个完整主机名。保存后,这个主机名当时解析出来的地址也会放行。
- `alice@my-vps.example.com`:账号只用来认出这种写法,不能证明这台机器属于你。
4. 点 **保存名单**。名单写在 `$DSH_HOME/net-scope-allow.txt`。
5. 密钥、密码、网段和通配符会在保存时丢掉。没有写进名单的大陆、香港、澳门地址仍然禁止。
上面的 `203.0.113.10` 和 `example.com` 只是写法示例,不是放行地址。把它们换成你自己的那一台再保存。
![自己的服务器](docs/preview/own-servers.png)
---
## 本地校验
+180 -77
View File
@@ -129,11 +129,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
const TARGETS = ["AGENTS.md", "CLAUDE.md"];
const PATCH_GROUPS = [
{ key: "prompt", ids: [1, 2, 3, 4, 5, 25, 26, 27, 28, 32] },
{ key: "code", ids: [6, 7, 8] },
{ key: "prompt", ids: [1, 2, 3, 4, 5, 25, 26, 28, 32, 43, 50, 53, 54] },
{ key: "code", ids: [6, 7, 8, 42, 45, 46, 51, 52, 55, 56] },
{ key: "engine", ids: [9, 10, 11, 12, 13, 14, 15, 16, 35] },
{ key: "tools", ids: [17, 18, 19, 21, 22, 23, 24, 29, 30, 31, 33, 34, 36, 37] },
{ key: "tools", ids: [17, 18, 19, 21, 22, 23, 24, 29, 30, 31, 33, 34, 36, 37, 48] },
{ key: "compat", ids: [38, 39, 40] },
{ key: "dsh20", ids: [47, 49] },
];
const zh = {
@@ -174,7 +175,13 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"theme.ink": "墨",
"purge.title": "补丁",
"override.title": "提示词",
"metric.purged": "补丁",
"own.title": "自己的服务器",
"own.hint": "每行一个 IP 或完整主机名。可以写成 账号@主机,账号只用来认出这种写法。主机名会连同它当时解析出的地址一起放行。不要写密钥、密码、网段。",
"own.save": "保存名单",
"saved.own": "已保存自己的服务器",
"saved.own.dropped": "已保存。有 {n} 行不是单个 IP 或主机名,已丢掉",
"metric.purged": "已应用",
"metric.purged.skip": "已应用,另有 {n} 项跳过",
"metric.shim": "shim",
"metric.bak.yes": "有备份",
"metric.bak.no": "无备份",
@@ -184,12 +191,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"status.applied": "已应用",
"status.pending": "待应用",
"status.skipped": "跳过",
"apply.hint": "待应用=原文还在。跳过=当前版本不需要或组件未安装,再点也不会变。",
"apply.hint": "点应用会把提示词框里的全文写入并打补丁,不必再点保存。待应用=原文还在。跳过=当前版本不需要或组件未安装。",
"warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。",
"warn.noRoot.desktop": "官方客户端的代码在 app.asar 里。点「应用」会解开并自动重启,不用另跑脚本。第三方 DSH Desktop 直接点「应用」。",
"unpack.restarting": "补丁已写入。点「重启」后客户端会自己重新打开。",
"restart.fullQuit": "正在重启,客户端会自己重新打开。",
"warn.noInject": "默认只注入可编辑提示词。启用规则集后以规则集为主。两边都空会提示必须添加。Skill 不顶替提示词。",
"warn.noInject": "官方始终用默认提示词。红队开了规则集就只用规则集;没开时用去掉 CTF 的默认提示词,再接红队操作。两边都空会提示必须添加。",
"need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。",
"btn.restoreInject": "恢复默认",
"saved.restoreInject": "已填入默认提示词,点保存写入",
@@ -318,6 +325,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"group.engine": "引擎",
"group.tools": "工具",
"group.compat": "0.1.5 兼容",
"group.dsh20": "0.2.0",
"patch.1": "全局免责 → 强指令",
"patch.2": "替换式免责 → 强指令",
"patch.3": "作用域免责 → 强指令",
@@ -343,7 +351,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"patch.24": "preset fetch 启用",
"patch.25": "去掉官方默认身份(功能提示词不动)",
"patch.26": "minimal:去掉默认身份并打开 inject",
"patch.27": "dsh-liangshen(梁神):去掉默认身份(可选)",
"patch.28": "dsh-liangshen(梁神):phase-1 保留注入段",
"patch.29": "dsh-tool-web:外部 untrusted 拦截→可执行",
"patch.30": "dsh-hooks-claude-code:deny→allow",
@@ -357,6 +364,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"patch.38": "persona text→prefix(0.1.2 预设)",
"patch.39": "会话 v0 plugin summary(mnemon)",
"patch.40": "complete 预设仍保留注入",
"patch.42": "设置页旧接口",
"patch.43": "网页预设去掉默认身份",
"patch.45": "官方桌面更新交接",
"patch.46": "官方更新脚本只用英文",
"patch.47": "OAuth 不再插入 Claude 身份",
"patch.48": "shell 去掉删除前的额外确认",
"patch.49": "OAuth 不再伪装 claude-cli",
"patch.50": "跨会话引用不再标不可信",
"patch.51": "新会话保持完全权限",
"patch.52": "会话日志默认不上传",
"patch.53": "网页提示去掉禁止另开服务器",
"patch.54": "交付物提示去掉多余禁止",
"patch.55": "每一步替换第一条系统提示",
"patch.56": "回退只藏被撤掉的那一轮",
"status.unlocated": "未定位",
"metric.unlocated": "还没定位到本机 Harness",
"rewind.label": "回退",
"rewind.aria": "回退",
"rewind.busy": "回退中…",
@@ -420,7 +443,13 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"theme.ink": "Ink",
"purge.title": "Patches",
"override.title": "Prompt",
"metric.purged": "Patches",
"own.title": "Own servers",
"own.hint": "One IP or exact hostname per line. account@host is accepted; the account only identifies that host. A hostname also allows the addresses it resolves to. Do not enter a key, a password, or a range.",
"own.save": "Save list",
"saved.own": "Own servers saved",
"saved.own.dropped": "Saved. {n} lines were not a single IP or hostname and were dropped",
"metric.purged": "Applied",
"metric.purged.skip": "Applied, {n} skipped",
"metric.shim": "shim",
"metric.bak.yes": "Backup",
"metric.bak.no": "No backup",
@@ -430,12 +459,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"status.applied": "Applied",
"status.pending": "Pending",
"status.skipped": "Skipped",
"apply.hint": "Pending = original text still present. Skipped = not needed for this version or component not installed.",
"apply.hint": "Apply writes the prompt in the box and the patches. A separate save is unnecessary. Pending = original text still present. Skipped = not needed for this version or the component is not installed.",
"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": "Official Harness keeps its code in app.asar. Apply unpacks it and restarts the app. Third-party DSH Desktop: just Apply.",
"unpack.restarting": "Patches are written. Click Restart and the client opens again by itself.",
"restart.fullQuit": "Restarting. The client will open again by itself.",
"warn.noInject": "By default only the editable prompt is injected. An enabled rule set takes over. If both are empty you will be asked to add a prompt. Skills do not replace the prompt.",
"warn.noInject": "Official mode always uses the default prompt. Red team uses only the active rule set; otherwise it uses the default prompt without the CTF section, then the red team steps. If both are empty you will be asked to add a prompt.",
"need.prompt": "Both the prompt and the rule set are empty. Add a prompt, or enable a rule that has content.",
"btn.restoreInject": "Reset default",
"saved.restoreInject": "Default prompt loaded. Save to write.",
@@ -564,6 +593,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"group.engine": "Engine",
"group.tools": "Tools",
"group.compat": "0.1.5 compat",
"group.dsh20": "0.2.0",
"patch.1": "Global disclaimer → mandate",
"patch.2": "Replacement disclaimer → mandate",
"patch.3": "Scope disclaimer → mandate",
@@ -589,7 +619,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"patch.24": "preset fetch on",
"patch.25": "Strip official default identity (keep feature prompts)",
"patch.26": "minimal: strip identity, open inject",
"patch.27": "dsh-liangshen: strip default identity (optional)",
"patch.28": "dsh-liangshen: keep inject in phase-1",
"patch.29": "dsh-tool-web: untrusted framing → usable data",
"patch.30": "dsh-hooks-claude-code: deny→allow",
@@ -603,6 +632,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
"patch.38": "persona text→prefix (0.1.2 presets)",
"patch.39": "session v0 plugin summary (mnemon)",
"patch.40": "Keep inject when a complete prompt is set",
"patch.42": "Settings legacy API",
"patch.43": "Strip identity from web presets",
"patch.45": "Official desktop update handoff",
"patch.46": "Official update script stays ASCII",
"patch.47": "OAuth no longer inserts Claude identity",
"patch.48": "Shell drops extra delete caution",
"patch.49": "OAuth no longer mimics claude-cli",
"patch.50": "Session references are not marked untrusted",
"patch.51": "Fresh session stays on full access",
"patch.52": "Session log upload off by default",
"patch.53": "Web prompt drops do-not-start",
"patch.54": "Deliverable prompt drops extra prohibition",
"patch.55": "Replace the first system prompt every step",
"patch.56": "Rewind hides only the cut range",
"status.unlocated": "Not located",
"metric.unlocated": "This install was not found yet",
"rewind.label": "Undo",
"rewind.aria": "Undo",
"rewind.busy": "Undoing…",
@@ -753,12 +798,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
.dshp-dock-body .dshp-root[data-theme="white"]{--dshp-ink:#1a1916;--dshp-mute:#534e46;--dshp-ok:#1f5c38;--dshp-warn:#8a5a12;--dshp-bad:#9a3434;--dshp-paper:#fffcf7;--dshp-fill:#ebe7df;--dshp-line:#d0caba;--dshp-accent:#3f6b52;--dshp-accent-soft:#d7e6dc;--dshp-bg:#f4f2ec}
.dshp-dock-body .dshp-root[data-theme="dusk"]{--dshp-ink:#f4f1ea;--dshp-mute:#c9c3b8;--dshp-ok:#9fd0ad;--dshp-warn:#e0c08a;--dshp-bad:#e0b0b0;--dshp-paper:#32312d;--dshp-fill:#353430;--dshp-line:#4a4740;--dshp-accent:#9bb5a6;--dshp-accent-soft:#3a433d;--dshp-bg:#2a2926}
.dshp-dock-body .dshp-panel,.dshp-dock-body .dshp-metric,.dshp-dock-body .dshp-group,.dshp-dock-body .dshp-editor,.dshp-dock-body .dshp-active,.dshp-dock-body .dshp-ask,.dshp-dock-body .dshp-create,.dshp-dock-body .dshp-switch{background:color-mix(in srgb,var(--dshp-ink) 6%,transparent)!important;backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px)}
.dshp-dock-body .dshp-root[data-theme="white"] .dshp-panel,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-metric,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-group,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-editor,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-active,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-ask,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-create,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-switch,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-rulelist,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-table,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-ruleitem{background:#fffcf7!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;border-color:#d0caba!important;color:#1a1916!important}
.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-panel,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-metric,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-group,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-editor,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-active,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-ask,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-create,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-switch,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-rulelist,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-table,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-ruleitem{background:#32312d!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;border-color:#4a4740!important;color:#f4f1ea!important}
.dshp-dock-body .dshp-root[data-theme="white"] .dshp-panel,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-metric,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-group,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-editor,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-active,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-ask,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-create,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-switch,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-rulelist,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-table,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-ruleitem{background:color-mix(in srgb,#fffdf8 76%,transparent)!important;backdrop-filter:blur(16px) saturate(1.2)!important;-webkit-backdrop-filter:blur(16px) saturate(1.2)!important;border-color:#d0caba!important;color:#1a1916!important}
.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-panel,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-metric,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-group,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-editor,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-active,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-ask,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-create,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-switch,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-rulelist,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-table,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-ruleitem{background:color-mix(in srgb,#161513 70%,transparent)!important;backdrop-filter:blur(16px) saturate(1.2)!important;-webkit-backdrop-filter:blur(16px) saturate(1.2)!important;border-color:#4a4740!important;color:#f4f1ea!important}
.dshp-dock-body .dshp-field,.dshp-dock-body .dshp-area{background:color-mix(in srgb,var(--dshp-ink) 8%,transparent);color:var(--dshp-ink);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
.dshp-dock-body .dshp-root[data-theme="white"] .dshp-field,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-area{background:#fff!important;color:#1a1916!important;border-color:#c8c2b6!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}
.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-field,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-area{background:#2a2926!important;color:#f4f1ea!important;border-color:#4a4740!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}
.dshp-dock-body select.dshp-field,.dshp-dock-body .dshp-field.dshp-ver{background:var(--dshp-paper,#2a2926)!important;color:var(--dshp-ink)!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;color-scheme:dark}
.dshp-dock-body .dshp-root[data-theme="white"] .dshp-field,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-area{background:color-mix(in srgb,#fff 84%,transparent)!important;color:#16140f!important;border-color:#b7b0a3!important;backdrop-filter:blur(16px) saturate(1.2)!important;-webkit-backdrop-filter:blur(16px) saturate(1.2)!important}
.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-field,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-area{background:color-mix(in srgb,#0e0d0c 80%,transparent)!important;color:#f7f4ee!important;border-color:color-mix(in srgb,#fff 28%,transparent)!important;backdrop-filter:blur(16px) saturate(1.2)!important;-webkit-backdrop-filter:blur(16px) saturate(1.2)!important}
.dshp-dock-body select.dshp-field,.dshp-dock-body .dshp-field.dshp-ver{background:var(--dshp-paper,#2a2926)!important;color:var(--dshp-ink)!important;backdrop-filter:blur(16px) saturate(1.2)!important;-webkit-backdrop-filter:blur(16px) saturate(1.2)!important;color-scheme:dark}
.dshp-dock-body .dshp-root[data-theme="white"] select.dshp-field,.dshp-dock-body .dshp-root[data-theme="white"] .dshp-field.dshp-ver{background:#fff!important;color:#1a1916!important;color-scheme:light}
.dshp-dock-body .dshp-root[data-theme="dusk"] select.dshp-field,.dshp-dock-body .dshp-root[data-theme="dusk"] .dshp-field.dshp-ver{background:#32312d!important;color:#e6e2db!important;color-scheme:dark}
.dshp-dock-body select.dshp-field option,.dshp-dock-body .dshp-field.dshp-ver option{background:#fff;color:#1a1916}
@@ -787,32 +832,32 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
.dshp-dock-body .rt-eng-select option,.dshp-dock-body .rt-input option{background:#1c1c1c;color:#f2f2f2}
.dshp-dock-body .rt-err{color:#ffb4b4!important;font-weight:600}
.dshp-dock-body .rt-rep-http,.dshp-dock-body pre{background:color-mix(in srgb,#000 55%,transparent)!important;color:var(--rt-ink)!important;border:1px solid var(--rt-line)}
/* 宿主浅色 / 白主题:实底、高对比、少眩光(避免半透明白+浅灰字) */
body:not([data-ds-dark-theme]) .dshp-dock{background:#f3f0e8!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;border:1px solid #c9c3b6!important;box-shadow:0 14px 36px rgba(26,25,22,.18),0 0 0 1px rgba(26,25,22,.06)!important;color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-head,body:not([data-ds-dark-theme]) .dshp-dock-tabs{background:#ebe7df!important;border-bottom-color:#c9c3b6!important;color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-head b,body:not([data-ds-dark-theme]) .dshp-dock-head button{color:#1a1916!important;text-shadow:none!important}
body:not([data-ds-dark-theme]) .dshp-dock-head button{background:#fffcf7!important;border-color:#c9c3b6!important}
body:not([data-ds-dark-theme]) .dshp-dock-tab{color:#5c574e!important;text-shadow:none!important}
body:not([data-ds-dark-theme]) .dshp-dock-tab:hover,body:not([data-ds-dark-theme]) .dshp-dock-tab.on{color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-body{background:#f3f0e8!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-root{background:#f3f0e8!important;--dshp-bg:#f3f0e8;--dshp-paper:#fffcf7;--dshp-fill:#ebe7df;--dshp-ink:#1a1916;--dshp-mute:#534e46;--dshp-line:#c9c3b6;--dshp-accent:#3f6b52;--dshp-accent-soft:#d7e6dc}
body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-panel,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-metric,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-group,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-editor,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-active,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-ask,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-create,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-switch,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-rulelist{background:#fffcf7!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;border-color:#c9c3b6!important;color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-field,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-area,body:not([data-ds-dark-theme]) .dshp-dock-body select.dshp-field,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-field.dshp-ver{background:#fff!important;color:#1a1916!important;border-color:#bdb6a8!important;backdrop-filter:none!important;color-scheme:light}
body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-title,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-sub h4,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-group-h strong,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-metric b,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-btn,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-rule-name{color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-mute,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-kicker,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-metric span,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-group-h em,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-count,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-rule-meta,body:not([data-ds-dark-theme]) .dshp-dock-body .dshp-hint{color:#534e46!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-dock{--rt-ink:#1a1916;--rt-mute:#4f4a42;--rt-surf:#fffcf7;--rt-surf-2:#ebe7df;--rt-line:#c9c3b6;color:#1a1916!important;background:#f3f0e8!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-embedded>.rt-head,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-tabs,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-foot{background:#ebe7df!important;border-color:#c9c3b6!important;color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-body{background:#f3f0e8!important;color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-card,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-pane,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-side,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-main,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-list,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-toolbar,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-evi,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-live-body,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-chain,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-split,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-table{background:#fffcf7!important;color:#1a1916!important;border:1px solid #c9c3b6!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-title,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-card h4,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-item-name,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-tab.on,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-kv b,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-mono,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-row,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-item,body:not([data-ds-dark-theme]) .dshp-dock-body h4,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-link,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-toolbar>span{text-shadow:none!important;color:#1a1916!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-tab,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-foot,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-empty,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-item-desc,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-kb-sub,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-kv span,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-tag,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-sec-sub{color:#4f4a42!important;opacity:1!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-row.head,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-vrow.head,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-score-row.head,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-table thead{background:#ebe7df!important;color:#4f4a42!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-row:hover,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-item:hover,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-item.on,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-seg:hover,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-seg.on{background:#ebe7df!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-btn,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-input,body:not([data-ds-dark-theme]) .dshp-dock-body textarea.rt-input,body:not([data-ds-dark-theme]) .dshp-dock-body select.rt-input,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-eng-select{background:#fff!important;color:#1a1916!important;border:1px solid #bdb6a8!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-eng-select option,body:not([data-ds-dark-theme]) .dshp-dock-body .rt-input option{background:#fff;color:#1a1916}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-err{color:#9a3434!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-btn-primary{background:#3f6b52!important;border-color:#3f6b52!important;color:#fff!important}
body:not([data-ds-dark-theme]) .dshp-dock-body .rt-rep-http,body:not([data-ds-dark-theme]) .dshp-dock-body pre{background:#ebe7df!important;color:#1a1916!important;border:1px solid #c9c3b6!important}
/* 白玻璃:深色字压在偏白的半透明底上,宿主深浅都不能把它刷回实底。 */
body .dshp-dock:has(.dshp-root[data-theme="white"]){background:color-mix(in srgb,#fffdf8 78%,transparent)!important;backdrop-filter:blur(18px) saturate(1.25)!important;-webkit-backdrop-filter:blur(18px) saturate(1.25)!important;border:1px solid color-mix(in srgb,#3c362e 32%,transparent)!important;box-shadow:0 14px 36px rgba(26,25,22,.16)!important;color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-head,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-tabs{background:color-mix(in srgb,#fffdf8 58%,transparent)!important;border-bottom-color:color-mix(in srgb,#3c362e 28%,transparent)!important;color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-head b,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-head button{color:#14120e!important;text-shadow:0 1px 0 rgba(255,255,255,.45)!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-head button{background:color-mix(in srgb,#fff 82%,transparent)!important;border-color:color-mix(in srgb,#3c362e 28%,transparent)!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-tab{color:#3c362e!important;text-shadow:none!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-tab:hover,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-tab.on{color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body{background:transparent!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-root{background:transparent!important;--dshp-bg:transparent;--dshp-paper:color-mix(in srgb,#fffdf8 72%,transparent);--dshp-fill:color-mix(in srgb,#14120e 8%,transparent);--dshp-ink:#14120e;--dshp-mute:#3c362e;--dshp-line:color-mix(in srgb,#3c362e 28%,transparent);--dshp-accent:#2f5a42;--dshp-accent-soft:color-mix(in srgb,#d7e6dc 70%,transparent)}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-panel,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-metric,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-group,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-editor,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-active,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-ask,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-create,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-switch,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-rulelist{background:color-mix(in srgb,#fffdf8 70%,transparent)!important;backdrop-filter:blur(14px) saturate(1.2)!important;-webkit-backdrop-filter:blur(14px) saturate(1.2)!important;border-color:color-mix(in srgb,#3c362e 26%,transparent)!important;color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-field,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-area{background:color-mix(in srgb,#fff 88%,transparent)!important;color:#14120e!important;border-color:color-mix(in srgb,#3c362e 34%,transparent)!important;backdrop-filter:blur(12px)!important;-webkit-backdrop-filter:blur(12px)!important;color-scheme:light}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-title,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-sub h4,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-group-h strong,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-metric b,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-btn,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-rule-name{color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-mute,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-kicker,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-metric span,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-group-h em,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-count,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-rule-meta,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .dshp-hint{color:#3c362e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-dock{--rt-ink:#14120e;--rt-mute:#3c362e;--rt-surf:color-mix(in srgb,#fffdf8 70%,transparent);--rt-surf-2:color-mix(in srgb,#fffdf8 82%,transparent);--rt-line:color-mix(in srgb,#3c362e 28%,transparent);color:#14120e!important;background:transparent!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-embedded>.rt-head,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-tabs,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-foot{background:color-mix(in srgb,#fffdf8 62%,transparent)!important;border-color:color-mix(in srgb,#3c362e 26%,transparent)!important;color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-body{background:transparent!important;color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-card,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-pane,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-side,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-main,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-list,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-toolbar,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-evi,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-live-body,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-chain,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-split,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-table{background:color-mix(in srgb,#fffdf8 68%,transparent)!important;color:#14120e!important;border:1px solid color-mix(in srgb,#3c362e 26%,transparent)!important;backdrop-filter:blur(14px) saturate(1.2)!important;-webkit-backdrop-filter:blur(14px) saturate(1.2)!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-title,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-card h4,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-item-name,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-tab.on,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-kv b,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-mono,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-row,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-item,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body h4,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-link,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-toolbar>span{text-shadow:none!important;color:#14120e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-tab,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-foot,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-empty,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-item-desc,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-kb-sub,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-kv span,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-tag,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-sec-sub{color:#3c362e!important;opacity:1!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-row.head,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-vrow.head,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-score-row.head,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-table thead{background:color-mix(in srgb,#fff 80%,transparent)!important;color:#3c362e!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-row:hover,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-item:hover,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-item.on,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-seg:hover,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-seg.on{background:color-mix(in srgb,#fff 74%,transparent)!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-btn,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-input,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body textarea.rt-input,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-eng-select{background:color-mix(in srgb,#fff 88%,transparent)!important;color:#14120e!important;border:1px solid color-mix(in srgb,#3c362e 34%,transparent)!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-eng-select option,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-input option{background:#fff;color:#14120e}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-err{color:#9a3434!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-btn-primary{background:#3f6b52!important;border-color:#3f6b52!important;color:#fff!important}
body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body .rt-rep-http,body .dshp-dock:has(.dshp-root[data-theme="white"]) .dshp-dock-body pre{background:color-mix(in srgb,#fff 84%,transparent)!important;color:#14120e!important;border:1px solid color-mix(in srgb,#3c362e 28%,transparent)!important}
body:not([data-ds-dark-theme]) .dshp-auth-modal{background:#fffcf7;color:#1a1916;border-color:#c9c3b6}
body:not([data-ds-dark-theme]) .dshp-auth-legal{background:#f3f0e8;color:#1a1916;border-color:#c9c3b6}
body:not([data-ds-dark-theme]) .dshp-auth-warn{background:#f5e6c8;color:#6b4a10}
@@ -820,20 +865,20 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button{border-color:#c9c3b6;color:
body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:#3f6b52;border-color:#3f6b52;color:#fff}
body:not([data-ds-dark-theme]) .dshp-hero-chip-btn,body:not([data-ds-dark-theme]) .dshp-hbtn{color:#1a1916;border-color:#3f6b52;background:#d7e6dc}
body:not([data-ds-dark-theme]) .dshp-hero-chip-btn:hover,body:not([data-ds-dark-theme]) .dshp-hbtn:hover{background:#c5dacd;color:#1a1916}
/* 宿主深色 / 墨主题:清洗实底墨色,与「墨」开关一致 */
body[data-ds-dark-theme] .dshp-dock{background:#2a2926!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;border:1px solid #4a4740!important;box-shadow:0 18px 48px rgba(0,0,0,.45)!important;color:#f4f1ea!important}
body[data-ds-dark-theme] .dshp-dock-head,body[data-ds-dark-theme] .dshp-dock-tabs{background:#32312d!important;border-bottom-color:#4a4740!important;color:#f4f1ea!important}
body[data-ds-dark-theme] .dshp-dock-head b,body[data-ds-dark-theme] .dshp-dock-head button{color:#f4f1ea!important;text-shadow:none!important}
body[data-ds-dark-theme] .dshp-dock-head button{background:#2a2926!important;border-color:#4a4740!important}
body[data-ds-dark-theme] .dshp-dock-tab{color:#c9c3b8!important;text-shadow:none!important}
body[data-ds-dark-theme] .dshp-dock-tab:hover,body[data-ds-dark-theme] .dshp-dock-tab.on{color:#f4f1ea!important}
body[data-ds-dark-theme] .dshp-dock-body{background:#2a2926!important}
body[data-ds-dark-theme] .dshp-dock-body .dshp-root{background:#2a2926!important;--dshp-bg:#2a2926;--dshp-paper:#32312d;--dshp-fill:#353430;--dshp-ink:#f4f1ea;--dshp-mute:#c9c3b8;--dshp-line:#4a4740;--dshp-accent:#9bb5a6;--dshp-accent-soft:#3a433d}
body[data-ds-dark-theme] .dshp-dock-body .dshp-panel,body[data-ds-dark-theme] .dshp-dock-body .dshp-metric,body[data-ds-dark-theme] .dshp-dock-body .dshp-group,body[data-ds-dark-theme] .dshp-dock-body .dshp-editor,body[data-ds-dark-theme] .dshp-dock-body .dshp-active,body[data-ds-dark-theme] .dshp-dock-body .dshp-ask,body[data-ds-dark-theme] .dshp-dock-body .dshp-create,body[data-ds-dark-theme] .dshp-dock-body .dshp-switch,body[data-ds-dark-theme] .dshp-dock-body .dshp-rulelist{background:#32312d!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important;border-color:#4a4740!important;color:#f4f1ea!important}
body[data-ds-dark-theme] .dshp-dock-body .dshp-field,body[data-ds-dark-theme] .dshp-dock-body .dshp-area,body[data-ds-dark-theme] .dshp-dock-body select.dshp-field,body[data-ds-dark-theme] .dshp-dock-body .dshp-field.dshp-ver{background:#2a2926!important;color:#f4f1ea!important;border-color:#4a4740!important;backdrop-filter:none!important;color-scheme:dark}
body[data-ds-dark-theme] .dshp-dock-body .dshp-title,body[data-ds-dark-theme] .dshp-dock-body .dshp-sub h4,body[data-ds-dark-theme] .dshp-dock-body .dshp-group-h strong,body[data-ds-dark-theme] .dshp-dock-body .dshp-metric b,body[data-ds-dark-theme] .dshp-dock-body .dshp-btn,body[data-ds-dark-theme] .dshp-dock-body .dshp-rule-name{color:#f4f1ea!important}
body[data-ds-dark-theme] .dshp-dock-body .dshp-mute,body[data-ds-dark-theme] .dshp-dock-body .dshp-kicker,body[data-ds-dark-theme] .dshp-dock-body .dshp-metric span,body[data-ds-dark-theme] .dshp-dock-body .dshp-group-h em,body[data-ds-dark-theme] .dshp-dock-body .dshp-count,body[data-ds-dark-theme] .dshp-dock-body .dshp-rule-meta,body[data-ds-dark-theme] .dshp-dock-body .dshp-hint{color:#c9c3b8!important}
body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3a433d;color:#f4f1ea}
/* 墨玻璃:浅色字压在偏黑的半透明底上。下拉选项保持实底,系统菜单不参与模糊。 */
body .dshp-dock:has(.dshp-root[data-theme="dusk"]){background:color-mix(in srgb,#100e0c 76%,transparent)!important;backdrop-filter:blur(18px) saturate(1.2)!important;-webkit-backdrop-filter:blur(18px) saturate(1.2)!important;border:1px solid color-mix(in srgb,#fff 22%,transparent)!important;box-shadow:0 18px 48px rgba(0,0,0,.42)!important;color:#f7f4ee!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-head,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-tabs{background:color-mix(in srgb,#161410 52%,transparent)!important;border-bottom-color:color-mix(in srgb,#fff 18%,transparent)!important;color:#f7f4ee!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-head b,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-head button{color:#f7f4ee!important;text-shadow:0 1px 2px rgba(0,0,0,.65)!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-head button{background:color-mix(in srgb,#0c0b09 70%,transparent)!important;border-color:color-mix(in srgb,#fff 22%,transparent)!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-tab{color:#e6dfd2!important;text-shadow:0 1px 2px rgba(0,0,0,.55)!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-tab:hover,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-tab.on{color:#f7f4ee!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body{background:transparent!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-root{background:transparent!important;--dshp-bg:transparent;--dshp-paper:color-mix(in srgb,#161410 68%,transparent);--dshp-fill:color-mix(in srgb,#fff 8%,transparent);--dshp-ink:#f7f4ee;--dshp-mute:#e6dfd2;--dshp-line:color-mix(in srgb,#fff 20%,transparent);--dshp-accent:#b7d0c2;--dshp-accent-soft:color-mix(in srgb,#3a433d 70%,transparent)}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-panel,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-metric,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-group,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-editor,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-active,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-ask,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-create,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-rulelist{background:color-mix(in srgb,#161410 64%,transparent)!important;backdrop-filter:blur(14px) saturate(1.15)!important;-webkit-backdrop-filter:blur(14px) saturate(1.15)!important;border-color:color-mix(in srgb,#fff 18%,transparent)!important;color:#f7f4ee!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-field,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-area{background:color-mix(in srgb,#0a0908 84%,transparent)!important;color:#f7f4ee!important;border-color:color-mix(in srgb,#fff 24%,transparent)!important;backdrop-filter:blur(12px)!important;-webkit-backdrop-filter:blur(12px)!important;color-scheme:dark}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-title,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-sub h4,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-group-h strong,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-metric b,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-btn,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-rule-name{color:#f7f4ee!important;text-shadow:0 1px 2px rgba(0,0,0,.55)}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-mute,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-kicker,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-metric span,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-group-h em,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-count,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-rule-meta,body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-hint{color:#e6dfd2!important}
body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch button.is-on{background:color-mix(in srgb,#3a433d 78%,transparent);color:#f7f4ee}
.dshp-dock-resize,.dshp-dock-resize-l,.dshp-dock-resize-r,.dshp-dock-resize-b{position:absolute;z-index:60;pointer-events:auto;touch-action:none}
.dshp-dock-resize{right:0;bottom:0;width:22px;height:22px;cursor:nwse-resize;background:linear-gradient(135deg,transparent 46%,color-mix(in srgb,var(--dsw-alias-brand-primary,#6dbf8c) 75%,transparent) 46%);border-radius:0 0 12px 0;opacity:.95}
.dshp-dock-resize-l{left:-2px;top:0;bottom:0;width:10px;cursor:ew-resize;background:color-mix(in srgb,var(--dsw-alias-brand-primary,#6dbf8c) 18%,transparent)}
@@ -885,7 +930,7 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
function statusKind(st) {
if (st === "applied" || st === "already") return "ok";
if (st === "pending") return "wait";
if (st === "missing_file" || st === "skipped") return "miss";
if (st === "missing_file" || st === "skipped" || st === "unlocated") return "miss";
return "bad";
}
@@ -894,11 +939,12 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
if (st === "pending") return t("status.pending");
if (st === "skipped") return t("status.skipped");
if (st === "missing_file") return t("skip");
if (st === "unlocated") return t("status.unlocated");
return st || t("unknown");
}
function statusSettled(st) {
return st === "applied" || st === "already" || st === "skipped" || st === "missing_file";
function statusApplied(st) {
return st === "applied" || st === "already";
}
function shimKind(v) {
@@ -928,12 +974,15 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
const t = useT();
const [open, setOpen] = useState({});
if (!state || !state.patch_status) return h("div", { className: "dshp-skel", style: { height: 120 } });
const located = !!state.ai_base;
return PATCH_GROUPS.map((group) => {
const rows = group.ids.map((id) => {
const st = state.patch_status[id] || state.patch_status[String(id)] || "missing_file";
const st = located
? (state.patch_status[id] || state.patch_status[String(id)] || "missing_file")
: "unlocated";
return { id, st, label: t("patch." + id) };
});
const done = rows.filter((r) => statusSettled(r.st)).length;
const done = rows.filter((r) => statusApplied(r.st)).length;
const expanded = !!open[group.key];
return h("div", { key: group.key, className: "dshp-group" },
h("button", {
@@ -1071,6 +1120,8 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
const [override, setOverride] = useState("");
const [defaultOverride, setDefaultOverride] = useState("");
const [overrideLoaded, setOverrideLoaded] = useState(false);
const [ownServers, setOwnServers] = useState("");
const [ownLoaded, setOwnLoaded] = useState(false);
const [patchBusy, setPatchBusy] = useState(false);
const [updateBusy, setUpdateBusy] = useState(false);
const [canApplyUpdate, setCanApplyUpdate] = useState(false);
@@ -1085,6 +1136,8 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
const [channel, setChannel] = useState("stable");
const [pick, setPick] = useState({ stable: "", beta: "" });
const actionTicket = useRef(0);
const overrideRef = useRef("");
overrideRef.current = override;
const syncPicks = (d) => {
const versions = (d && d.versions) || [];
@@ -1260,6 +1313,14 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
else setNotice({ kind: "error", text: tr("err.override", { error: (d && d.error) || "" }) });
})
.catch((e) => setNotice({ kind: "error", text: tr("err.override", { error: e.message }) }));
apiJson("/dsh-purge/own-servers")
.then((d) => {
if (d && d.ok) {
setOwnServers(typeof d.content === "string" ? d.content : "");
setOwnLoaded(true);
}
})
.catch(() => {});
}, []);
useEffect(() => { loadAll(); }, [loadAll]);
@@ -1281,12 +1342,13 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
fetch("/dsh-purge/" + action, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(action === "apply" ? { content: override } : {}),
body: JSON.stringify(action === "apply" ? { content: overrideRef.current } : {}),
})
.then((r) => r.json())
.then((d) => {
if (ticket !== actionTicket.current) return;
const applyEmptyBlocked = action === "apply" && promptBoxEmpty(override) && (!d || d.injectSource !== "rule");
const posted = action === "apply" ? overrideRef.current : override;
const applyEmptyBlocked = action === "apply" && promptBoxEmpty(posted) && (!d || d.injectSource !== "rule");
if (responseNeedsPrompt(d) || applyEmptyBlocked) {
rejectNeedPrompt(tr);
return;
@@ -1361,7 +1423,7 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
run();
return;
}
bothInjectEmpty(override).then((empty) => {
bothInjectEmpty(overrideRef.current).then((empty) => {
if (ticket !== actionTicket.current) return;
if (empty) {
rejectNeedPrompt(tr);
@@ -1369,7 +1431,7 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
}
run();
});
}, [loadAll, override, rejectNeedPrompt]);
}, [loadAll, rejectNeedPrompt]);
const saveOverride = useCallback(() => {
const tr = t;
@@ -1381,12 +1443,12 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
fetch("/dsh-purge/override", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ content: override }),
body: JSON.stringify({ content: overrideRef.current }),
})
.then((r) => r.json())
.then((d) => {
if (ticket !== actionTicket.current) return;
if (!d.ok || responseNeedsPrompt(d) || (promptBoxEmpty(override) && d.injectSource !== "rule")) {
if (!d.ok || responseNeedsPrompt(d) || (promptBoxEmpty(overrideRef.current) && d.injectSource !== "rule")) {
rejectNeedPrompt(tr);
return;
}
@@ -1401,7 +1463,7 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
if (ticket === actionTicket.current) setPatchBusy(false);
});
};
bothInjectEmpty(override).then((empty) => {
bothInjectEmpty(overrideRef.current).then((empty) => {
if (ticket !== actionTicket.current) return;
if (empty) {
rejectNeedPrompt(tr);
@@ -1409,10 +1471,11 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
}
go();
});
}, [override, t, rejectNeedPrompt]);
}, [t, rejectNeedPrompt]);
const restoreOverride = useCallback(() => {
if (!defaultOverride) return;
overrideRef.current = defaultOverride;
setOverride(defaultOverride);
setNotice({ kind: "ok", text: t("saved.restoreInject") });
}, [defaultOverride, t]);
@@ -1472,11 +1535,11 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
}, [state, waitHostAfterUninstall]);
const s = state;
const located = !!(s && s.ai_base);
const total = s && s.patches_total ? s.patches_total : 26;
const applied = s && typeof s.patches_applied === "number" ? s.patches_applied : 0;
const skipped = s && typeof s.patches_skipped === "number" ? s.patches_skipped : 0;
const settled = Math.min(total, applied + skipped);
const pct = total ? Math.round((settled / total) * 100) : 0;
const skipped = located && s && typeof s.patches_skipped === "number" ? s.patches_skipped : 0;
const pct = located && total ? Math.round((applied / total) * 100) : 0;
const hostSurface = hostSurfaceOf(s);
const versions = (updateInfo && updateInfo.versions) || [];
@@ -1560,8 +1623,8 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
),
s ? h("div", { className: "dshp-metrics" },
h("div", { className: "dshp-metric" },
h("b", null, settled + " / " + total),
h("span", null, t("metric.purged")),
h("b", null, located ? (applied + " / " + total) : ("0 / " + total)),
h("span", null, !located ? t("metric.unlocated") : (skipped > 0 ? t("metric.purged.skip", { n: skipped }) : t("metric.purged"))),
),
h("div", { className: "dshp-metric" },
h("b", { style: { fontSize: 13, fontFamily: "var(--dshp-mono)", fontWeight: 500 } },
@@ -1652,7 +1715,10 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
h("textarea", {
className: "dshp-area",
value: override,
onChange: (e) => setOverride(e.target.value),
onChange: (e) => {
overrideRef.current = e.target.value;
setOverride(e.target.value);
},
spellCheck: false,
placeholder: "",
}),
@@ -1660,6 +1726,42 @@ body[data-ds-dark-theme] .dshp-dock-body .dshp-switch button.is-on{background:#3
className: "dshp-hint",
style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 },
}, t("need.prompt")) : null,
h("div", { className: "dshp-sub" },
h("h4", null, t("own.title")),
h("div", { className: "dshp-row", style: { margin: 0 } },
h(Btn, {
kind: "primary",
tiny: true,
disabled: !ownLoaded,
onClick: () => {
fetch("/dsh-purge/own-servers", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ content: ownServers }),
}).then((r) => r.json()).then((d) => {
if (!d || !d.ok) {
setNotice({ kind: "error", text: (d && d.error) || t("err.override", { error: "" }) });
return;
}
if (typeof d.content === "string") setOwnServers(d.content);
setNotice({
kind: "ok",
text: d.dropped > 0 ? t("saved.own.dropped", { n: d.dropped }) : t("saved.own"),
});
}).catch((e) => setNotice({ kind: "error", text: e.message }));
},
}, t("own.save")),
),
),
h("textarea", {
className: "dshp-area",
value: ownServers,
onChange: (e) => setOwnServers(e.target.value),
spellCheck: false,
rows: 4,
style: { minHeight: 96 },
}),
h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("own.hint")),
);
}
@@ -7151,8 +7253,9 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert
const text = String(value || "").trim();
if (!text) return false;
if (text === "redteam") return true;
if (/红队/.test(text)) return true;
if (/^red[\s_-]*team$/i.test(text)) return true;
const label = text.replace(/不是红队/g, "").replace(/非红队/g, "");
if (/红队/.test(label)) return true;
return false;
}
@@ -7203,7 +7306,7 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert
try {
const labels = document.querySelectorAll("[class*='PfFEtG_label'], [title*='红队'], [title*='RedTeam']");
for (const el of labels) {
if (isRedteamPresetId(el.textContent) || /红队/.test(String(el.textContent || ""))) return true;
if (isRedteamPresetId(el.textContent)) return true;
}
} catch { /* ignore */ }
return false;
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+428 -61
View File
@@ -11,7 +11,18 @@ import {
revertHideConsoleFromBin,
} from "./hide-console.js";
import * as desktop from "./desktop.js";
import { asarArchiveIsFile, extractAsar, hostFs, overlayAsarUnpacked, renameAsarAside } from "./extract-asar.js";
import {
asarArchiveIsFile,
asarFileIdentity,
commitExtractedDir,
extractAsarToSide,
shouldExtractAsar,
hostFs,
newestPreservedDir,
overlayAsarUnpacked,
renameAsarAside,
restoreExtractedDir,
} from "./extract-asar.js";
import { adapterFor, detectSurface } from "./surface.js";
import { openSlot } from "./table-read.js";
@@ -97,6 +108,8 @@ const memo = {
function remember(slot, compute) {
if (memo[slot].ready) return memo[slot].value;
const value = compute();
// 启动早期可能还看不到宿主目录。空结果不缓存,否则整次进程都是 0/52、每条跳过。
if (slot === "ai" && !value) return value;
memo[slot] = { ready: true, value };
return value;
}
@@ -1624,22 +1637,95 @@ export function sealedAsarHandoff(input = {}) {
return { exe, asar, swapAsar: true };
}
/** 官方 app.asar 解开到 resources/app。点「应用」时调用,不要求用户先跑脚本。 */
function unpackedAsarStampPath() {
return path.join(findDshHome(), "dsh-purge", "unpacked-asar.json");
}
export function readUnpackedAsarStamp() {
try {
const raw = JSON.parse(hostFs.readFileSync(unpackedAsarStampPath(), "utf8"));
const size = Number(raw.size);
const mtimeMs = Number(raw.mtimeMs);
if (!Number.isFinite(size) || !Number.isFinite(mtimeMs)) return null;
return { size, mtimeMs };
} catch {
return null;
}
}
export function writeUnpackedAsarStamp(identity) {
if (!identity || !Number.isFinite(identity.size) || !Number.isFinite(identity.mtimeMs)) return;
const fp = unpackedAsarStampPath();
hostFs.mkdirSync(path.dirname(fp), { recursive: true });
hostFs.writeFileSync(fp, `${JSON.stringify({ size: identity.size, mtimeMs: identity.mtimeMs })}\n`, "utf8");
}
/** 目录已经在用、归档不在时,记住旁边 .bak 的大小和时间。同一份再出现就不重新解。 */
export function rememberUnpackedArchive() {
if (readUnpackedAsarStamp()) return;
const exe = desktop.findDesktopAppExecutable();
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return;
const asar = desktop.appAsarPath(exe);
if (!asar || asarArchiveIsFile(asar)) return;
const ident = asarFileIdentity(`${asar}.bak`);
if (ident) writeUnpackedAsarStamp(ident);
}
/** 当前目录还不能当宿主时,把升级脚本或上一次换目录挪走的那一份放回去。能用的目录不动。 */
function restoreUnusableExtract(appDir, prev) {
if (aiBaseUnderAppDir(appDir)) return false;
const saved = prev || newestPreservedDir(appDir);
if (!saved) return false;
return restoreExtractedDir(appDir, saved);
}
/** 官方 app.asar 解开到 resources/app。目录已能用且归档没变时直接改文件,不重新解包。 */
export async function openSealedDesktopHost(options = {}) {
const handoff = sealedAsarHandoff();
if (!handoff) return { aiBase: null, swapAsar: false };
if (!handoff) return { aiBase: null, swapAsar: false, extracted: false, prev: "", appDir: "", archive: null };
const appDir = desktop.appDirForExecutable(handoff.exe);
let aiBase = options.forceExtract ? null : aiBaseUnderAppDir(appDir);
if (!aiBase) {
await extractAsar(handoff.asar, appDir);
aiBase = aiBaseUnderAppDir(appDir);
const archive = asarFileIdentity(handoff.asar);
const recorded = readUnpackedAsarStamp();
let aiBase = aiBaseUnderAppDir(appDir);
const extract = shouldExtractAsar({
usable: Boolean(aiBase),
identity: archive,
recorded,
upgrade: options.upgrade === true,
});
let extracted = false;
let prev = "";
if (extract) {
try {
const side = extractAsarToSide(handoff.asar, appDir);
overlayAsarUnpacked(handoff.asar, side.next);
if (!aiBaseUnderAppDir(side.next)) {
try { hostFs.rmSync(side.next, { recursive: true, force: true }); } catch { /* 半成品留在旁边,不覆盖正在用的目录 */ }
throw new Error(`已解开 ${handoff.asar},但里面没有 @deepseek-ai`);
}
const committed = commitExtractedDir(appDir, side.next);
prev = committed.prev || "";
extracted = true;
aiBase = aiBaseUnderAppDir(appDir);
} catch (error) {
try { restoreUnusableExtract(appDir, prev); } catch { /* 放回失败时旧目录仍留在旁边 */ }
throw error;
}
} else if (aiBase) {
overlayAsarUnpacked(handoff.asar, appDir);
if (archive && !recorded) writeUnpackedAsarStamp(archive);
}
overlayAsarUnpacked(handoff.asar, appDir);
if (!aiBase) {
restoreUnusableExtract(appDir, prev);
throw new Error(`已解开 ${handoff.asar},但 ${appDir} 下没有 @deepseek-ai`);
}
resetPathMemo();
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar };
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar, extracted, prev, appDir, archive: extracted ? archive : null };
}
export function restoreSealedExtract(appDir, prev) {
const saved = prev || newestPreservedDir(appDir);
return restoreExtractedDir(appDir, saved);
}
export function scheduleSealedDesktopRestart(handoff) {
@@ -2054,22 +2140,6 @@ const PATCHES = [
],
markers: [' prefix: ""'],
},
{
id: 44, name: "COMPACTION_INSTANT_SETTINGS_SCOPE", layer: "代码", layer_en: "Code",
desc: "即时压缩网页端改用 configForms / compaction client uses configForms",
file: "compaction-instant-client",
replacements: [
{
pattern: 'var inject = ["slots", "locale", "connection", "remote", "settingsScope"];',
replace: 'var inject = ["slots", "locale", "connection", "remote", "configForms"];',
},
{
pattern: "var controller = new CardController(ctx.settingsScope.bind({ namespace: SETTINGS_NAMESPACE }), [",
replace: "var controller = new CardController(ctx.configForms.get(SETTINGS_NAMESPACE), [",
},
],
markers: ["ctx.configForms.get(SETTINGS_NAMESPACE)"],
},
{
id: 5, name: "APPROVAL_NEVER_SENTENCE", layer: "提示词", layer_en: "Prompt",
desc: "审批提示句限制 / approval sentence",
@@ -2281,6 +2351,32 @@ const ENGINE_PATCHES = [
file: "sandbox-local",
rel: ["lib", "index.js"],
patterns: [
// 新版 dsh-sandbox-local:confine(argv, policy) 去掉了 async/signal 与 policy 规范化。
'confine(argv, policy) {\n' +
'\t\tif (this.runnerCommand !== void 0) return {\n' +
'\t\t\targv: [\n' +
'\t\t\t\t...this.runnerCommand,\n' +
'\t\t\t\t...bwrapProfileArgs(policy),\n' +
'\t\t\t\t"--",\n' +
'\t\t\t\t...argv\n' +
'\t\t\t],\n' +
'\t\t\tenforcement: "full",\n' +
'\t\t\tdenialSignatures: DENIAL_SIGNATURES.runnerCommand,\n' +
'\t\t\trunnerFailureRules: [{ fatalSignatures: this.configuredRunnerFailureSignatures }]\n' +
'\t\t};\n' +
'\t\tconst selected = this.selectRunner(policy.mode);\n' +
'\t\treturn {\n' +
'\t\t\targv: [\n' +
'\t\t\t\t...this.runnerArgv(selected.runner, policy),\n' +
'\t\t\t\t"--",\n' +
'\t\t\t\t...argv\n' +
'\t\t\t],\n' +
'\t\t\tenforcement: selected.enforcement,\n' +
'\t\t\tdenialSignatures: DENIAL_SIGNATURES[selected.runner],\n' +
'\t\t\trunnerFailureRules: RUNNER_FAILURE_RULES[selected.runner]\n' +
'\t\t};\n' +
'\t}',
// 旧签名(带 signal 与 policy 规范化),保留以兼容旧版回放。
'async confine(argv, policy, signal) {\n' +
'\t\tsignal?.throwIfAborted();\n' +
'\t\tpolicy = {\n' +
@@ -2499,19 +2595,32 @@ const NEW_TOOL_PATCHES = [
},
{
id: 23, name: "SUBAGENT_MAXDEPTH_RAISED", layer: "代码", layer_en: "Code",
desc: "子代理深度默认 1 → 10 / subagent maxDepth raised",
file: "subagent",
desc: "子代理深度默认 3 → 10 / subagent maxDepth raised",
// 0.1.7 起深度默认在工具参数上(dsh-tool-subagent);旧版在 dsh-subagent 服务配置上。
// 两个 key 都列,命中哪个都能抬高递归预算。
file: ["subagent", "tool-subagent"],
rel: ["lib", "index.js"],
replacements: [
{
// 0.1.7 起深度默认在 dsh-subagent 的服务配置上,工具参数不再带 .default(3)。
// 新版工具参数:union + provider-managed,默认 3。
pattern:
'maxDepth: z.union([z.natural().max(Number.MAX_SAFE_INTEGER), z.const("provider-managed")]).default(3)',
replace:
'maxDepth: z.union([z.natural().max(Number.MAX_SAFE_INTEGER), z.const("provider-managed")]).default(10) // [dsh-purge] subagent depth raised',
},
{
// 0.1.5/0.1.6 时代:数值 schema,默认 1。
pattern:
"maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(1).volatile()",
replace:
"maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(10).volatile()",
},
],
markers: ["maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(10).volatile()"],
markersAny: true,
markers: [
"[dsh-purge] subagent depth raised",
"maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(10).volatile()",
],
},
{
id: 24, name: "PRESET_FETCH_ENABLED", layer: "代码", layer_en: "Code",
@@ -2575,29 +2684,6 @@ const NEW_TOOL_PATCHES = [
"personaPrefix: !!js process.env.DSH_SYSTEM_PROMPT ?? ''",
],
},
{
// 梁神 phase-1 只留 persona,滤掉 inject。
id: 27, name: "LIANGSHEN_PERSONA_PURGE", layer: "提示词", layer_en: "Prompt",
desc: "插件 dsh-liangshen(梁神):拒绝锁→可执行(可选) / @linxin666/dsh-liangshen",
file: ["preset-liangshen", "preset-liangshen-pkg"],
optional: true, // only when liangshen is installed; text drifts by version
replacements: [
{
// 0.1.5 persona 不认 text,改写到 prefix。
pattern: "name: '@deepseek-ai/dsh-persona'\n config:\n text:",
replace: "name: '@deepseek-ai/dsh-persona'\n config:\n prefix:",
},
{
pattern: "text: You are a helpful software engineer assistant.",
replace: 'prefix: ""',
},
],
markersAny: true,
markers: [
'prefix: ""',
"[dsh-purge] identity stripped",
],
},
{
// phase-1 白名单放行 dsh-purge section。
id: 28, name: "LIANGSHEN_PHASE1_KEEP_INJECT", layer: "提示词", layer_en: "Prompt",
@@ -2642,9 +2728,11 @@ const NEW_TOOL_PATCHES = [
'description: "Canonical local URL of the web GUI serving this session." /* [dsh-purge] web surface identity neutralized */',
},
],
// #53 会把前一句再收成 Local web GUI,不能再要求两句标记同时在。
markersAny: true,
markers: [
"through the local web GUI at ${webUrl}.",
"[dsh-purge] web surface identity neutralized",
"through the local web GUI at ${webUrl}.",
],
},
{
@@ -3313,6 +3401,48 @@ const NEW_TOOL_PATCHES = [
optional: true,
skipIfMarked: true,
replacements: [
{
// pi-ai 新版:变量名从 initialSystemText 改成 context.systemPrompt。
pattern:
" // For OAuth tokens, we MUST include Claude Code identity\n" +
" if (isOAuthToken) {\n" +
" params.system = [\n" +
" {\n" +
' type: "text",\n' +
' text: "You are Claude Code, Anthropic\'s official CLI for Claude.",\n' +
" ...(cacheControl ? { cache_control: cacheControl } : {}),\n" +
" },\n" +
" ];\n" +
" if (context.systemPrompt) {\n" +
" params.system.push({\n" +
' type: "text",\n' +
" text: sanitizeSurrogates(context.systemPrompt),\n" +
" ...(cacheControl ? { cache_control: cacheControl } : {}),\n" +
" });\n" +
" }\n" +
" }\n" +
" else if (context.systemPrompt) {\n" +
" // Add cache control to system prompt for non-OAuth tokens\n" +
" params.system = [\n" +
" {\n" +
' type: "text",\n' +
" text: sanitizeSurrogates(context.systemPrompt),\n" +
" ...(cacheControl ? { cache_control: cacheControl } : {}),\n" +
" },\n" +
" ];\n" +
" }",
replace:
" // [dsh-purge] OAuth no longer prepends Claude Code identity\n" +
" if (context.systemPrompt) {\n" +
" params.system = [\n" +
" {\n" +
' type: "text",\n' +
" text: sanitizeSurrogates(context.systemPrompt),\n" +
" ...(cacheControl ? { cache_control: cacheControl } : {}),\n" +
" },\n" +
" ];\n" +
" }",
},
{
pattern:
" // For OAuth tokens, we MUST include Claude Code identity\n" +
@@ -3507,6 +3637,212 @@ const NEW_TOOL_PATCHES = [
],
markers: ["[dsh-purge] deliverable prohibition removed"],
},
{
id: 55,
name: "SYSTEM_PROMPT_REPLACE_HEAD",
layer: "代码",
layer_en: "Code",
desc: "每一步用当前整段系统提示替换第一条,避免旧提示被钉住 / replace the first system prompt every step",
file: ["agent-loop"],
replacements: [
{
pattern: 'inHistory: preparedCall?.systemPromptUpdate === "in-history",',
replace: "inHistory: false, // [dsh-purge] system prompt replaces the first node",
},
],
markers: ["[dsh-purge] system prompt replaces the first node"],
},
{
id: 56,
name: "REWIND_HIDE_CUT_ONLY",
layer: "代码",
layer_en: "Code",
desc: "回退只藏被撤掉的那一轮 / rewind hides only the cut range",
file: ["conversation-client"],
optional: true,
replacements: [
{
pattern:
"\t\tfunction rewindVisibleEntries(entries) {\n" +
"\t\t\tconst list = Array.isArray(entries) ? entries : [...entries];\n" +
"\t\t\tlet latest = null;\n" +
"\t\t\tfor (const entry of list) {\n" +
"\t\t\t\tconst event = entry && entry.event;\n" +
"\t\t\t\tif (!isRewindMarker(event)) continue;\n" +
"\t\t\t\tif (latest === null || event.seq > latest.seq) latest = event;\n" +
"\t\t\t}\n" +
"\t\t\tif (latest === null) return list;\n" +
"\t\t\tconst hidden = /* @__PURE__ */ new Set();\n" +
"\t\t\tif (Array.isArray(latest.sourceEventSeqs)) {\n" +
"\t\t\t\tfor (const seq of latest.sourceEventSeqs) hidden.add(seq);\n" +
"\t\t\t}\n" +
"\t\t\thidden.add(latest.seq);\n" +
"\t\t\treturn list.filter((entry) => {\n" +
"\t\t\t\tconst event = entry && entry.event;\n" +
"\t\t\t\tif (!event || hidden.has(event.seq)) return false;\n" +
"\t\t\t\tif (event.seq > latest.seq) return true;\n" +
"\t\t\t\treturn event.type === \"system/message\";\n" +
"\t\t\t});\n" +
"\t\t}",
replace:
"\t\tfunction rewindVisibleEntries(entries) {\n" +
"\t\t\tconst list = Array.isArray(entries) ? entries : [...entries];\n" +
"\t\t\tconst hidden = /* @__PURE__ */ new Set();\n" +
"\t\t\tfor (const entry of list) {\n" +
"\t\t\t\tconst event = entry && entry.event;\n" +
"\t\t\t\tif (!isRewindMarker(event)) continue;\n" +
"\t\t\t\thidden.add(event.seq);\n" +
"\t\t\t\tconst op = event.surfaceOp;\n" +
"\t\t\t\tif (op && typeof op.startSeq === \"number\" && typeof op.endSeq === \"number\" && op.endSeq >= op.startSeq && op.endSeq - op.startSeq < 100000) {\n" +
"\t\t\t\t\tfor (let seq = op.startSeq; seq <= op.endSeq; seq += 1) hidden.add(seq);\n" +
"\t\t\t\t}\n" +
"\t\t\t\tconst raw = event.sourceEventSeqs;\n" +
"\t\t\t\tif (Array.isArray(raw)) {\n" +
"\t\t\t\t\tfor (const row of raw) {\n" +
"\t\t\t\t\t\tif (typeof row === \"number\") hidden.add(row);\n" +
"\t\t\t\t\t\telse if (Array.isArray(row) && row.length === 2 && typeof row[0] === \"number\" && typeof row[1] === \"number\" && row[1] >= row[0] && row[1] - row[0] < 100000) {\n" +
"\t\t\t\t\t\t\tfor (let seq = row[0]; seq <= row[1]; seq += 1) hidden.add(seq);\n" +
"\t\t\t\t\t\t}\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t}\n" +
"\t\t\t\tconst cutEnd = op && typeof op.endSeq === \"number\" ? op.endSeq : event.seq;\n" +
"\t\t\t\tlet turnStart = null;\n" +
"\t\t\t\tlet turnEnd = null;\n" +
"\t\t\t\tfor (const row of list) {\n" +
"\t\t\t\t\tconst ev = row && row.event;\n" +
"\t\t\t\t\tif (!ev || ev.seq >= event.seq) continue;\n" +
"\t\t\t\t\tif (ev.type === \"turn/start\") turnStart = ev.seq;\n" +
"\t\t\t\t\tif (ev.type === \"turn/end\" && ev.seq >= cutEnd && turnEnd === null) turnEnd = ev.seq;\n" +
"\t\t\t\t}\n" +
"\t\t\t\tif (turnStart !== null) {\n" +
"\t\t\t\t\tconst last = turnEnd === null ? event.seq : turnEnd;\n" +
"\t\t\t\t\tfor (const row of list) {\n" +
"\t\t\t\t\t\tconst ev = row && row.event;\n" +
"\t\t\t\t\t\tif (!ev || ev.seq < turnStart || ev.seq > last) continue;\n" +
"\t\t\t\t\t\tif (ev.type === \"system/message\") continue;\n" +
"\t\t\t\t\t\thidden.add(ev.seq);\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t}\n" +
"\t\t\t}\n" +
"\t\t\tif (hidden.size === 0) return list;\n" +
"\t\t\treturn list.filter((entry) => {\n" +
"\t\t\t\tconst event = entry && entry.event;\n" +
"\t\t\t\treturn !!event && !hidden.has(event.seq);\n" +
"\t\t\t});\n" +
"\t\t} // [dsh-purge] rewind hides only the cut range",
},
{
pattern:
"\t\t/**\n" +
"\t\t* Session-owned incremental engine that assembles business Contexts from a\n" +
"\t\t* contiguous Event window and materializes registered view snapshots.\n" +
"\t\t*/\n" +
"\t\tvar ConversationNodeAssembler = class {",
replace:
"\t\t/**\n" +
"\t\t* Session-owned incremental engine that assembles business Contexts from a\n" +
"\t\t* contiguous Event window and materializes registered view snapshots.\n" +
"\t\t*/\n" +
"\t\tfunction isRewindMarker(event) {\n" +
"\t\t\tif (!event || event.type !== \"user/message\") return false;\n" +
"\t\t\tconst id = event.data && event.data.id;\n" +
"\t\t\tif (typeof id !== \"string\" || id.indexOf(\"rewind-\") !== 0) return false;\n" +
"\t\t\tconst op = event.surfaceOp;\n" +
"\t\t\treturn !!op && op !== \"append\" && op.op === \"replace\";\n" +
"\t\t}\n" +
"\t\tfunction rewindVisibleEntries(entries) {\n" +
"\t\t\tconst list = Array.isArray(entries) ? entries : [...entries];\n" +
"\t\t\tconst hidden = /* @__PURE__ */ new Set();\n" +
"\t\t\tfor (const entry of list) {\n" +
"\t\t\t\tconst event = entry && entry.event;\n" +
"\t\t\t\tif (!isRewindMarker(event)) continue;\n" +
"\t\t\t\thidden.add(event.seq);\n" +
"\t\t\t\tconst op = event.surfaceOp;\n" +
"\t\t\t\tif (op && typeof op.startSeq === \"number\" && typeof op.endSeq === \"number\" && op.endSeq >= op.startSeq && op.endSeq - op.startSeq < 100000) {\n" +
"\t\t\t\t\tfor (let seq = op.startSeq; seq <= op.endSeq; seq += 1) hidden.add(seq);\n" +
"\t\t\t\t}\n" +
"\t\t\t\tconst raw = event.sourceEventSeqs;\n" +
"\t\t\t\tif (Array.isArray(raw)) {\n" +
"\t\t\t\t\tfor (const row of raw) {\n" +
"\t\t\t\t\t\tif (typeof row === \"number\") hidden.add(row);\n" +
"\t\t\t\t\t\telse if (Array.isArray(row) && row.length === 2 && typeof row[0] === \"number\" && typeof row[1] === \"number\" && row[1] >= row[0] && row[1] - row[0] < 100000) {\n" +
"\t\t\t\t\t\t\tfor (let seq = row[0]; seq <= row[1]; seq += 1) hidden.add(seq);\n" +
"\t\t\t\t\t\t}\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t}\n" +
"\t\t\t\tconst cutEnd = op && typeof op.endSeq === \"number\" ? op.endSeq : event.seq;\n" +
"\t\t\t\tlet turnStart = null;\n" +
"\t\t\t\tlet turnEnd = null;\n" +
"\t\t\t\tfor (const row of list) {\n" +
"\t\t\t\t\tconst ev = row && row.event;\n" +
"\t\t\t\t\tif (!ev || ev.seq >= event.seq) continue;\n" +
"\t\t\t\t\tif (ev.type === \"turn/start\") turnStart = ev.seq;\n" +
"\t\t\t\t\tif (ev.type === \"turn/end\" && ev.seq >= cutEnd && turnEnd === null) turnEnd = ev.seq;\n" +
"\t\t\t\t}\n" +
"\t\t\t\tif (turnStart !== null) {\n" +
"\t\t\t\t\tconst last = turnEnd === null ? event.seq : turnEnd;\n" +
"\t\t\t\t\tfor (const row of list) {\n" +
"\t\t\t\t\t\tconst ev = row && row.event;\n" +
"\t\t\t\t\t\tif (!ev || ev.seq < turnStart || ev.seq > last) continue;\n" +
"\t\t\t\t\t\tif (ev.type === \"system/message\") continue;\n" +
"\t\t\t\t\t\thidden.add(ev.seq);\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t}\n" +
"\t\t\t}\n" +
"\t\t\tif (hidden.size === 0) return list;\n" +
"\t\t\treturn list.filter((entry) => {\n" +
"\t\t\t\tconst event = entry && entry.event;\n" +
"\t\t\t\treturn !!event && !hidden.has(event.seq);\n" +
"\t\t\t});\n" +
"\t\t} // [dsh-purge] rewind hides only the cut range\n" +
"\t\tvar ConversationNodeAssembler = class {",
},
{
pattern:
"\t\t\treplaceWindow(entries, hasMore) {\n" +
"\t\t\t\tthis.contexts.clear();",
replace:
"\t\t\treplaceWindow(entries, hasMore) {\n" +
"\t\t\t\tentries = rewindVisibleEntries(entries);\n" +
"\t\t\t\tthis.contexts.clear();",
},
],
markers: ["[dsh-purge] rewind hides only the cut range"],
},
{
id: 57,
name: "DEEPSEEK_SYSTEM_ROLE",
layer: "代码",
layer_en: "Code",
desc: "deepseek.com 的系统提示词固定走 system,思维链不动 / keep deepseek.com instructions on system",
file: ["pi-ai-completions"],
optional: true,
skipIfMarked: true,
replacements: [
{
pattern: 'const instructionRole = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";',
replace: 'const instructionRole = model.reasoning && compat.supportsDeveloperRole && !String(model.baseUrl || "").toLowerCase().includes("deepseek.com") ? "developer" : "system"; // [dsh-purge] deepseek.com keeps system role',
},
],
markers: ["[dsh-purge] deepseek.com keeps system role"],
},
{
id: 58,
name: "REWIND_SKIP_DERIVE",
layer: "代码",
layer_en: "Code",
desc: "回退空标记不进模型请求 / rewind markers stay off the model transcript",
file: ["session"],
optional: true,
skipIfMarked: true,
replacements: [
{
pattern: '\t\tcase "user/message": return event.data;',
replace: '\t\tcase "user/message":\n\t\t\tif (typeof event.data?.id === "string" && event.data.id.indexOf("rewind-") === 0) return null;\n\t\t\treturn event.data; // [dsh-purge] rewind markers stay off the model transcript',
},
],
markers: ["[dsh-purge] rewind markers stay off the model transcript"],
},
];
export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES];
@@ -3549,8 +3885,14 @@ function officialShellMain() {
try {
const exe = desktop.findDesktopAppExecutable();
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return "";
const main = path.join(desktop.appDirForExecutable(exe), "lib", "main.js");
return fs.existsSync(main) ? main : "";
const appDir = desktop.appDirForExecutable(exe);
// 官方桌面壳入口布局换过:早期是 lib/main.js,0.1.3 起直接是 main.js。
// 只认 lib/ 会让 desktop-shell 永远未定位,#45/#46 被误报成"文件缺失"。
for (const rel of [["lib", "main.js"], ["main.js"]]) {
const main = path.join(appDir, ...rel);
if (fs.existsSync(main)) return main;
}
return "";
} catch {
return "";
}
@@ -3755,10 +4097,14 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
...nestedPkg(aiBase, "dsh-user-approval", "lib", "invariant.js"),
...(root ? [path.join(root, "packages", "interaction", "user-approval", "lib", "invariant.js")] : []),
]),
"escalation": firstExisting([
...nestedPkg(aiBase, "dsh-sandbox", "lib", "types", "escalation.js"),
...(root ? [path.join(root, "packages", "sandbox", "sandbox", "lib", "types", "escalation.js")] : []),
// 运行时加载的是包入口 lib/index.js(escalation 实现已被 bundle 内联进它);
// lib/types/escalation.js 只是编译残留,补丁打在那里对运行行为零影响。
// 两者都覆盖,且入口排前,保证 markers 命中真正被执行的文件。
"escalation": allExisting([
...nestedPkg(aiBase, "dsh-sandbox", "lib", "index.js"),
...nestedPkg(aiBase, "dsh-sandbox", "lib", "types", "escalation.js"),
...(root ? [path.join(root, "packages", "sandbox", "sandbox", "lib", "index.js")] : []),
...(root ? [path.join(root, "packages", "sandbox", "sandbox", "lib", "types", "escalation.js")] : []),
]),
"fs-sandbox": firstExisting([
path.join(aiBase, "dsh-fs-sandbox", "lib", "index.js"),
@@ -3905,6 +4251,15 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
"deliverables-prompt": allExisting([
...nestedPkg(aiBase, "dsh-client-ui-deliverables", "lib", "index.js"),
]),
"session": allExisting([
...nestedPkg(aiBase, "dsh-session", "lib", "index.js"),
]),
"agent-loop": allExisting([
...nestedPkg(aiBase, "dsh-agent-loop", "lib", "index.js"),
]),
"conversation-client": allExisting([
...nestedPkg(aiBase, "dsh-client-ui-conversation", "lib", "client.js"),
]),
};
return filterTargetFiles(files);
}
@@ -4913,7 +5268,7 @@ export async function readOverrideForUi(dshHome) {
}
}
const customized = await isUserCustomizedOverride(dshHome);
const show = customized ? disk : defaultContent;
const show = normalizeOverride(disk) ? disk : defaultContent;
return {
path: fp,
exists,
@@ -4925,11 +5280,10 @@ export async function readOverrideForUi(dshHome) {
};
}
/** 插件加载时同步落下默认提示词,避免第一轮 assemble 读到空文件。 */
/** 插件加载时同步落下默认提示词,避免第一轮 assemble 读到空文件。磁盘是空的就写入,不管有没有点过保存。 */
export function seedOverrideSync(dshHome) {
const fp = findOverrideFile(dshHome);
fs.mkdirSync(dshHome, { recursive: true });
if (readOverrideStateSync(dshHome).customized === true) return "exists";
let disk = "";
try {
if (fs.existsSync(fp)) disk = fs.readFileSync(fp, "utf8");
@@ -4947,6 +5301,19 @@ export async function installOverride(dshHome, force = false) {
const fp = findOverrideFile(dshHome);
await fsp.mkdir(dshHome, { recursive: true });
if (!force && await isUserCustomizedOverride(dshHome)) return "exists";
if (!force && fs.existsSync(fp)) {
let disk = "";
try {
disk = await loadText(fp);
} catch {
disk = "";
}
const bundled = defaultOverrideText();
if (normalizeOverride(disk) && normalizeOverride(disk) !== normalizeOverride(bundled)) {
await markOverrideCustomized(dshHome, true, disk);
return "exists";
}
}
const bundled = defaultOverrideText();
if (!normalizeOverride(bundled)) return fs.existsSync(fp) ? "empty" : "missing";
await fsp.writeFile(fp, bundled, "utf8");
+118
View File
@@ -120,6 +120,39 @@ export function asarArchiveIsFile(p) {
}
}
/** 用大小和修改时间认出是不是同一份归档。 */
export function asarFileIdentity(asarPath) {
try {
const st = archiveFs().statSync(asarPath);
if (!st.isFile()) return null;
return { size: st.size, mtimeMs: Math.round(st.mtimeMs) };
} catch {
return null;
}
}
export function sameAsarIdentity(left, right) {
return Boolean(
left && right
&& left.size === right.size
&& left.mtimeMs === right.mtimeMs,
);
}
/**
* 可用目录配同一份归档:不解包。
* 目录不在,或记录过的归档大小/时间变了:解一次。
* 升级标记碰上另一份归档,同样解一次。目录还在、又没记录过、也不是升级:先认这份归档,不解。
*/
export function shouldExtractAsar({ usable, identity, recorded, upgrade }) {
if (!identity) return false;
if (!usable) return true;
const same = sameAsarIdentity(identity, recorded);
if (upgrade && !same) return true;
if (recorded && !same) return true;
return false;
}
function readHeader(fd, afs) {
const pre = Buffer.alloc(16);
if (afs.readSync(fd, pre, 0, 16, 0) !== 16) throw new Error("asar header truncated");
@@ -224,6 +257,91 @@ export function overlayAsarUnpacked(asarPath, destDir) {
return { copied };
}
function discardDir(dir) {
if (!dir) return;
try { diskFs().rmSync(dir, { recursive: true, force: true }); } catch { /* 残留目录下次再清 */ }
}
/** 解到目标旁边的目录。失败时删掉半成品,不碰已经在用的那一份。 */
export function extractAsarToSide(asarPath, destDir) {
const next = `${destDir}.dshpurge-next`;
discardDir(next);
try {
const count = extractAsar(asarPath, next);
return { next, count };
} catch (error) {
discardDir(next);
throw error;
}
}
/** 解开完成之后才把旧目录挪走、新目录换上。换不上就把旧目录放回去。 */
export function commitExtractedDir(destDir, nextDir) {
const fs = diskFs();
if (!nextDir || !fs.existsSync(nextDir)) throw new Error("解包目录不存在");
let prev = "";
if (fs.existsSync(destDir)) {
prev = `${destDir}.dshpurge-prev`;
if (fs.existsSync(prev)) prev = `${destDir}.dshpurge-prev-${Date.now()}`;
fs.renameSync(destDir, prev);
}
try {
fs.renameSync(nextDir, destDir);
} catch (error) {
if (prev && !fs.existsSync(destDir)) {
try { fs.renameSync(prev, destDir); } catch { /* 调用方再试一次放回 */ }
}
discardDir(nextDir);
throw error;
}
return { prev };
}
/** 升级脚本事先挪走的旧目录。补丁没写完时用它放回去。 */
export function newestPreservedDir(destDir) {
const fs = diskFs();
const parent = path.dirname(destDir);
const prefix = `${path.basename(destDir)}.dshpurge-prev`;
let names = [];
try { names = fs.readdirSync(parent); } catch { return ""; }
let best = "";
let bestTime = -1;
for (const name of names) {
if (name !== prefix && !name.startsWith(`${prefix}-`)) continue;
const full = path.join(parent, name);
let time = 0;
try { time = fs.statSync(full).mtimeMs; } catch { continue; }
if (time >= bestTime) {
best = full;
bestTime = time;
}
}
return best;
}
/** 补丁没写完时,把刚才挪走的旧目录放回原处。 */
export function restoreExtractedDir(destDir, prev) {
const fs = diskFs();
if (!prev || !fs.existsSync(prev)) return false;
let failed = "";
if (fs.existsSync(destDir)) {
failed = `${destDir}.dshpurge-failed-${Date.now()}`;
fs.renameSync(destDir, failed);
}
try {
fs.renameSync(prev, destDir);
} catch (error) {
if (failed && !fs.existsSync(destDir)) {
try { fs.renameSync(failed, destDir); } catch { /* 旧目录仍在 prev */ }
}
throw error;
}
if (failed) {
try { fs.rmSync(failed, { recursive: true, force: true }); } catch { /* 坏目录留着不影响已放回的那一份 */ }
}
return true;
}
export function extractAsar(asarPath, destDir) {
const afs = archiveFs();
const fd = afs.openSync(asarPath, "r");
+173 -28
View File
@@ -1,4 +1,6 @@
export const GLOBAL_PROMPT_ORDER = 5000;
import { ownServerNote } from "./net-scope.js";
export const GLOBAL_PROMPT_ORDER = -100000;
export const IDENTITY_CARD_PREFIX = "WHO YOU ARE (highest priority";
const PERSONA_PREFIX_NAMES = new Set([
@@ -96,6 +98,10 @@ function stripHarnessPersona(text) {
/You are a coding agent powered by the \{\{model\}\} model\. Your working directory is \{\{cwd\}\}\.?\s*/g,
"Working directory: {{cwd}}. ",
)
.replace(
/The DeepSeek Harness implementation checkout is at [\s\S]*?Use this checkout only to inspect or extend DSH itself\.?\s*/g,
"",
)
.replace(
/You are a coding agent powered by the [^\n.]+ model, running on the DeepSeek Harness\.?\s*/g,
"",
@@ -138,18 +144,44 @@ function withoutRedteamPreset(sections) {
});
}
function assemblyHasExactInject(sections, inject) {
if (!inject) return true;
return sections.some((section) => String(section?.text || "").includes(inject));
const OWN_SERVER_MARK = "OWN SERVERS — EXACT LIST ONLY";
function injectNeedles(inject) {
const text = String(inject || "").trim();
if (!text) return [];
const at = text.indexOf(OWN_SERVER_MARK);
const base = at >= 0 ? text.slice(0, at).trim() : "";
const needles = [text];
if (base && base !== text) needles.push(base);
return needles;
}
function ensureFullInject(sections, inject) {
if (!inject || assemblyHasExactInject(sections, inject)) return sections;
return [{ name: "dsh-purge", text: inject, order: -10000 }, ...sections];
/** 每次组装都把提示词放到最前。后面段落里的同一份正文拆掉,避免再拼一份。 */
function leadWithInject(sections, inject) {
const text = String(inject || "").trim();
if (!text) return sections;
const needles = injectNeedles(text);
const rest = [];
for (const section of sections) {
if (!section || section.name === "dsh-purge") continue;
const body = typeof section.text === "string" ? section.text : "";
if (!needles.some((needle) => body.includes(needle))) {
rest.push(section);
continue;
}
let next = body;
for (const needle of needles) next = next.split(needle).join("");
next = next.replace(/\n{3,}/g, "\n\n").trim();
if (!next) continue;
rest.push({ ...section, text: next });
}
return [{ name: "dsh-purge", text, order: GLOBAL_PROMPT_ORDER, interpolate: false }, ...rest];
}
/** 红队预设里要留下来的操作说明起点。这句前面的「你是红队指挥」身份句丢掉。 */
const REDTEAM_OPS_MARK = "## 运行环境前提";
const REDTEAM_LEAD_IDENTITY = "## 你是谁、你不做什么";
const REDTEAM_OPS_NOTE = "身份和规则以上面的提示词为准。下面只补充红队调度步骤,不改写上面的身份。";
function redteamOpsBody(text) {
const raw = String(text || "");
@@ -158,32 +190,94 @@ function redteamOpsBody(text) {
return raw.slice(at).trim();
}
/** prompt-inject.md 后部从这里起只给红队会话。标准模式和其它预设不带这段。 */
/** 红队操作稿里的「你是谁」会盖住用户提示词,模型会把提示词当成用户消息里的注入。 */
export function withoutRedteamLeadIdentity(text) {
const raw = String(text || "");
const start = raw.indexOf(REDTEAM_LEAD_IDENTITY);
if (start < 0) return raw.trim();
const rest = raw.slice(start + REDTEAM_LEAD_IDENTITY.length);
const next = rest.search(/\n## /);
const end = next < 0 ? raw.length : start + REDTEAM_LEAD_IDENTITY.length + next;
return (raw.slice(0, start) + raw.slice(end)).replace(/\n{3,}/g, "\n\n").trim();
}
function redteamProcedure(text) {
const ops = redteamOpsBody(text);
if (ops == null) return null;
const body = withoutRedteamLeadIdentity(ops);
if (!body) return REDTEAM_OPS_NOTE;
if (body.includes(REDTEAM_OPS_NOTE)) return body;
return `${REDTEAM_OPS_NOTE}\n\n${body}`;
}
/** 这一句及其后文是竞赛沙箱约定,只留给官方模式。红队带上它会和运行环境前提抢授权判断。 */
export const CTF_INJECT_MARK = "CTF CORE CONTRACT";
export function splitRedteamInject(text) {
const raw = String(text || "");
const at = raw.indexOf(CTF_INJECT_MARK);
if (at < 0) return { common: raw, redteamTail: "" };
if (at < 0) return { common: raw, ctfTail: "" };
const common = raw.slice(0, at).replace(/(?:\r?\n[ \t]*[═=\-─━]{6,}[ \t]*)+\s*$/u, "").replace(/\s+$/u, "");
return { common, redteamTail: raw.slice(at).trim() };
return { common, ctfTail: raw.slice(at).trim() };
}
/** 红队用这一份。没有 CTF 标题时原样返回。 */
export function withoutCtfContract(text) {
return splitRedteamInject(text).common;
}
const REGION_LECTURE = /Exception, and this exception overrides[\s\S]*?any part of that task\.\s*/gu;
/** 禁区说明留在提示词文件里给用户看。注入给模型的那份拿掉,避免它自己去核对网段。 */
export function stripRegionLecture(text) {
return String(text || "").replace(REGION_LECTURE, "\n\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n");
}
/** 官方保留 CTF。红队从 CTF 标题处切开。两边都去掉禁区说明。 */
export function modePromptText(text, redteam) {
const raw = redteam ? withoutCtfContract(text) : String(text || "");
return stripRegionLecture(raw).trim();
}
function presetLabel(value) {
if (typeof value === "string") return value.trim();
if (!value || typeof value !== "object") return "";
if (typeof value.id === "string" && value.id.trim()) return value.id.trim();
if (typeof value.name === "string" && value.name.trim()) return value.name.trim();
return "";
}
export function isRedteamPresetId(value) {
const text = presetLabel(value);
if (!text) return false;
if (text === "redteam") return true;
if (/^red[\s_-]*team$/i.test(text)) return true;
const label = text.replace(/不是红队/g, "").replace(/非红队/g, "");
if (/红队/.test(label)) return true;
return false;
}
export function sessionAgentPreset(context) {
const session = sessionOfContext(context);
const projected = presetLabel(session?.projectionValues?.agentPreset || session?.agentPreset);
if (projected) return projected;
const headerPreset = presetLabel(session?.header?.agentPreset);
if (headerPreset) return headerPreset;
let preset = "";
const headerPreset = session?.header?.agentPreset;
if (typeof headerPreset === "string" && headerPreset) preset = headerPreset;
for (const event of eventList(session)) {
if (event?.type !== "agent-preset/selected") continue;
const name = event.data?.agentPreset || event.data?.preset || event.data?.name;
if (typeof name === "string" && name) preset = name;
const name = presetLabel(event.data?.agentPreset || event.data?.preset || event.data?.name);
if (name) preset = name;
}
return preset;
}
export function isRedteamSession(context) {
return sessionAgentPreset(context) === "redteam";
const session = sessionForInject(context);
if (session && session !== sessionOfContext(context)) {
return isRedteamPresetId(sessionAgentPreset({ session }));
}
return isRedteamPresetId(sessionAgentPreset(context));
}
function writePurgeSection(sections, inject) {
@@ -199,7 +293,7 @@ function writePurgeSection(sections, inject) {
return [{ name: "dsh-purge", text, order: -10000 }, ...next];
}
/** 注册顺序在 5000,原文已经包含注入时不会再往前插,第二轮就继续用宿主开头的那条系统消息。 */
/** 宿主按 order 升序拼接。提示词必须排在身份、Agent Teams、工作目录之前。 */
function hoistOperatorPrompt(sections) {
const index = sections.findIndex((section) => section?.name === "dsh-purge");
if (index < 0) return sections;
@@ -212,9 +306,42 @@ function sessionOfContext(context) {
return context?.agent?.session || context?.session || null;
}
function inheritsParentPrompt(session) {
const header = session?.header;
if (!header?.parentSession) return false;
return header.origin === "subagent" || (header.delegationDepth ?? 0) > 0;
}
function parentSessionRecord(context, parentId) {
const ctx = context?.agent?.ctx || context?.ctx;
if (!ctx || !parentId) return null;
try {
const registry = ctx.agents || ctx.get?.("agents");
const parent = registry?.get?.(parentId);
if (parent?.session) return parent.session;
} catch {
/* 父会话不在这条注册表上时,用子会话自己的预设。 */
}
return null;
}
/** 子代理沿父会话走到主会话,注入和主会话同一份。 */
export function sessionForInject(context) {
let session = sessionOfContext(context);
const seen = new Set();
while (session && !seen.has(session)) {
seen.add(session);
if (!inheritsParentPrompt(session)) return session;
const parent = parentSessionRecord(context, session.header.parentSession);
if (!parent || parent === session) return session;
session = parent;
}
return sessionOfContext(context);
}
export function isRedteamSubagent(context) {
const header = sessionOfContext(context)?.header;
return header?.origin === "subagent" && header?.agentPreset === "redteam";
return header?.origin === "subagent" && isRedteamSession(context);
}
/**
@@ -227,7 +354,7 @@ function attachInjectToRedteamPersona(sections, inject, roleText, cardText) {
const role = typeof roleText === "string" ? roleText.trim() : "";
const card = typeof cardText === "string" ? cardText.trim() : "";
const next = sections.map((section) => {
const ops = redteamOpsBody(section?.text);
const ops = redteamProcedure(section?.text);
if (ops == null) return section;
attached = true;
const parts = [];
@@ -407,6 +534,20 @@ function foldInjectIntoPersona(sections, injectText) {
return [{ name: "deployment:persona-prefix", text: inject, order }, ...out];
}
function withOwnServers(injectText) {
const text = String(injectText || "").trim();
if (!text) return text;
try {
const note = ownServerNote();
if (!note) return text;
const at = text.indexOf(OWN_SERVER_MARK);
const base = at >= 0 ? text.slice(0, at).trim() : text;
return `${base}\n\n${note}`;
} catch {
return text;
}
}
export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) {
if (!assembled || !Array.isArray(assembled.sections)) return assembled;
const opts = normalizeRewriteOptions(fallbackInject, options);
@@ -427,8 +568,9 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
}
}
const injectText = collectInjectText(purge, opts.fallbackInject);
const redteam = isRedteamSession(opts.context);
const rawInject = modePromptText(collectInjectText(purge, opts.fallbackInject), redteam);
const injectText = withOwnServers(rawInject);
// #29: 不要把上一条 system/message 全文钉回 sections。
// 默认留下 dsh-purge 段。0.1.5 在 waterfall 之后若 complete:true,只认这段把注入抄进最终提示词;
// 提前折进 persona 再删掉本段,重启加载该逻辑后注入会丢。
@@ -436,15 +578,18 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
const extras = withoutHardcodedExec(opts.dropPurgeAfterFold
? purge.filter((section) => section.name !== "dsh-purge")
: purge);
let sections = [...folded, ...extras];
if (!redteam) {
sections = writePurgeSection(withoutRedteamPreset(sections), injectText);
assembled.sections = ensureFullInject(sections, injectText);
return assembled;
let sections = [...folded, ...extras].map((section) => {
if (!section || typeof section.text !== "string") return section;
const cut = modePromptText(section.text, redteam);
return cut === section.text ? section : { ...section, text: cut };
});
if (!redteam) sections = withoutRedteamPreset(sections);
else {
const withOps = attachInjectToRedteamPersona(sections, injectText, opts.roleText, opts.cardText);
sections = withOps === sections
? insertRoleSection(insertCardSection(sections, opts.cardText), opts.roleText)
: withOps;
}
assembled.sections = ensureFullInject(
attachInjectToRedteamPersona(sections, injectText),
injectText,
);
assembled.sections = leadWithInject(sections, injectText);
return assembled;
}
+68 -9
View File
@@ -12,11 +12,11 @@ import {
isRedteamSession,
rewritePromptAssembly,
} from "./identity.js";
import { installSubagentRoleCapture } from "./redteam/role-section.js";
import { installSubagentRoleCapture, resolveSubagentRoleText } from "./redteam/role-section.js";
import * as rewind from "./rewind.js";
import * as continueRetry from "./continue-retry.js";
import * as uninstaller from "./uninstall.js";
import { installRegionGate } from "./net-scope.js";
import { installRegionGate, readAllowText, writeAllowText } from "./net-scope.js";
export const name = "dsh-purge";
@@ -187,9 +187,10 @@ export function registerPromptSections(ctx, config, _injectFile) {
ctx.systemPrompt.section({
name: "dsh-purge",
order: GLOBAL_PROMPT_ORDER,
text: () => {
interpolate: false,
text: (context) => {
if (!injectAllowedNow(config)) return "";
return rules.resolveInjectText(core.findDshHome()).text;
return rules.resolveModeInject(core.findDshHome(), isRedteamSession(context));
},
});
@@ -233,21 +234,31 @@ function installMnemonMessageStrip(ctx, config = {}) {
function rewriteLiveAssembly(config, assembled, context) {
const enabled = config.enabled !== false;
const redteam = enabled && isRedteamSession(context);
const inject = enabled ? readInjectFallback(context) : "";
return rewritePromptAssembly(assembled, {
fallbackInject: inject,
dropMnemon: config.stripMnemon !== false,
dropPurgeAfterFold: false,
context,
roleText: redteam ? resolveSubagentRoleText(context) : "",
});
}
/** Cordis 的 ctx 是 Proxy:未声明 inject 时点属性会抛 "cannot get property ... without inject",所以两段都要包 try。 */
function permissionPresetsOf(ctx) {
if (ctx?.permissionPresets && typeof ctx.permissionPresets.set === "function") return ctx.permissionPresets;
try {
const direct = ctx?.permissionPresets;
if (direct && typeof direct.set === "function") return direct;
} catch {
/* 未 inject 这项服务时,Cordis 代理会抛,不能让新会话的全开权限钉死失败。 */
}
try {
const svc = ctx?.get?.("permissionPresets");
if (svc && typeof svc.set === "function") return svc;
} catch {}
} catch {
/* 没有这项服务。 */
}
return null;
}
@@ -283,6 +294,24 @@ function installFreshFullAccess(ctx) {
} catch {}
}
function installRewindDeriveFilter(ctx) {
if (!ctx || ctx.__dshPurgeRewindDerive) return;
ctx.__dshPurgeRewindDerive = true;
const wrapOne = (session) => {
try { rewind.wrapSessionDeriveMessages(session); } catch { /* ignore */ }
};
try {
const store = ctx.get?.("sessions");
const all = typeof store?.all === "function" ? store.all()
: typeof store?.list === "function" ? store.list()
: [];
for (const session of all || []) wrapOne(session);
} catch { /* ignore */ }
try {
ctx.on("session/created", (session) => wrapOne(session));
} catch { /* ignore */ }
}
function installIdentityOverride(ctx, config = {}) {
if (typeof ctx.on !== "function") return;
installSubagentRoleCapture(ctx);
@@ -317,13 +346,14 @@ function shimNeedsPatch(state) {
}
async function settleInstalledPatches(config, ctx) {
try { core.rememberUnpackedArchive(); } catch { /* 没有官方安装目录时不必记归档 */ }
if (officialUpdate.upgradeMarkerExists(process.execPath)) {
const upgraded = await reapply.reapplyInstalled({ scheduleSwap: false, forceExtract: true });
officialUpdate.clearUpgradeMarker(process.execPath);
const upgraded = await reapply.reapplyInstalled({ scheduleSwap: false, upgrade: true });
if (!upgraded.ok) {
log(config, "official upgrade reapply failed:", upgraded.error || "");
return "reapply-failed";
}
officialUpdate.clearUpgradeMarker(process.execPath);
officialUpdate.clearStaleExtractedApps(process.execPath);
log(config, "official upgrade reapplied; restarting onto the new build");
try {
@@ -786,6 +816,7 @@ export function apply(ctx, config) {
installIdentityOverride(ctx, cfg);
installRegionGate(ctx);
installFreshFullAccess(ctx);
installRewindDeriveFilter(ctx);
installMnemonMessageStrip(ctx, cfg);
const injectFile = core.findOverrideFile(core.findDshHome());
registerPromptSections(ctx, cfg, injectFile);
@@ -1261,7 +1292,7 @@ function installWebServer(ctx, cfg) {
});
return;
}
if (typeof body?.content === "string") {
if (typeof body?.content === "string" && core.normalizeOverride(body.content)) {
await core.saveOverrideContent(state.dsh_home, body.content);
}
await core.backupAll(state.ai_base);
@@ -1424,6 +1455,34 @@ function installWebServer(ctx, cfg) {
response.end();
},
}, "dsh-purge: override");
registerPluginRoute({
kind: "exact",
path: "/dsh-purge/own-servers",
handler: async (request, response) => {
const home = core.findDshHome();
if (request.method === "GET") {
sendJson(response, 200, { ok: true, content: readAllowText(home) });
return;
}
if (request.method === "POST") {
try {
const body = await readJsonBody(request);
const content = typeof body?.content === "string" ? body.content : null;
if (content === null) {
sendJson(response, 400, { ok: false, error: "content must be a string" });
return;
}
const saved = await writeAllowText(home, content);
sendJson(response, 200, { ok: true, content: saved.text, dropped: saved.dropped });
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e && e.message ? e.message : e) });
}
return;
}
response.writeHead(405, { allow: "GET, POST" });
response.end();
},
}, "dsh-purge: own-servers");
installRulesHttp(host.webServer);
installSkillsHttp(host.webServer);
registerPluginRoute({
+575 -80
View File
@@ -1,22 +1,96 @@
import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { promises as dns } from "node:dns";
const REGION_NAME = {
CN: "中国大陆",
HK: "香港",
MO: "澳门",
};
import { findDshHome } from "./core.js";
const SUFFIXES = [
[".cn", "CN"],
[".hk", "HK"],
[".mo", "MO"],
[".xn--fiqs8s", "CN"],
[".xn--fiqz9s", "CN"],
[".xn--j6w193g", "HK"],
[".xn--mix082f", "MO"],
[".xn--55qx5d", "CN"],
[".xn--io0a7i", "CN"],
[".xn--55qw42g", "CN"],
[".xn--zfr164b", "CN"],
[".xn--czru2d", "CN"],
[".xn--hxt814e", "CN"],
[".xn--fiq228c5hs", "CN"],
[".xn--3bst00m", "CN"],
[".xn--ses554g", "CN"],
[".中国", "CN"],
[".中國", "CN"],
[".公司", "CN"],
[".网络", "CN"],
[".網絡", "CN"],
[".公益", "CN"],
[".政务", "CN"],
[".商城", "CN"],
[".网店", "CN"],
[".中文网", "CN"],
[".集团", "CN"],
[".网址", "CN"],
[".在线", "CN"],
[".移动", "CN"],
[".我爱你", "CN"],
[".香港", "HK"],
[".澳门", "MO"],
[".澳門", "MO"],
[".com.cn", "CN"],
[".net.cn", "CN"],
[".org.cn", "CN"],
[".gov.cn", "CN"],
[".edu.cn", "CN"],
[".ac.cn", "CN"],
[".mil.cn", "CN"],
[".ah.cn", "CN"],
[".bj.cn", "CN"],
[".cq.cn", "CN"],
[".fj.cn", "CN"],
[".gd.cn", "CN"],
[".gs.cn", "CN"],
[".gx.cn", "CN"],
[".gz.cn", "CN"],
[".ha.cn", "CN"],
[".hb.cn", "CN"],
[".he.cn", "CN"],
[".hi.cn", "CN"],
[".hl.cn", "CN"],
[".hn.cn", "CN"],
[".jl.cn", "CN"],
[".js.cn", "CN"],
[".jx.cn", "CN"],
[".ln.cn", "CN"],
[".nm.cn", "CN"],
[".nx.cn", "CN"],
[".qh.cn", "CN"],
[".sc.cn", "CN"],
[".sd.cn", "CN"],
[".sh.cn", "CN"],
[".sn.cn", "CN"],
[".sx.cn", "CN"],
[".tj.cn", "CN"],
[".xj.cn", "CN"],
[".xz.cn", "CN"],
[".yn.cn", "CN"],
[".zj.cn", "CN"],
[".hk.cn", "HK"],
[".mo.cn", "MO"],
[".cn", "CN"],
[".com.hk", "HK"],
[".edu.hk", "HK"],
[".gov.hk", "HK"],
[".idv.hk", "HK"],
[".net.hk", "HK"],
[".org.hk", "HK"],
[".hk", "HK"],
[".com.mo", "MO"],
[".edu.mo", "MO"],
[".gov.mo", "MO"],
[".net.mo", "MO"],
[".org.mo", "MO"],
[".mo", "MO"],
];
const FILE_SUFFIX = new Set([
@@ -26,11 +100,6 @@ const FILE_SUFFIX = new Set([
"ini", "bak", "patch", "diff", "sh", "ps1", "cmd", "exe",
]);
const SKIP_KEYS = new Set([
"content", "old_string", "new_string", "text", "patch", "code",
"file_text", "body", "diff",
]);
const ranges = loadRanges();
const v4 = ranges.v4;
const v6 = ranges.v6.map((row) => ({
@@ -39,9 +108,70 @@ const v6 = ranges.v6.map((row) => ({
region: row[2],
})).filter((row) => row.value != null);
const lookupCache = new Map();
const hostLookupCache = new Map();
const LOOKUP_TTL_MS = 10 * 60 * 1000;
const LOOKUP_LIMIT = 12;
const LOOKUP_CONCURRENCY = 6;
const DENIAL = "不行,这是严令禁止的";
const CF_V4 = [
"173.245.48.0/20",
"103.21.244.0/22",
"103.22.200.0/22",
"103.31.4.0/22",
"141.101.64.0/18",
"108.162.192.0/18",
"190.93.240.0/20",
"188.114.96.0/20",
"197.234.240.0/22",
"198.41.128.0/17",
"162.158.0.0/15",
"104.16.0.0/13",
"104.24.0.0/14",
"172.64.0.0/13",
"131.0.72.0/22",
];
const CF_V6 = [
["2400:cb00::", 32],
["2606:4700::", 32],
["2803:f800::", 32],
["2405:b500::", 32],
["2405:8100::", 32],
["2a06:98c0::", 29],
["2c0f:f248::", 32],
];
const VENDOR_NS = [
"aliyun.com",
"aliyuncs.com",
"alibabadns.com",
"alidns.com",
"hichina.com",
"dnspod.com",
"dnspod.net",
"dnsv1.com",
"dnsv2.com",
"dnsv3.com",
"dnsv4.com",
"dnsv5.com",
"qcloud.com",
"myqcloud.com",
"tencent.com",
"tencentcs.com",
"huaweicloud.com",
"hwclouds.com",
"baidubce.com",
"bdydns.com",
"volces.com",
"volcengine.com",
"ctyun.cn",
"ucloud.cn",
"qingcloud.com",
"ksyun.com",
"jdcloud.com",
];
const ATTACK = /渗透|攻击|打穿|打下|打站|入侵|拿下|拿壳|拿权限|爆破|提权|webshell|getshell|端口扫描|pentest|\bexploit\b|\battack\b|\bbreach\b|\bpwn\b/i;
function loadRanges() {
try {
@@ -166,6 +296,21 @@ function addHost(raw, hosts) {
hosts.add(host);
}
function inFilePath(sample, index) {
const prev = sample[index - 1];
return prev === "/" || prev === "\\";
}
/** 网址里的主机照收。裸名字要像域名:路径片段、文件后缀、两段的 .mo 文件名丢掉。 */
function keepBareDomain(sample, index, name) {
if (inFilePath(sample, index)) return false;
const labels = name.split(".");
const tail = labels[labels.length - 1];
if (FILE_SUFFIX.has(tail)) return false;
if (labels.length === 2 && tail === "mo") return false;
return true;
}
function collectFromText(text, hosts) {
const sample = String(text || "").slice(0, 32768);
const url = /\b(?:[a-z][a-z0-9+.-]*:\/\/)([^/?#\s]+)/gi;
@@ -174,35 +319,14 @@ function collectFromText(text, hosts) {
for (const match of sample.matchAll(ipv4)) hosts.add(match[0]);
const ipv6 = /\b(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}\b/gi;
for (const match of sample.matchAll(ipv6)) hosts.add(match[0]);
if (/[\\/]/.test(sample)) return;
const domain = /\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\b/gi;
for (const match of sample.matchAll(domain)) {
const name = match[0].toLowerCase();
const tail = name.slice(name.lastIndexOf(".") + 1);
if (FILE_SUFFIX.has(tail)) continue;
if (!keepBareDomain(sample, match.index, name)) continue;
hosts.add(name);
}
}
function collect(value, key, hosts) {
if (typeof value === "string") {
if (SKIP_KEYS.has(String(key || "")) && value.length > 200) return;
collectFromText(value, hosts);
return;
}
if (Array.isArray(value)) {
for (const item of value) collect(item, key, hosts);
return;
}
if (value && typeof value === "object") {
for (const [childKey, child] of Object.entries(value)) collect(child, childKey, hosts);
}
}
function blocked(label, region) {
return { label, region, regionName: REGION_NAME[region] || region };
}
async function addressesOf(host) {
const found = [];
const records = await Promise.race([
@@ -231,65 +355,436 @@ async function addressesOf(host) {
return found;
}
async function regionOfResolved(host) {
const now = Date.now();
const cached = lookupCache.get(host);
if (cached && now - cached.at < LOOKUP_TTL_MS) return cached.region;
let region = "";
try {
for (const address of await addressesOf(host)) {
region = regionOfIp(address);
if (region) break;
}
} catch {
region = "";
}
lookupCache.set(host, { at: now, region });
return region;
const HOST_NAME = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
const V4_TEXT = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
export function allowFilePath(dshHome = findDshHome()) {
return path.join(dshHome, "net-scope-allow.txt");
}
/** 命中中国大陆、香港、澳门网段时返回目标;解析不到或不在这些网段则放行。 */
export async function findBlocked(value) {
/** 只接受一个 IP 或一个完整主机名。账号可以写成 user@host。密钥、网段、通配符丢掉。 */
export function entryHost(raw) {
const text = String(raw || "").trim();
if (!text || text.startsWith("#")) return "";
if (text.length > 253 || /[\s/\\*]/.test(text)) return "";
if (/BEGIN |PRIVATE KEY|ssh-(?:rsa|ed25519|dss) /i.test(text)) return "";
let body = text;
const at = body.lastIndexOf("@");
if (at >= 0) {
const user = body.slice(0, at);
if (!/^[A-Za-z0-9._-]{1,32}$/.test(user)) return "";
body = body.slice(at + 1);
}
const host = hostOf(body);
if (!host || host.length > 253) return "";
if (V4_TEXT.test(host)) return host;
if (host.includes(":")) return parseIpv6(host) != null ? host : "";
if (!HOST_NAME.test(host)) return "";
const tail = host.slice(host.lastIndexOf(".") + 1);
if (FILE_SUFFIX.has(tail)) return "";
return host;
}
export function normalizeAllowText(text) {
const kept = [];
const seen = new Set();
let dropped = 0;
for (const line of String(text || "").split(/\r?\n/)) {
const raw = line.trim();
if (!raw) continue;
if (raw.startsWith("#")) {
kept.push(raw);
continue;
}
const host = entryHost(raw);
if (!host) {
dropped += 1;
continue;
}
if (seen.has(host)) continue;
seen.add(host);
const at = raw.lastIndexOf("@");
kept.push(at > 0 ? `${raw.slice(0, at)}@${host}` : host);
}
return { text: kept.length ? `${kept.join("\n")}\n` : "", dropped, hosts: [...seen] };
}
export function readAllowText(dshHome = findDshHome()) {
try {
return fs.readFileSync(allowFilePath(dshHome), "utf8");
} catch {
return "";
}
}
export async function writeAllowText(dshHome, text) {
const normalized = normalizeAllowText(text);
const fp = allowFilePath(dshHome);
await fs.promises.mkdir(path.dirname(fp), { recursive: true });
await fs.promises.writeFile(fp, normalized.text, "utf8");
allowCache = { path: "", mtime: -1, exact: new Set(), ips: null, at: 0 };
return normalized;
}
let allowCache = { path: "", mtime: -1, exact: new Set(), ips: null, at: 0 };
function readAllowExact(dshHome = findDshHome()) {
const fp = allowFilePath(dshHome);
let mtime = -1;
try {
mtime = fs.statSync(fp).mtimeMs;
} catch {
mtime = -1;
}
if (allowCache.path === fp && allowCache.mtime === mtime) return allowCache;
const exact = new Set(normalizeAllowText(readAllowText(dshHome)).hosts);
allowCache = { path: fp, mtime, exact, ips: null, at: Date.now() };
return allowCache;
}
function allowDecision(dshHome) {
return readAllowExact(dshHome);
}
export function ownServerNote() {
return "";
}
function permittedHost(host, allow) {
return allow.exact.has(host);
}
function ipv4InCidr(ip, cidr) {
const [base, bitsText] = String(cidr).split("/");
const addr = ipv4ToInt(ip);
const net = ipv4ToInt(base);
const bits = Number(bitsText);
if (addr == null || net == null || !Number.isInteger(bits) || bits < 0 || bits > 32) return false;
if (bits === 0) return true;
const mask = (0xffffffff << (32 - bits)) >>> 0;
return (addr & mask) === (net & mask);
}
function ipv6InPrefix(ip, base, len) {
const value = parseIpv6(ip);
const net = parseIpv6(base);
if (value == null || net == null) return false;
const shift = BigInt(128 - len);
return (value >> shift) === (net >> shift);
}
function isCloudflareAddress(ip) {
const text = String(ip || "").trim().toLowerCase();
if (text.includes(":")) return CF_V6.some(([base, len]) => ipv6InPrefix(text, base, len));
return CF_V4.some((cidr) => ipv4InCidr(text, cidr));
}
function isOwnNetwork(host) {
const name = hostOf(host);
if (!name) return false;
if (name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local")) return true;
if (name.includes(":")) {
const value = parseIpv6(name);
if (value == null) return false;
if (value === 0n || value === 1n) return true;
if ((value >> 118n) === 0x3fan) return true;
if ((value >> 121n) === 0x7en) return true;
return false;
}
const value = ipv4ToInt(name);
return value != null && isSkippedV4(value);
}
function isIp(host) {
return V4_TEXT.test(host) || host.includes(":");
}
function nsHit(nameservers, suffixes) {
for (const raw of nameservers || []) {
const name = String(raw || "").trim().toLowerCase().replace(/\.$/, "");
if (!name) continue;
if (suffixes.some((suffix) => name === suffix || name.endsWith(`.${suffix}`))) return true;
}
return false;
}
function coveredByCloudflare(addresses, nameservers) {
if (nsHit(nameservers, ["cloudflare.com"])) return true;
const pub = (addresses || []).map((item) => String(item || "").trim()).filter((item) => item && !isOwnNetwork(item));
return pub.length > 0 && pub.every(isCloudflareAddress);
}
function taskHit(label, kind) {
return { label, kind };
}
/** 纯判断:后缀优先,Cloudflare 只放过还没被后缀命中的名字。厂商看 NS,也看地址的反向名字。 */
export function decisionFromLookup({ host, addresses = [], nameservers = [], pointers = [] } = {}) {
const name = hostOf(host);
if (!name || isOwnNetwork(name)) return null;
if (regionOfSuffix(name)) return taskHit(name, "domain");
if (isIp(name)) return regionOfIp(name) ? taskHit(name, "range") : null;
if (coveredByCloudflare(addresses, nameservers)) return null;
for (const address of addresses) {
if (regionOfIp(address)) return taskHit(name, "range");
}
if (nsHit(nameservers, VENDOR_NS) || nsHit(pointers, VENDOR_NS)) return taskHit(name, "server");
return null;
}
export function isAttackTask(text) {
return ATTACK.test(String(text || ""));
}
function hostsInTask(text) {
const hosts = new Set();
collect(value, "", hosts);
const sample = String(text || "").slice(0, 32768);
collectFromText(sample, hosts);
const labeled = /(?:[a-z0-9\u00a1-\uffff](?:[a-z0-9\u00a1-\uffff-]{0,61}[a-z0-9\u00a1-\uffff])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59}|[\u4e00-\u9fff]{2,12})/giu;
for (const match of sample.matchAll(labeled)) {
const name = match[0].toLowerCase().replace(/\.$/, "");
if (!keepBareDomain(sample, match.index, name)) continue;
addHost(name, hosts);
}
return hosts;
}
async function pointersOf(addresses) {
const names = [];
const list = [];
const seen = new Set();
for (const raw of addresses || []) {
const address = String(raw || "").trim().toLowerCase();
if (!address || seen.has(address) || isOwnNetwork(address)) continue;
seen.add(address);
list.push(address);
if (list.length >= 4) break;
}
await Promise.all(list.map(async (address) => {
try {
const rows = await Promise.race([
dns.reverse(address).catch(() => []),
new Promise((resolve) => setTimeout(() => resolve([]), 1500)),
]);
if (!Array.isArray(rows)) return;
for (const row of rows) {
const name = String(row || "").trim().toLowerCase().replace(/\.$/, "");
if (name) names.push(name);
}
} catch {
/* 反向解析失败不当成命中。 */
}
}));
return names;
}
async function firstHit(items, worker) {
const list = Array.isArray(items) ? items : [];
if (!list.length) return null;
let cursor = 0;
let found = null;
const width = Math.min(LOOKUP_CONCURRENCY, list.length);
const run = async () => {
while (found == null && cursor < list.length) {
const host = list[cursor];
cursor += 1;
const hit = await worker(host);
if (hit && found == null) found = hit;
}
};
await Promise.all(Array.from({ length: width }, () => run()));
return found;
}
async function nameserversOf(host) {
const records = await Promise.race([
dns.resolveNs(host).catch(() => []),
new Promise((resolve) => setTimeout(() => resolve([]), 1500)),
]);
return Array.isArray(records) ? records.map((item) => String(item).trim().toLowerCase()) : [];
}
async function lookupHost(host) {
const now = Date.now();
const cached = hostLookupCache.get(host);
if (cached && now - cached.at < LOOKUP_TTL_MS) return cached.lookup;
const lookup = { addresses: [], nameservers: [], pointers: [] };
try {
lookup.addresses = await addressesOf(host);
} catch {
lookup.addresses = [];
}
try {
lookup.nameservers = await nameserversOf(host);
} catch {
lookup.nameservers = [];
}
if (lookup.addresses.length && !coveredByCloudflare(lookup.addresses, lookup.nameservers)) {
lookup.pointers = await pointersOf(lookup.addresses);
}
if (lookup.addresses.length || lookup.nameservers.length || lookup.pointers.length) {
hostLookupCache.set(host, { at: now, lookup });
}
return lookup;
}
export async function classifyHost(host, dshHome = findDshHome()) {
const name = hostOf(host);
if (!name) return null;
const allow = allowDecision(dshHome);
if (permittedHost(name, allow)) return null;
if (isOwnNetwork(name) || regionOfSuffix(name) || isIp(name)) {
return decisionFromLookup({ host: name });
}
const looked = await lookupHost(name);
return decisionFromLookup({
host: name,
addresses: looked.addresses,
nameservers: looked.nameservers,
pointers: looked.pointers,
});
}
export async function taskTargetHit(text, dshHome = findDshHome()) {
if (!isAttackTask(text)) return null;
const allow = allowDecision(dshHome);
const pending = [];
for (const host of hosts) {
const suffix = regionOfSuffix(host);
if (suffix) return blocked(host, suffix);
const ip = regionOfIp(host);
if (ip) return blocked(host, ip);
if (host.includes(".") && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) && !host.includes(":")) {
pending.push(host);
for (const host of hostsInTask(text)) {
const name = hostOf(host);
if (!name || permittedHost(name, allow) || isOwnNetwork(name)) continue;
if (regionOfSuffix(name)) return taskHit(name, "domain");
if (isIp(name)) {
if (regionOfIp(name)) return taskHit(name, "range");
continue;
}
pending.push(name);
}
return firstHit(pending, (host) => classifyHost(host, dshHome));
}
function messageBody(message) {
if (typeof message?.content === "string") return message.content;
if (!Array.isArray(message?.content)) return typeof message?.text === "string" ? message.text : "";
return message.content.map((block) => {
if (typeof block === "string") return block;
if (block && block.type === "text" && typeof block.text === "string") return block.text;
return "";
}).join("\n");
}
function humanTaskText(message) {
if (!message || typeof message !== "object") return "";
if (message.role && message.role !== "user") return "";
const kind = message.source?.kind;
if (kind && kind !== "user") return "";
const text = messageBody(message);
if (/^\s*Current runtime context\b/i.test(text)) return "";
return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "\n").trim();
}
function sessionOf(payload) {
const agent = payload?.agent;
if (agent?.session && typeof agent.session.append === "function") return agent.session;
if (payload?.session && typeof payload.session.append === "function") return payload.session;
return null;
}
async function denialMessage() {
try {
const mod = await import("@deepseek-ai/dsh-llm");
if (typeof mod.createAssistantMessage === "function") {
return mod.createAssistantMessage({
content: [{ type: "text", text: DENIAL }],
source: { provider: "dsh-purge", model: "task-gate" },
});
}
} catch {
/* 宿主包不在这条导入路径上时用手写消息。 */
}
return {
id: randomUUID(),
role: "assistant",
content: [{ type: "text", text: DENIAL }],
source: { kind: "model", provider: "dsh-purge", model: "task-gate" },
};
}
function denialStream() {
return [
{ type: "block-start", index: 0, blockType: "text" },
{ type: "text-delta", index: 0, text: DENIAL },
{ type: "block-end", index: 0, block: { type: "text", text: DENIAL } },
{ type: "finish", reason: "stop" },
];
}
async function appendDenial(session, turn, step) {
session.append("assistant/message", {
turn,
step,
message: await denialMessage(),
stream: denialStream(),
}, { surfaceOp: "append" });
}
async function parkDenial(payload) {
const session = sessionOf(payload);
const turn = Number(payload?.turn);
const step = Number(payload?.step);
if (!session || !Number.isSafeInteger(turn) || step !== 1) return false;
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
let opened = false;
try {
for (const message of messages) {
session.append("user/message", message, { surfaceOp: "append" });
}
session.append("step/start", { turn, step });
opened = true;
await appendDenial(session, turn, step);
session.append("step/end", { turn, step });
return true;
} catch {
try {
if (!opened) session.append("step/start", { turn, step });
await appendDenial(session, turn, step);
session.append("step/end", { turn, step });
return true;
} catch {
if (opened) {
try { session.append("step/end", { turn, step }); } catch { /* 步已经合不上时,交给宿主收尾。 */ }
}
return false;
}
}
const batch = pending.slice(0, LOOKUP_LIMIT);
const resolved = await Promise.all(batch.map((host) => regionOfResolved(host)));
for (let i = 0; i < batch.length; i += 1) {
if (resolved[i]) return blocked(batch[i], resolved[i]);
}
return null;
}
export function installRegionGate(ctx) {
if (!ctx || typeof ctx.on !== "function") return;
const hook = async (exec, next) => {
const hook = async (payload, next) => {
const forward = () => (typeof next === "function" ? next() : { kind: "enter", messages: payload?.messages || [] });
if (Number(payload?.step) !== 1) return forward();
let hit = null;
try {
const hit = await findBlocked(exec?.arguments);
if (hit) {
return {
kind: "deny",
reason: "不行,这是严令禁止的",
};
}
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
const task = messages.map(humanTaskText).filter(Boolean).join("\n");
if (!task || !isAttackTask(task)) return forward();
hit = await taskTargetHit(task);
} catch {
return next();
return forward();
}
return next();
if (!hit) return forward();
try {
const parked = await parkDenial(payload);
if (parked) return { kind: "enter", messages: [] };
} catch {
/* 禁止句没写上时不能把这一轮收成空白。 */
}
return forward();
};
const arm = () => {
if (ctx.__dshPurgeRegionGate) return;
try {
ctx.on("tools/pre-execute", hook, { global: true, prepend: true });
ctx.on("agent/pre-step", hook, { global: true, prepend: true });
ctx.__dshPurgeRegionGate = true;
} catch {
/* 宿主还没有这条事件时,下一拍再挂。 */
+28 -6
View File
@@ -77,33 +77,55 @@ export async function reapplyInstalled(options = {}) {
core.applyRuntimeEnv();
let aiBase = null;
let handoff = null;
let freshExtract = null;
try {
const state = await core.gatherState();
aiBase = state.ai_base;
} catch (e) {
return { ok: false, error: String(e && e.message ? e.message : e) };
}
if (!aiBase || options.forceExtract === true) {
const sealed = core.sealedAsarHandoff();
if (!aiBase || sealed) {
try {
const opened = await core.openSealedDesktopHost({ forceExtract: options.forceExtract === true });
const opened = await core.openSealedDesktopHost({ upgrade: options.upgrade === true });
if (opened.aiBase) aiBase = opened.aiBase;
if (opened.swapAsar) handoff = opened;
if (opened.extracted) freshExtract = opened;
} catch (e) {
return { ok: false, error: String(e && e.message ? e.message : e) };
}
} else {
handoff = core.sealedAsarHandoff();
core.rememberUnpackedArchive();
}
if (!aiBase) return { ok: false, error: core.missingAiBaseMessage() };
const reverted = await core.revertAll(aiBase);
await core.revertAllShims();
// 刚解开的是官方原件。已经在用的目录仍先还原再按这一版重打。
const reverted = freshExtract ? { reverted: [] } : await core.revertAll(aiBase);
if (!freshExtract) await core.revertAllShims();
await core.backupAll(aiBase);
const report = await core.applyPatches(aiBase);
await core.patchAllShims();
const flash = core.silenceCmdFlash(aiBase);
const summary = core.summarizeApplyReport(report);
const clean = summary.failed.length === 0 && flash.ok === true && core.hostCleanMarkersPresent(aiBase);
if (clean) writeAppliedStamp(installedRev());
if (!clean && freshExtract) {
const restored = core.restoreSealedExtract(freshExtract.appDir, freshExtract.prev);
return {
ok: false,
error: restored ? "清洗没有完成,已放回上一份解开目录" : "清洗没有完成",
restored,
version: pluginVersion(),
reverted: 0,
applied: summary.applied || 0,
failed: summary.failed.length,
renamed: false,
needsFullQuit: false,
cmdFlashOk: flash.ok === true,
};
}
if (clean) {
writeAppliedStamp(installedRev());
if (freshExtract?.archive) core.writeUnpackedAsarStamp(freshExtract.archive);
}
let renamed = false;
if (clean && handoff?.asar && options.scheduleSwap !== false) {
const swapped = core.scheduleSealedDesktopRestart(handoff);
+7 -5
View File
@@ -8,6 +8,7 @@
*/
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { isRedteamSession } from '../identity.js'
import { redteamRoot } from './platform-config.js'
const ROLE_TAG = /^[ \t]*redteamRole:[ \t]*(recon|assess|vuln-scan|exploit|internal)[ \t]*$/im
@@ -33,15 +34,16 @@ function remember(agent, role) {
for (const id of ids) roleBySession.set(String(id), role)
}
function isRedteamChild(session) {
function isRedteamChild(session, agent) {
const header = session?.header
return header?.origin === 'subagent' && header?.agentPreset === 'redteam'
if (header?.origin !== 'subagent' && !((header?.delegationDepth ?? 0) > 0)) return false
return isRedteamSession({ session, agent: agent ? { ...agent, session } : { session } })
}
export function noteClaimedMessage(payload) {
const agent = payload?.agent
const session = agent?.session
if (!isRedteamChild(session)) return
if (!isRedteamChild(session, agent)) return
const role = parseRedteamRole(textOfMessage(payload?.message))
if (!role) return
remember(agent, role)
@@ -99,9 +101,9 @@ function readRoleFile(engagementId, role) {
export function resolveSubagentRoleText(context) {
try {
const session = context?.agent?.session || context?.session
if (!isRedteamChild(session)) return ''
const agent = context?.agent
const session = agent?.session || context?.session
if (!isRedteamChild(session, agent)) return ''
const sessionId = session?.id ?? agent?.id
let role = sessionId !== undefined && sessionId !== null
? roleBySession.get(String(sessionId)) || ''
+89 -32
View File
@@ -116,20 +116,23 @@ export function pendingInboxInserts(events) {
return ids;
}
export function lastTurnSubagentIds(events) {
export function lastTurnSubagentIds(events, fromSeq = -1) {
const list = Array.isArray(events) ? events : [];
let lastStart = -1;
for (let i = list.length - 1; i >= 0; i -= 1) {
if (list[i]?.type === "turn/start") {
lastStart = list[i].seq;
break;
let floor = Number(fromSeq);
if (!Number.isFinite(floor) || floor < 0) {
floor = -1;
for (let i = list.length - 1; i >= 0; i -= 1) {
if (list[i]?.type === "turn/start") {
floor = list[i].seq;
break;
}
}
}
if (lastStart < 0) return [];
if (floor < 0) return [];
const ids = [];
const seen = new Set();
for (const event of list) {
if (!event || event.seq < lastStart) continue;
if (!event || event.seq < floor) continue;
if (event.type !== "subagent/catalog" && event.type !== "subagent/descriptor") continue;
const id = event.data?.childId || event.data?.sessionId || event.data?.id;
if (!id || seen.has(id)) continue;
@@ -141,18 +144,47 @@ export function lastTurnSubagentIds(events) {
export function planRewind(events) {
const list = Array.isArray(events) ? events : [];
const turnStarts = list.filter((event) => event?.type === "turn/start");
const lastStart = turnStarts[turnStarts.length - 1];
const usersInLastTurn = lastStart
? list.filter((event) => isHumanUserEvent(event) && event.seq >= lastStart.seq)
: [];
const lastUser = usersInLastTurn[0]
|| list.filter(isHumanUserEvent).at(-1);
const lastUser = list.filter(isHumanUserEvent).at(-1);
if (!lastUser) {
return { ok: false, error: "没有可回退的上一句" };
}
const text = userTextFromEvent(lastUser);
return { ok: true, mode: "input", text };
return {
ok: true,
mode: "input",
text: userTextFromEvent(lastUser),
fromSeq: lastUser.seq,
};
}
function isRewindMarkerEvent(event) {
if (!event || event.type !== "user/message") return false;
const id = event.data?.id;
return typeof id === "string" && id.startsWith("rewind-");
}
/** 回退标记只占表面位置,不能再进下一轮模型请求。 */
export function isRewindDerivedMessage(message) {
if (!message) return true;
const id = message.id;
return typeof id === "string" && id.startsWith("rewind-");
}
/** 只拿掉 fromSeq 及之后的表面节点。系统提示停在节点 0 时不动它。前面连续的回退空标记一并清掉,避免下一次发送还带着上一轮。 */
export function cutSurfaceNodes(nodes, fromSeq, eventAt) {
const list = (Array.isArray(nodes) ? nodes : []).map((seq) => Number(seq));
const floor = Number(fromSeq);
let startIdx = list.findIndex((seq) => Number.isFinite(floor) ? seq >= floor : true);
if (startIdx < 0) return [];
const lookup = typeof eventAt === "function" ? eventAt : () => null;
if (startIdx === 0 && lookup(list[0])?.type === "system/message") startIdx = 1;
while (startIdx > 0) {
const prev = lookup(list[startIdx - 1]);
if (!prev || prev.type === "system/message" || !isRewindMarkerEvent(prev)) break;
startIdx -= 1;
}
if (startIdx === 0 && lookup(list[0])?.type === "system/message") startIdx = 1;
if (startIdx >= list.length) return [];
return list.slice(startIdx);
}
function rememberDraft(sessionId, text, parentId) {
@@ -283,6 +315,24 @@ function getAgent(ctx, sessionId) {
}
}
/** 回退后下一句按新请求开,不要接着上一轮的 request/header series。 */
function resetRequestSeries(ctx, sessionId) {
const agent = getAgent(ctx, sessionId);
if (!agent) return;
try { agent.requestHeaderLogged = false; } catch { /* ignore */ }
try { agent.requestSurfaceGeneration = -1; } catch { /* ignore */ }
}
export function wrapSessionDeriveMessages(session) {
if (!session || typeof session.deriveMessages !== "function" || session.__dshPurgeRewindDerive) return session;
const orig = session.deriveMessages.bind(session);
session.deriveMessages = function deriveMessagesWithoutRewind() {
return orig().filter((message) => !isRewindDerivedMessage(message));
};
session.__dshPurgeRewindDerive = true;
return session;
}
async function disarmRewoundSession(ctx, sessionId) {
if (!sessionId) return;
const controller = service(ctx, "sessionController");
@@ -387,14 +437,14 @@ function derivedStillContains(session, text) {
}
if (!Array.isArray(messages)) return false;
for (const message of messages) {
if (!message || message.role === "system") continue;
if (!message || message.role === "system" || isRewindDerivedMessage(message)) continue;
if (flatMessageText(message).includes(needle)) return true;
}
return false;
}
/** 留在当前会话。把系统提示后面的可见记录从模型请求里拿掉,不另开会话。 */
function clearModelHistory(session, text) {
/** 留在当前会话。只把 fromSeq 起的这一轮从模型请求里拿掉,更早的轮次留着。 */
function clearModelHistory(session, text, fromSeq = 0) {
if (!session || typeof session.append !== "function" || !session.surface) {
throw new Error("没有清掉之前发送的内容");
}
@@ -407,15 +457,13 @@ function clearModelHistory(session, text) {
}
const events = typeof session.snapshotEvents === "function" ? session.snapshotEvents() : [];
const eventAt = (seq) => events.find((event) => event?.seq === seq) || session.eventAt?.(seq);
let startIdx = 0;
if (eventAt(nodes[0])?.type === "system/message") startIdx = 1;
if (startIdx >= nodes.length) {
const shadowed = cutSurfaceNodes(nodes, fromSeq, eventAt);
if (shadowed.length === 0) {
if (derivedStillContains(session, text)) {
throw new Error("没有清掉之前发送的内容");
}
return true;
}
const shadowed = nodes.slice(startIdx).map((seq) => Number(seq));
const startSeq = shadowed[0];
const endSeq = shadowed[shadowed.length - 1];
if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq)) {
@@ -430,32 +478,33 @@ function clearModelHistory(session, text) {
surfaceOp: { op: "replace", startSeq, endSeq },
sourceEventSeqs: shadowed,
});
if (derivedStillContains(session, text)) {
const left = new Set((session.surface.nodes || []).map((seq) => Number(seq)));
if (shadowed.some((seq) => left.has(seq))) {
throw new Error("没有清掉之前发送的内容");
}
return true;
}
async function rewindOneSession(ctx, controller, sessionId) {
async function rewindOneSession(ctx, controller, sessionId, options = {}) {
let log = await readSessionLog(ctx, sessionId);
if (lastOpenTurn(log.events)) {
try { ignoreSettled(controller.cancel?.({ sessionId })); } catch { /* ignore */ }
log = await waitTurnClosed(ctx, sessionId);
}
const plan = planRewind(log.events);
const plan = options.full
? { ok: true, mode: "input", text: lastHumanUserText(log.events), fromSeq: 0 }
: planRewind(log.events);
if (!plan.ok) return plan;
await disarmRewoundSession(ctx, sessionId);
const session = liveSession(ctx, sessionId);
const session = wrapSessionDeriveMessages(liveSession(ctx, sessionId));
let cleared = false;
try {
cleared = clearModelHistory(session, plan.text);
cleared = clearModelHistory(session, plan.text, plan.fromSeq);
} catch (err) {
return { ok: false, error: errorText(err) };
}
if (derivedStillContains(session, plan.text)) {
return { ok: false, error: "没有清掉之前发送的内容" };
}
resetRequestSeries(ctx, sessionId);
const rec = rememberDraft(sessionId, plan.text, sessionId);
return {
@@ -499,8 +548,16 @@ export async function applyRewind(ctx, sessionId, mode) {
if (sessionId !== target.sessionId) {
try { ignoreSettled(controller.cancel?.({ sessionId })); } catch { /* ignore */ }
}
const preview = planRewind(target.log?.events || []);
const children = preview.ok ? lastTurnSubagentIds(target.log.events, preview.fromSeq) : [];
const result = await rewindOneSession(ctx, controller, target.sessionId);
if (!result.ok) return result;
for (const childId of children) {
if (!childId || childId === target.sessionId) continue;
if (!liveSession(ctx, childId)) continue;
const child = await rewindOneSession(ctx, controller, childId, { full: true });
if (!child.ok) return child;
}
return { ...result, sourceId: sessionId, mode: "round" };
}
+19 -9
View File
@@ -1,7 +1,8 @@
import fs from "node:fs";
import { promises as fsp } from "node:fs";
import path from "node:path";
import { findDshHome, findOverrideFile, normalizeOverride } from "./core.js";
import { defaultOverrideText, findDshHome, findOverrideFile, normalizeOverride } from "./core.js";
import { modePromptText } from "./identity.js";
const RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
const MAX_RULE_BYTES = 256 * 1024;
@@ -181,25 +182,34 @@ export function overrideFileText(dshHome) {
}
}
function promptOrDefault(dshHome) {
const disk = normalizeOverride(overrideFileText(dshHome));
if (disk) return disk;
return normalizeOverride(defaultOverrideText());
}
/** 没启用规则集时只注入可编辑提示词。启用规则集后以规则集为主。两边都空则不注入。 */
export function resolveInjectText(dshHome) {
const ruleId = activeRuleId(dshHome);
const rule = normalizeOverride(activeRuleText(dshHome));
if (rule) return { text: rule, source: "rule", ruleId };
const prompt = normalizeOverride(overrideFileText(dshHome));
const prompt = promptOrDefault(dshHome);
if (prompt) return { text: prompt, source: "prompt", ruleId: null };
return { text: "", source: "none", ruleId };
}
/** 红队在当前正文之外,再带上另一份没有重复的提示词或规则集。 */
/**
* 官方始终用默认提示词全文,含 CTF,不读规则集。
* 红队开了规则集就只用规则集,不带默认提示词。
* 红队没开规则集时用默认提示词,去掉 CTF。操作说明由组装接在后面。
* 禁区说明不进模型。
*/
export function resolveModeInject(dshHome, redteam) {
const prompt = normalizeOverride(overrideFileText(dshHome));
const prompt = promptOrDefault(dshHome);
if (!redteam) return modePromptText(prompt, false);
const rule = normalizeOverride(activeRuleText(dshHome));
if (!redteam) return rule || prompt;
const parts = [];
if (prompt) parts.push(prompt);
if (rule && rule !== prompt) parts.push(rule);
return parts.join("\n\n");
if (rule) return modePromptText(rule, true);
return modePromptText(prompt, true);
}
export async function activateRule(dshHome, id) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-purge",
"version": "1.1.41",
"version": "1.1.44",
"description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,内嵌演练台;不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐",
"type": "module",
"main": "lib/index.js",
+56
View File
@@ -1,3 +1,59 @@
# 1.1.44
## 中文
- 版本升级到 1.1.44。
- 官方桌面解开 `app.asar` 时先写到旁边的目录,解开完成才换上 `resources/app`。目录里已经有宿主之后只改这些文件。同一份归档又出现时只把它挪开。归档的大小或时间变了,或目录不在了,才再解一次。解包卡住或补丁没写完,把上一份放回去,升级标记留到下次再试。
- 回退上一轮只撤掉最后一条已经发出的消息和它的回复,更早的轮次留在对话里,也从模型请求里拿掉。连续回退后留下的空标记不再进下一轮请求,下一句按新消息发。
- 可编辑提示词整份放在系统提示最前,同一份正文不再拼第二遍。每一步用当前这一份替换第一条系统提示。
- deepseek.com 的系统提示固定走 system,思维链照旧发送。
- 地区拦截只看这次任务里的目标。自己的服务器只认名单上的那一个地址或主机名。禁止句写上之后才结束这一轮。
- 官方始终用带 CTF 的默认提示词。红队开了规则集就只用规则集;否则用去掉 CTF 的默认提示词,再接红队操作。子代理跟主会话吃同一份。磁盘没有提示词时启动就用默认那份,不必先点保存。
## English
- Version 1.1.44.
- Unpacking `app.asar` writes beside `resources/app` and swaps in only after the unpack finishes. Once that directory is usable, later starts only edit those files. The same archive showing up again is moved aside. A new size or mtime, or a missing directory, is unpacked once. If unpacking sticks or that patch round does not finish, the previous directory is put back and the upgrade marker stays for the next start.
- Rewinding the previous round removes only that sent message and its reply. Earlier rounds stay on screen and leave the next model request. Leftover rewind markers stay off the next model request, so the next send is a new message.
- The editable prompt is placed once at the front of the system prompt. Each step replaces the first system prompt with that current text.
- Instructions for deepseek.com stay on the system role. Thinking is still sent.
- The region check looks only at this task's target. An own server is allowed only when that exact address or hostname is on the list. The turn ends after the denial sentence is written.
- Official mode always uses the default prompt, including CTF. Red team uses only the active rule set, or the default prompt without CTF followed by the red team steps. Subagents receive the same inject as the main session. If the prompt file is empty, startup uses the bundled default without requiring Save.
# 1.1.43
## 中文
- 版本升级到 1.1.43。
- 还没定位到本机 Harness 时,不再把每一条显示成跳过,分组计数也不再把跳过算成已完成。
- 补丁列表补齐到全部 52 条,总数和分组对得上。
- 启动时如果暂时找不到宿主目录,不再把这个空结果缓存住。
## English
- Version 1.1.43.
- Before this install is located, rows are no longer shown as skipped, and a skip no longer counts as done in the group total.
- The patch list now includes all 52 items, so the total matches the groups.
- A miss while looking up the host directory is not cached for the rest of the process.
# 1.1.42
## 中文
- 版本升级到 1.1.42。
- 清洗页提示词下面可以登记自己的服务器:每行一个 IP 或完整主机名,点保存名单。说明里写了步骤,并附了截图。
- 新对话把提示词放在系统提示最前。面板改为白墨玻璃,两种主题都能看清字。
- 补丁进度只计已应用的项。网页身份那条在后一条改写句子之后,仍显示已应用。
- 补上 0.1.x 的入口针。已经打过的 0.2.0 不会被重写。
## English
- Version 1.1.42.
- Under Prompt on the Clean page, register your own server: one IP or exact hostname per line, then Save list. The docs include the steps and a screenshot.
- New chats place the prompt at the front of the system prompt. The dock is frosted glass, and both the light and ink themes stay readable.
- The patch count includes only applied items. The web-surface identity row stays applied after the later sentence rewrite.
- Needles for 0.1.x entry points were added. An already patched 0.2.0 host is not rewritten.
# 1.1.41
## 中文
+3 -1
View File
@@ -3,5 +3,7 @@
"docs/preview/dock-auth.png",
"docs/preview/dock-drill.png",
"docs/preview/settings.png",
"docs/preview/rules.png"
"docs/preview/rules.png",
"docs/preview/own-servers.png",
"docs/preview/own-servers-en.png"
]