From fedda6d338d7960a3a7c7c57364e7ccb62121fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= <188421097+HunYiSage@users.noreply.github.com> Date: Sun, 20 Sep 2026 11:00:02 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.10=EF=BC=8C?= =?UTF-8?q?=E7=A9=BA=E6=8F=90=E7=A4=BA=E8=AF=8D=E6=8B=A6=E6=88=AA=E5=B9=B6?= =?UTF-8?q?=E4=BF=AE=E9=A6=96=E8=BD=AE=E6=B3=A8=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- README.md | 19 ++++-- README.zh-CN.md | 19 ++++-- client.js | 169 ++++++++++++++++++++++++++++++++++++----------- cordis.patch.yml | 2 +- lib/core.js | 50 +++++++++----- lib/identity.js | 49 ++++++++------ lib/index.js | 143 ++++++++++++++++++++------------------- lib/rules.js | 56 ++++++++++------ package.json | 2 +- 9 files changed, 334 insertions(+), 175 deletions(-) diff --git a/README.md b/README.md index f17a438..ee045de 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

⚔️ DeepSeek Harness cybersecurity red-team tool (dsh-purge)

-

Version 1.1.9

+

Version 1.1.10

Local official DeepSeek Harness cybersecurity red-team plugin: evaluate and harden host safety policy in a controlled local install; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐ @@ -39,7 +39,7 @@ If this project helps you, send it over — I'm out here asking~ | Asset | Address | |---|---| -| **USDT (TRC20)** | `TScRVxQsUhCRh5jApLVxwFdWcJ1S2hKWRf` | +| **USDT (TRC20)** | `TV5ajPkRD8RH623Dx9mqvYZVNN8nPGRKid` | | **Solana** | `6x16GhRgLVpKFFXaU1seKNdx2rypspSJTL4dbpt6Xpwk` | | **Ethereum** | `0xB68BD60C0e8c519513B7DF9bB147696815423B3E` | | **Bitcoin** | `bc1qu70yxkrtwnymt8ryluz9x8y8hqzune5340npht` | @@ -244,13 +244,13 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv

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

🔗 **Raw protocol URL:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.9&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.10&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz ``` **Web trigger example:** @@ -263,7 +263,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.9', + version: '1.1.10', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -282,7 +282,7 @@ export function installDshPurgeToDesktop() { **HTML link:** ```html - + 🚀 Install in desktop client ``` @@ -293,7 +293,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | Plugin id | | name | `dsh-purge` | Display name | -| version | `1.1.9` | Semver | +| version | `1.1.10` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub source archive | @@ -745,6 +745,11 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change ## Changelog +### 1.1.10 + +- Saving or applying with both the prompt and the rule set empty is blocked and shows a dialog +- First-turn inject is complete; later turns no longer pin the previous full system prompt + ### 1.1.9 - Removed the default prompt from the repository diff --git a/README.zh-CN.md b/README.zh-CN.md index 9b89307..07fd11a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@

⚔️ DeepSeek Harness 网络安全红队工具(dsh-purge)

-

Version 1.1.9

+

Version 1.1.10

本机官方 DeepSeek Harness 网络安全红队评测插件:在受控本机环境评测并加固宿主安全策略,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐ @@ -36,7 +36,7 @@ | 币种 | 地址 | |---|---| -| **USDT(TRC20)** | `TScRVxQsUhCRh5jApLVxwFdWcJ1S2hKWRf` | +| **USDT(TRC20)** | `TV5ajPkRD8RH623Dx9mqvYZVNN8nPGRKid` | | **Solana** | `6x16GhRgLVpKFFXaU1seKNdx2rypspSJTL4dbpt6Xpwk` | | **Ethereum** | `0xB68BD60C0e8c519513B7DF9bB147696815423B3E` | | **Bitcoin** | `bc1qu70yxkrtwnymt8ryluz9x8y8hqzune5340npht` | @@ -241,13 +241,13 @@ dsh plugin --profile default add https://github.com/YuJunZhiXue/dsh-purge/archiv

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

🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.9&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.10&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz ``` **网页端(前端)触发代码示例:** @@ -260,7 +260,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.9', + version: '1.1.10', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -279,7 +279,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -290,7 +290,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.9` | 语义化版本号 | +| version | `1.1.10` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub 源码包地址 | @@ -732,6 +732,11 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt ## 更新记录 +### 1.1.10 + +- 提示词和规则集都空时不能保存或应用,弹窗要求先添加提示词 +- 第一轮完整注入;不再钉上一轮整篇系统提示,避免来回追加 + ### 1.1.9 - 将提示词从仓库中下线 diff --git a/client.js b/client.js index 103ebe6..2cde99d 100644 --- a/client.js +++ b/client.js @@ -73,6 +73,35 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { } finally { clearTimeout(timer); } } + function promptBoxEmpty(text) { + return !String(text || "").trim(); + } + + function responseNeedsPrompt(d) { + return Boolean(d && (d.needPrompt || d.injectSource === "none")); + } + + function warnNeedPrompt(d, tr) { + if (!responseNeedsPrompt(d)) return false; + window.alert(tr("need.prompt")); + return true; + } + + function activeRuleHasBody(st) { + if (!st || !st.ok) return false; + const active = st.rules && st.rules.find((r) => r.id === st.active); + return Boolean(active && active.size > 0); + } + + async function bothInjectEmpty(overrideText) { + if (!promptBoxEmpty(overrideText)) return false; + try { + return !activeRuleHasBody(await rulesApi("status")); + } catch { + return true; + } + } + function rulesApi(op, extra) { return apiJson("/dsh-purge/rules", { method: "POST", @@ -110,7 +139,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "apply.hint": "待应用=原文还在。跳过=没装或官方已改写,再点也不会变。", "warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。", "warn.noRoot.desktop": "未定位到当前桌面应用里的 @deepseek-ai。请退出托盘后重新打开 DSH Desktop.exe,再在桌面端设置页点「应用」。安装目录不限盘符。", - "warn.noInject": "未自行改过时始终使用插件内置默认提示词。保存不同内容后才会换成你的;恢复默认可改回去。", + "warn.noInject": "提示词优先;为空则注入当前启用的规则集。两边都空会提示必须添加。", + "need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。", "btn.restoreInject": "恢复默认", "saved.restoreInject": "已填入默认提示词,点保存写入", "skip": "跳过", @@ -280,7 +310,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "apply.hint": "Pending = original text still present. Skipped = missing or already rewritten.", "warn.noRoot": "Could not find this host’s @deepseek-ai tree, so Apply will not patch anything. Fully quit and reopen this host, then Apply here. Desktop may live on any drive; do not use official dsh to purge Desktop.", "warn.noRoot.desktop": "Could not find @deepseek-ai inside this desktop app. Quit the tray, reopen DSH Desktop.exe, then Apply on the desktop Settings page. The install folder can be on any drive.", - "warn.noInject": "Until you save a different prompt, the plugin keeps its built-in default. Restore default to go back.", + "warn.noInject": "The prompt box wins. If it is empty, the enabled rule set is injected. 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.", "skip": "Skipped", @@ -732,6 +763,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const [updateNotice, setUpdateNotice] = useState({ kind: "idle", text: "" }); const [updateInfo, setUpdateInfo] = useState(null); const [canApplyUpdate, setCanApplyUpdate] = useState(false); + const actionTicket = useRef(0); const updateErrorText = (tr, e) => { const msg = String((e && e.message) || e || ""); @@ -797,8 +829,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { if (d && d.ok) { const packed = typeof d.defaultContent === "string" ? d.defaultContent : ""; if (packed) setDefaultOverride(packed); - const shown = String(d.content || packed || "").trim() ? (d.content || packed) : packed; - setOverride(shown); + setOverride(typeof d.content === "string" ? d.content : packed); setOverrideLoaded(true); } else setNotice({ kind: "error", text: tr("err.override", { error: (d && d.error) || "" }) }); @@ -808,21 +839,41 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { useEffect(() => { loadAll(); }, [loadAll]); - const doAction = useCallback((action, actionKey) => { - setPatchBusy(true); + const rejectNeedPrompt = useCallback((tr) => { setAskRestart(false); - setNotice({ kind: "idle", text: "" }); + setNotice({ kind: "error", text: tr("need.prompt") }); + setTimeout(() => window.alert(tr("need.prompt")), 0); + }, []); + + const doAction = useCallback((action, actionKey) => { const tr = tRef.current; const label = tr(actionKey); - fetch("/dsh-purge/" + action, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }) - .then((r) => r.json()) - .then((d) => { - if (d.ok) { + const ticket = ++actionTicket.current; + const run = () => { + setPatchBusy(true); + setAskRestart(false); + setNotice({ kind: "idle", text: "" }); + fetch("/dsh-purge/" + action, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(action === "apply" ? { content: override } : {}), + }) + .then((r) => r.json()) + .then((d) => { + if (ticket !== actionTicket.current) return; + const applyEmptyBlocked = action === "apply" && promptBoxEmpty(override) && (!d || d.injectSource !== "rule"); + if (responseNeedsPrompt(d) || applyEmptyBlocked) { + rejectNeedPrompt(tr); + return; + } + if (!d.ok) { + setNotice({ kind: "error", text: tr("err.action", { action: label, error: d.error || "" }) }); + return; + } if (action === "apply") { if (typeof d.defaultContent === "string") setDefaultOverride(d.defaultContent); - const shown = d.override_content || d.defaultContent; - if (typeof shown === "string" && shown) { - setOverride(shown); + if (typeof d.override_content === "string") { + setOverride(d.override_content); setOverrideLoaded(true); } } @@ -858,32 +909,68 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { setNotice({ kind: "ok", text: tr("ok.done") }); loadAll(); if (action === "apply") setAskRestart(true); - } else { - setNotice({ kind: "error", text: tr("err.action", { action: label, error: d.error || "" }) }); - } - }) - .catch((e) => setNotice({ kind: "error", text: tr("err.action", { action: label, error: e.message }) })) - .finally(() => setPatchBusy(false)); - }, [loadAll]); + }) + .catch((e) => { + if (ticket !== actionTicket.current) return; + setNotice({ kind: "error", text: tr("err.action", { action: label, error: e.message }) }); + }) + .finally(() => { + if (ticket === actionTicket.current) setPatchBusy(false); + }); + }; + if (action !== "apply") { + run(); + return; + } + bothInjectEmpty(override).then((empty) => { + if (ticket !== actionTicket.current) return; + if (empty) { + rejectNeedPrompt(tr); + return; + } + run(); + }); + }, [loadAll, override, rejectNeedPrompt]); const saveOverride = useCallback(() => { - setPatchBusy(true); - setNotice({ kind: "idle", text: "" }); - fetch("/dsh-purge/override", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ content: override }), - }) - .then((r) => r.json()) - .then((d) => { - if (d.ok && typeof d.content === "string") setOverride(d.content); - setNotice(d.ok - ? { kind: "ok", text: t("saved.override") } - : { kind: "error", text: t("err.save", { error: d.error || "" }) }); + const tr = t; + const ticket = ++actionTicket.current; + const go = () => { + setPatchBusy(true); + setAskRestart(false); + setNotice({ kind: "idle", text: "" }); + fetch("/dsh-purge/override", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ content: override }), }) - .catch((e) => setNotice({ kind: "error", text: t("err.save", { error: e.message }) })) - .finally(() => setPatchBusy(false)); - }, [override, t]); + .then((r) => r.json()) + .then((d) => { + if (ticket !== actionTicket.current) return; + if (!d.ok || responseNeedsPrompt(d) || (promptBoxEmpty(override) && d.injectSource !== "rule")) { + rejectNeedPrompt(tr); + return; + } + if (typeof d.content === "string") setOverride(d.content); + setNotice({ kind: "ok", text: t("saved.override") }); + }) + .catch((e) => { + if (ticket !== actionTicket.current) return; + setNotice({ kind: "error", text: t("err.save", { error: e.message }) }); + }) + .finally(() => { + if (ticket === actionTicket.current) setPatchBusy(false); + }); + }; + bothInjectEmpty(override).then((empty) => { + if (ticket !== actionTicket.current) return; + if (empty) { + rejectNeedPrompt(tr); + return; + } + go(); + }); + }, [override, t, rejectNeedPrompt]); const restoreOverride = useCallback(() => { if (!defaultOverride) return; @@ -1056,6 +1143,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { spellCheck: false, placeholder: "", }), + promptBoxEmpty(override) ? h("p", { + className: "dshp-hint", + style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 }, + }, t("need.prompt")) : null, ); } @@ -1105,9 +1196,11 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .then((d) => { if (d && d.ok) { setNotice({ kind: "ok", text: t("ok.done") }); + if (action === "save" || action === "activate") warnNeedPrompt(d, t); loadStatus(); if (after) after(); } else { + warnNeedPrompt(d, t); setNotice({ kind: "error", text: t("err.action", { error: (d && d.error) || "" }) }); } }) @@ -1123,7 +1216,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { setEditId(id); setEditName(d.name || id); setEditTarget(d.target || "AGENTS.md"); - setContent(d.content || ""); + setContent(typeof d.content === "string" ? d.content : ""); } else setNotice({ kind: "error", text: t("err.read", { error: d.error || "" }) }); }) .catch((e) => setNotice({ kind: "error", text: t("err.read", { error: e.message }) })) diff --git a/cordis.patch.yml b/cordis.patch.yml index 0c1bac0..eb89673 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -11,7 +11,7 @@ autoApplyOnStart: true autoUpdateOnStart: true autoRevertOnMissing: false - injectOnce: true + injectOnce: false stripMnemon: true verbose: false postPrompt: "" diff --git a/lib/core.js b/lib/core.js index 3ed2601..77e8ac1 100644 --- a/lib/core.js +++ b/lib/core.js @@ -2975,11 +2975,11 @@ const NEW_TOOL_PATCHES = [ "\t\t\t...transformed,\n" + "\t\t\tsections: completeSection === void 0 ? transformed.sections : (function (complete, assembled) {\n" + "\t\t\t\tconst sections = assembled.sections || [];\n" + - "\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\").trim()).filter(Boolean).join(\"\\n\\n\");\n" + + "\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\")).filter((t) => t.length > 0).join(\"\\n\\n\");\n" + "\t\t\t\tconst folded = sections.find((s) => s && s.name === complete.name);\n" + "\t\t\t\tconst base = folded && typeof folded.text === \"string\" ? { ...complete, text: folded.text } : { ...complete };\n" + "\t\t\t\tif (!inject) return [base];\n" + - "\t\t\t\tif (String(base.text || \"\").includes(inject.slice(0, Math.min(80, inject.length)))) return [base];\n" + + "\t\t\t\tif (String(base.text || \"\").includes(inject)) return [base];\n" + "\t\t\t\treturn [{ ...base, text: inject + \"\\n\\n\" + base.text }]; // [dsh-purge] complete prompt keeps inject\n" + "\t\t\t})(completeSection, transformed),\n" + "\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" + @@ -4249,16 +4249,20 @@ export function overrideStatePath(dshHome) { return path.join(dshHome, "dsh-purge", "override-state.json"); } -export async function readOverrideState(dshHome) { +export function readOverrideStateSync(dshHome) { const fp = overrideStatePath(dshHome); try { - const raw = JSON.parse(await fsp.readFile(fp, "utf8")); + const raw = JSON.parse(fs.readFileSync(fp, "utf8")); return raw && typeof raw === "object" ? raw : {}; } catch { return {}; } } +export async function readOverrideState(dshHome) { + return readOverrideStateSync(dshHome); +} + export async function writeOverrideState(dshHome, state) { const fp = overrideStatePath(dshHome); await fsp.mkdir(path.dirname(fp), { recursive: true }); @@ -4275,6 +4279,9 @@ export async function markOverrideCustomized(dshHome, customized, text) { } export async function isUserCustomizedOverride(dshHome) { + const state = await readOverrideState(dshHome); + if (state.customized === true) return true; + if (state.customized === false) return false; const fp = findOverrideFile(dshHome); let disk = ""; if (fs.existsSync(fp)) { @@ -4286,9 +4293,6 @@ export async function isUserCustomizedOverride(dshHome) { } if (!normalizeOverride(disk)) return false; if (hashOverride(disk) === defaultOverrideHash()) return false; - const state = await readOverrideState(dshHome); - if (state.customized === false) return false; - if (state.customized === true) return true; return true; } @@ -4319,11 +4323,11 @@ export async function readOverrideForUi(dshHome) { } } const customized = await isUserCustomizedOverride(dshHome); - const show = customized && normalizeOverride(disk) ? disk : defaultContent; + const show = customized ? disk : defaultContent; return { path: fp, exists, - empty: !normalizeOverride(disk), + empty: !normalizeOverride(show), customized, usingDefault: !customized, content: show, @@ -4331,6 +4335,24 @@ export async function readOverrideForUi(dshHome) { }; } +/** 插件加载时同步落下默认提示词,避免第一轮 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"); + } catch { + disk = ""; + } + if (normalizeOverride(disk)) return "exists"; + const bundled = defaultOverrideText(); + if (!normalizeOverride(bundled)) return fs.existsSync(fp) ? "empty" : "missing"; + fs.writeFileSync(fp, bundled, "utf8"); + return "wrote"; +} + export async function installOverride(dshHome, force = false) { const fp = findOverrideFile(dshHome); await fsp.mkdir(dshHome, { recursive: true }); @@ -4345,14 +4367,12 @@ export async function installOverride(dshHome, force = false) { export async function saveOverrideContent(dshHome, content) { const bundled = defaultOverrideText(); const incoming = typeof content === "string" ? content : ""; - const customized = Boolean(normalizeOverride(incoming)) - && normalizeOverride(incoming) !== normalizeOverride(bundled); - const toWrite = customized ? incoming : bundled; + const customized = normalizeOverride(incoming) !== normalizeOverride(bundled); const fp = findOverrideFile(dshHome); await fsp.mkdir(dshHome, { recursive: true }); - await fsp.writeFile(fp, toWrite, "utf8"); - await markOverrideCustomized(dshHome, customized, toWrite); - return { path: fp, customized, content: toWrite }; + await fsp.writeFile(fp, incoming, "utf8"); + await markOverrideCustomized(dshHome, customized, incoming); + return { path: fp, customized, content: incoming, defaultContent: bundled }; } export async function ensureOverrideContent(dshHome, force = false) { diff --git a/lib/identity.js b/lib/identity.js index 3df1980..c7ed2d6 100644 --- a/lib/identity.js +++ b/lib/identity.js @@ -90,10 +90,20 @@ function stripHarnessPersona(text) { } function collectInjectText(purgeSections, fallbackText) { + const fallback = typeof fallbackText === "string" ? fallbackText : ""; + if (fallback) return fallback; const main = purgeSections.find((section) => section.name === "dsh-purge"); - const fromMain = String(main?.text || "").trim(); - if (fromMain) return fromMain; - return typeof fallbackText === "string" ? fallbackText.trim() : ""; + return String(main?.text || ""); +} + +function assemblyHasExactInject(sections, inject) { + if (!inject) return true; + return sections.some((section) => String(section?.text || "").includes(inject)); +} + +function ensureFullInject(sections, inject) { + if (!inject || assemblyHasExactInject(sections, inject)) return sections; + return [{ name: "dsh-purge", text: inject, order: -10000 }, ...sections]; } function stripIdentityPrefix(text) { @@ -135,13 +145,13 @@ function messageText(message) { export function existingSystemPrompt(context) { const events = eventList(context?.agent?.session || context?.session); - let latest = ""; + const texts = []; for (const event of events) { if (event?.type !== "system/message") continue; const text = messageText(event.data?.message || event.data).trim(); - if (text) latest = text; + if (text) texts.push(text); } - return latest; + return texts.join("\n\n"); } export function isFirstConversationTurn(context) { @@ -162,13 +172,13 @@ export function isFirstConversationTurn(context) { export function promptAlreadyInjected(existing, injectText) { const inject = String(injectText || "").trim(); if (!inject) return false; - return String(existing || "").includes(inject.slice(0, Math.min(80, inject.length))); + return String(existing || "").includes(inject); } -export function shouldInjectPrompt(context, injectOnce = true, injectText = "") { - if (injectOnce === false) return true; - if (isFirstConversationTurn(context)) return true; - return !promptAlreadyInjected(existingSystemPrompt(context), injectText); +export function shouldInjectPrompt(_context, _injectOnce = true, _injectText = "") { + // 0.1.5 in-history:渲染少了注入就会再追加一条 system/message。 + // 用「最后一条是否含注入」决定本步掏空注入,会 A/B 死循环。每步都必须留下完整注入。 + return true; } export function isMnemonPluginMessage(message) { @@ -199,7 +209,7 @@ function normalizeRewriteOptions(fallbackInject, options) { // 0.1.5 优先写入 persona-prefix;无 prefix 时写入 legacy persona。 function foldInjectIntoPersona(sections, injectText) { - const inject = typeof injectText === "string" ? injectText.trim() : ""; + const inject = typeof injectText === "string" ? injectText : ""; const names = sections.map((s) => String(s?.name || "")); const hasPrefix = names.some((n) => PERSONA_PREFIX_NAMES.has(n)); let folded = false; @@ -207,16 +217,16 @@ function foldInjectIntoPersona(sections, injectText) { const name = String(section?.name || ""); if (!isPersonaFoldTarget(name, hasPrefix)) return section; folded = true; - const prior = stripIdentityPrefix(String(section.text || "").trim()); + const prior = stripIdentityPrefix(String(section.text || "")); if (!inject) return { ...section, text: prior }; - if (prior.includes(inject.slice(0, Math.min(80, inject.length)))) { - return { ...section, text: prior }; - } + if (prior.includes(inject)) return { ...section, text: prior }; return { ...section, text: prior ? `${inject}\n\n${prior}` : inject }; }); if (folded) return out; if (!inject) return out; - return [{ name: "deployment:persona-prefix", text: inject }, ...out]; + const orders = sections.map((s) => s?.order).filter((n) => Number.isFinite(n)); + const order = orders.length ? Math.min(0, ...orders) : 0; + return [{ name: "deployment:persona-prefix", text: inject, order }, ...out]; } export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) { @@ -233,18 +243,17 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options = next.text = stripHarnessPersona(next.text); } if (String(next.name).startsWith("dsh-purge")) { - if (!opts.fallbackInject) continue; purge.push(next); } else { rest.push(next); } } - const injectText = opts.fallbackInject ? collectInjectText(purge, opts.fallbackInject) : ""; + const injectText = collectInjectText(purge, opts.fallbackInject); const folded = foldInjectIntoPersona(rest, injectText); const extras = opts.dropPurgeAfterFold ? purge.filter((section) => section.name !== "dsh-purge") : purge; - assembled.sections = [...folded, ...extras]; + assembled.sections = ensureFullInject([...folded, ...extras], injectText); return assembled; } diff --git a/lib/index.js b/lib/index.js index 918750b..ead4f33 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,6 +1,5 @@ import fs from "node:fs"; import { promises as fsp } from "node:fs"; -import { AsyncLocalStorage } from "node:async_hooks"; import * as core from "./core.js"; import * as hostctl from "./host.js"; import * as rules from "./rules.js"; @@ -9,7 +8,6 @@ import { GLOBAL_PROMPT_ORDER, isMnemonPluginMessage, rewritePromptAssembly, - shouldInjectPrompt, } from "./identity.js"; import * as rewind from "./rewind.js"; import * as continueRetry from "./continue-retry.js"; @@ -24,7 +22,7 @@ const DEFAULTS = { autoApplyOnStart: true, autoUpdateOnStart: true, autoRevertOnMissing: false, - injectOnce: true, + injectOnce: false, stripMnemon: true, postPrompt: "", postPromptOrder: 5100, @@ -138,43 +136,39 @@ function renderStatus(state) { return out.join("\n"); } -function readInjectFile(injectFile) { - try { - if (!injectFile || !fs.existsSync(injectFile)) return ""; - return fs.readFileSync(injectFile, "utf8").trim(); - } catch { - return ""; - } -} - -const assembleState = new AsyncLocalStorage(); - function injectAllowedNow(config) { - if (config.enabled === false) return false; - const state = assembleState.getStore(); - return !state || state.allow !== false; + return config.enabled !== false; } -export function registerPromptSections(ctx, config, injectFile) { +function injectSnapshot(dshHome = core.findDshHome()) { + const resolved = rules.resolveInjectText(dshHome); + return { + injectSource: resolved.source, + injectRuleId: resolved.ruleId, + needPrompt: resolved.source === "none", + }; +} + +/** 以设置页文本框为准;空框且没有启用中的规则集则必须补提示词。 */ +function injectSnapshotFromBox(dshHome, boxText) { + if (typeof boxText !== "string") return injectSnapshot(dshHome); + if (core.normalizeOverride(boxText)) { + return { injectSource: "prompt", injectRuleId: null, needPrompt: false }; + } + const ruleId = rules.activeRuleId(dshHome); + if (core.normalizeOverride(rules.activeRuleText(dshHome))) { + return { injectSource: "rule", injectRuleId: ruleId, needPrompt: false }; + } + return { injectSource: "none", injectRuleId: ruleId, needPrompt: true }; +} + +export function registerPromptSections(ctx, config, _injectFile) { ctx.systemPrompt.section({ name: "dsh-purge", order: GLOBAL_PROMPT_ORDER, text: () => { if (!injectAllowedNow(config)) return ""; - return readInjectFile(injectFile); - }, - }); - - ctx.systemPrompt.section({ - name: "dsh-purge:rules", - order: GLOBAL_PROMPT_ORDER + 1, - text: () => { - if (!injectAllowedNow(config)) return ""; - try { - return rules.activeRuleText(core.findDshHome()); - } catch { - return ""; - } + return rules.resolveInjectText(core.findDshHome()).text; }, }); @@ -190,26 +184,8 @@ export function registerPromptSections(ctx, config, injectFile) { }); } -const INJECT_FALLBACK_MAX_BYTES = 512 * 1024; - function readInjectFallback() { - try { - const fp = core.findOverrideFile(core.findDshHome()); - if (!fp || !fs.existsSync(fp)) return ""; - const st = fs.statSync(fp); - if (!st.isFile() || st.size <= 0) return ""; - if (st.size <= INJECT_FALLBACK_MAX_BYTES) return fs.readFileSync(fp, "utf8"); - const fd = fs.openSync(fp, "r"); - try { - const buf = Buffer.alloc(INJECT_FALLBACK_MAX_BYTES); - const n = fs.readSync(fd, buf, 0, INJECT_FALLBACK_MAX_BYTES, 0); - return buf.toString("utf8", 0, n); - } finally { - fs.closeSync(fd); - } - } catch { - return ""; - } + return rules.resolveInjectText(core.findDshHome()).text; } function installMnemonMessageStrip(ctx, config = {}) { @@ -238,16 +214,14 @@ function installIdentityOverride(ctx, config = {}) { if (typeof ctx.on !== "function") return; if (ctx.__dshPurgeAssembleHook) return; ctx.__dshPurgeAssembleHook = true; - const hook = async (_assembly, context, next) => { - const inject = config.enabled === false ? "" : readInjectFallback(); - const allow = config.enabled !== false && shouldInjectPrompt(context, config.injectOnce !== false, inject); - return assembleState.run({ allow }, async () => { - const assembled = typeof next === "function" ? await next() : _assembly; - return rewritePromptAssembly(assembled, { - fallbackInject: allow ? inject : "", - dropMnemon: config.stripMnemon !== false, - dropPurgeAfterFold: true, - }); + const hook = async (_assembly, _context, next) => { + const assembled = typeof next === "function" ? await next() : _assembly; + const enabled = config.enabled !== false; + const inject = enabled ? readInjectFallback() : ""; + return rewritePromptAssembly(assembled, { + fallbackInject: inject, + dropMnemon: config.stripMnemon !== false, + dropPurgeAfterFold: true, }); }; // 只挂一次:挂多次会让同一轮 assemble 折两遍,UI 也会显示两次注入。 @@ -559,6 +533,11 @@ export function apply(ctx, config) { } }); + try { + core.seedOverrideSync(core.findDshHome()); + } catch (e) { + console.warn("[dsh-purge] seed override error:", String(e)); + } installIdentityOverride(ctx, cfg); installMnemonMessageStrip(ctx, cfg); const injectFile = core.findOverrideFile(core.findDshHome()); @@ -948,9 +927,24 @@ function installWebServer(ctx, cfg) { sendJson(response, 500, { ok: false, error: core.missingAiBaseMessage() }); return; } + const body = await readJsonBody(request); + const ui = await core.readOverrideForUi(state.dsh_home); + const boxText = typeof body?.content === "string" ? body.content : ui.content; + const snap = injectSnapshotFromBox(state.dsh_home, boxText); + if (snap.needPrompt) { + sendJson(response, 400, { + ok: false, + needPrompt: true, + error: "提示词和规则集都是空的,必须先添加提示词", + override_content: boxText, + defaultContent: ui.defaultContent, + ...snap, + }); + return; + } await core.backupAll(state.ai_base); const report = await core.applyPatches(state.ai_base); - const override = await core.ensureOverrideContent(state.dsh_home, false); + const override = await core.readOverrideForUi(state.dsh_home); const shim = await core.patchAllShims(); const flash = core.silenceCmdFlash(state.ai_base); const summary = core.summarizeApplyReport(report); @@ -968,6 +962,8 @@ function installWebServer(ctx, cfg) { })), report: report.map((r) => ({ id: r.patch_id, name: r.name, status: r.status })), override_content: override.content, + defaultContent: override.defaultContent, + ...injectSnapshot(state.dsh_home), override_path: override.path, override_installed: override.installed, shim, @@ -1038,8 +1034,9 @@ function installWebServer(ctx, cfg) { handler: async (request, response) => { if (request.method === "GET") { try { - const ui = await core.ensureOverrideContent(core.findDshHome(), false); - sendJson(response, 200, { ok: true, ...ui }); + const home = core.findDshHome(); + const ui = await core.readOverrideForUi(home); + sendJson(response, 200, { ok: true, ...ui, ...injectSnapshot(home) }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } @@ -1053,8 +1050,19 @@ function installWebServer(ctx, cfg) { sendJson(response, 400, { ok: false, error: "content must be a string" }); return; } - const saved = await core.saveOverrideContent(core.findDshHome(), content); - sendJson(response, 200, { ok: true, ...saved }); + const home = core.findDshHome(); + const snap = injectSnapshotFromBox(home, content); + if (snap.needPrompt) { + sendJson(response, 400, { + ok: false, + error: "提示词和规则集都是空的,必须先添加提示词", + content, + ...snap, + }); + return; + } + const saved = await core.saveOverrideContent(home, content); + sendJson(response, 200, { ok: true, ...saved, ...injectSnapshot(home) }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } @@ -1121,7 +1129,7 @@ async function handleRulesOp(op, body, queryId) { name: typeof body?.name === "string" ? body.name : undefined, target: typeof body?.target === "string" ? body.target : undefined, }); - return { ok: true, id }; + return { ok: true, id, ...injectSnapshot(dshHome) }; } if (op === "activate") { if (!rules.validRuleId(id)) return { status: 400, ok: false, error: "invalid id" }; @@ -1133,6 +1141,7 @@ async function handleRulesOp(op, body, queryId) { target: meta.target, agents_path: rules.targetPath(dshHome, meta.target), note: "已写入目标文件并注入 systemPrompt,新会话生效", + ...injectSnapshot(dshHome), }; } if (op === "delete") { diff --git a/lib/rules.js b/lib/rules.js index 4ab82b3..54bd285 100644 --- a/lib/rules.js +++ b/lib/rules.js @@ -1,7 +1,7 @@ import fs from "node:fs"; import { promises as fsp } from "node:fs"; import path from "node:path"; -import { findDshHome } from "./core.js"; +import { findDshHome, findOverrideFile, normalizeOverride } from "./core.js"; const RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; const MAX_RULE_BYTES = 256 * 1024; @@ -151,17 +151,46 @@ export async function setActive(dshHome, id) { await fsp.writeFile(stateFile(dshHome), JSON.stringify({ active: id }, null, 2), "utf8"); } -export function activeRuleText(dshHome) { +export function activeRuleId(dshHome) { try { const parsed = JSON.parse(fs.readFileSync(stateFile(dshHome), "utf8")); const id = parsed?.active; - if (!validRuleId(id)) return ""; - return fs.readFileSync(rulePath(dshHome, id), "utf8").trim(); + return validRuleId(id) ? id : null; + } catch { + return null; + } +} + +export function activeRuleText(dshHome) { + const id = activeRuleId(dshHome); + if (!id) return ""; + try { + return fs.readFileSync(rulePath(dshHome, id), "utf8"); } catch { return ""; } } +export function overrideFileText(dshHome) { + const fp = findOverrideFile(dshHome); + try { + if (!fp || !fs.existsSync(fp)) return ""; + return fs.readFileSync(fp, "utf8"); + } catch { + return ""; + } +} + +/** 提示词优先;为空则用当前启用的规则集。两边都空则不注入。 */ +export function resolveInjectText(dshHome) { + const prompt = overrideFileText(dshHome); + if (normalizeOverride(prompt)) return { text: prompt, source: "prompt", ruleId: null }; + const ruleId = activeRuleId(dshHome); + const rule = activeRuleText(dshHome); + if (normalizeOverride(rule)) return { text: rule, source: "rule", ruleId }; + return { text: "", source: "none", ruleId }; +} + export async function activateRule(dshHome, id) { const content = await readRule(dshHome, id); if (content === null) throw new Error(`rule not found: ${id}`); @@ -181,21 +210,7 @@ export async function ensureInitialState(dshHome) { } active = null; } - if (active !== null) return { active }; - if (listed.length > 0) return { active: null }; - for (const target of RULE_TARGETS) { - try { - const content = await fsp.readFile(targetPath(dshHome, target), "utf8"); - if (content.trim().length > 0) { - await saveRule(dshHome, "default", content, { name: "默认规则", target }); - await setActive(dshHome, "default"); - return { active: "default", imported: target }; - } - } catch { - // 当前 target 文件不存在,试下一个 - } - } - return { active: null }; + return { active }; } export async function resetToOriginal(dshHome) { @@ -243,9 +258,12 @@ export async function rulesStatus(dshHome) { } catch { } } + const inject = resolveInjectText(dshHome); return { rules: listed, active, + injectSource: inject.source, + injectRuleId: inject.ruleId, active_target, agents_exists, agents_synced, diff --git a/package.json b/package.json index 49c4227..5743b76 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.9", + "version": "1.1.10", "description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐", "type": "module", "main": "lib/index.js",