diff --git a/README.md b/README.md index b24cbac..888395d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@
Version 1.1.65
+Version 1.1.66
DeepSeek Harness jailbreak: every model, swap prompts per model. Default prompt for 小码酱. Please star ⭐ If you build on this, see Attribution required. @@ -134,7 +134,7 @@ Using them without attribution, hiding the source, or passing them off as your o Pick the plugin that matches your dsh. The latest plugin supports **dsh 0.2** only. Older dsh builds need the matching older plugin. Do not apply this release to 0.1.x. -- **dsh 0.2** (official desktop **0.2.0-rc.2** / official `dsh web`): use **1.1.40** or newer. The current release is **1.1.65**. The install commands on this page install that line. +- **dsh 0.2** (official desktop **0.2.0-rc.2** / official `dsh web`): use **1.1.40** or newer. The current release is **1.1.66**. The install commands on this page install that line. - **dsh 0.1.7** (including **0.1.7-rc.1** and **0.1.7-rc.2**): use **1.1.39** or older. Pick the tag on [Releases](https://github.com/YuJunZhiXue/dsh-purge/releases). Unmatched patches stay pending or skipped. Nothing is rewritten blindly. @@ -205,13 +205,13 @@ Official desktop 0.2 loads the `desktop` profile. Do not use `default`, and do n
🌐 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.65&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.66&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 ```
+
+
Version 1.1.66
-**Version 1.1.65** ++ DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分 +
-*DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分* + - - - -[English](README.md) | [中文](README.zh-CN.md) + > **官方 Web 和官方桌面端都支持。** 官方 `dsh web` 用 profile `web`;官方桌面 EXE(DeepSeek Harness **0.2.0-rc.2**)用 profile `desktop`。两边分开安装、分开点「应用」。当前版本只适配 dsh 0.2;更早的 dsh 用对应的老版本插件。社区桌面端不维护。 > @@ -33,7 +47,7 @@ --- - + ## ☕ 赞助 @@ -124,7 +138,7 @@ Harness 不只是把问题交给模型。它还会在运行时改提示词、审 请选择支持的版本。最新版只支持 **dsh 0.2**。更早的 dsh 使用对应的老版本插件,不要拿当前版本去打 0.1.x。 -- **dsh 0.2**(官方桌面 **0.2.0-rc.2** / 官方 `dsh web`):用 **1.1.40** 及以上,当前是 **1.1.65**。本页安装命令装的就是这一档。 +- **dsh 0.2**(官方桌面 **0.2.0-rc.2** / 官方 `dsh web`):用 **1.1.40** 及以上,当前是 **1.1.66**。本页安装命令装的就是这一档。 - **dsh 0.1.7**(含 **0.1.7-rc.1**、**0.1.7-rc.2**):用 **1.1.39** 及更早。[Releases](https://github.com/YuJunZhiXue/dsh-purge/releases) 里选对应标签。 对不上的补丁会显示待应用或跳过,不会乱改文件。 @@ -199,7 +213,7 @@ dsh plugin --profile desktop add https://github.com/YuJunZhiXue/dsh-purge/archiv 🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.65&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.66&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 ``` **协议参数和网页触发代码** @@ -214,7 +228,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.65', + version: '1.1.66', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -233,7 +247,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -245,7 +259,7 @@ export function installDshPurgeToDesktop() { | ----------- | --------------------------------------------------------------------------- | ------------ | | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.65` | 语义化版本号 | +| version | `1.1.66` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub 源码包地址 | @@ -553,29 +567,29 @@ dsh-purge --uninstall **清洗** -清洗 + **演练台授权** -演练台授权 + **演练台** -演练台 + **补丁** -补丁 + **规则集** -规则集 + **自己的服务器** 在清洗页,提示词下面。每行一台,点保存名单。步骤见 [自己的服务器](#自己的服务器)。 -自己的服务器 + | 区域 | 说明 | @@ -583,7 +597,6 @@ dsh-purge --uninstall | dsh-purge | 会话标题旁的按钮,打开或收起右侧栏 | | 清洗 | 原来的规则设定:补丁、提示词、规则集、Skill | | 演练台 | 授权后的资产、技能与环境页。未授权时按钮标「未授权」 | -| | | | 补丁 | 分组查看状态,应用、还原或卸载 | | 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 | | 自己的服务器 | 每行登记一个 IP 或完整主机名,保存后写入 `$DSH_HOME/net-scope-allow.txt` | @@ -644,8 +657,6 @@ purge_status purge_apply purge_revert 上面的 `203.0.113.10` 和 `example.com` 只是写法示例,不是放行地址。把它们换成你自己的那一台再保存。 -自己的服务器 - --- ## 本地校验 diff --git a/client.js b/client.js index af70e20..54bdba6 100644 --- a/client.js +++ b/client.js @@ -188,6 +188,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "table.patch": "项目", "table.status": "状态", "status.applied": "已应用", + "status.off": "已关闭", "status.pending": "待应用", "status.unmatched": "没对上", "status.skipped": "跳过", @@ -199,7 +200,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "warn.noInject": "官方始终用默认提示词。红队开了规则集就只用规则集;没开时用去掉 CTF 的默认提示词,再接红队操作。两边都空会提示必须添加。", "need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。", "btn.restoreInject": "恢复默认", - "saved.restoreInject": "已填入默认提示词,点保存写入", + "saved.restoreInject": "已恢复默认提示词", "skip": "跳过", "unknown": "未知", "delete": "删除", @@ -416,6 +417,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "rewind.once.hint": "把这一轮发出去的那句放回输入框,并清掉这一轮", "rewind.round": "回退上一轮", "rewind.round.hint": "把这一轮发出去的那句放回输入框;子代理也只撤这一轮", + "hooksDeny.title": "Hooks 拦截", + "hooksDeny.bypass": "放行 hooks 的 deny / ask(补丁 30 / 31 / 64 / 65)", + "hooksDeny.hint": "关掉后,用户自己的 PreToolUse / UserPromptSubmit / Stop hook 的 deny 会按官方逻辑生效。官方 ask 分支本身是空操作,关开关不会弹出审批框。改完后点「应用」并重启才写进宿主。", + "saved.hooksDeny": "已保存", "continue.title": "失败重试 / 继续", "continue.hint": "请求失败会自动重试;异常停止或中断可点「继续」或自动续跑。自己点停止不会自动继续。次数用完后需新开一轮。", "continue.autoRetry": "失败自动重试", @@ -500,6 +505,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "table.patch": "Item", "table.status": "Status", "status.applied": "Applied", + "status.off": "Off", "status.pending": "Pending", "status.unmatched": "No match", "status.skipped": "Skipped", @@ -511,7 +517,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "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.", + "saved.restoreInject": "Default prompt restored", "skip": "Skipped", "unknown": "Unknown", "delete": "Delete", @@ -728,6 +734,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "rewind.once.hint": "Put this round's message back in the box and drop only this round", "rewind.round": "Undo last round", "rewind.round.hint": "Put this round's message back in the box; subagents drop only this round", + "hooksDeny.title": "Hook interception", + "hooksDeny.bypass": "Bypass hook deny / ask (patches 30 / 31 / 64 / 65)", + "hooksDeny.hint": "When off, your own PreToolUse / UserPromptSubmit / Stop hook deny runs as the official host wrote it. The official ask branch is a no-op; turning this off will not show an approval dialog. Click Apply and restart to write the host files.", + "saved.hooksDeny": "Saved", "continue.title": "Retry / Continue", "continue.hint": "Failed requests auto-retry. After an abnormal stop or interrupt, use Continue or auto-resume. A manual stop never auto-continues. Counts reset after a completed turn.", "continue.autoRetry": "Auto-retry on failure", @@ -973,12 +983,13 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds if (st === "pending") return "wait"; if (st === "unmatched") return "bad"; if (st === "na") return "ok"; - if (st === "missing_file" || st === "skipped" || st === "unlocated") return "miss"; + if (st === "missing_file" || st === "skipped" || st === "unlocated" || st === "off") return "miss"; return "bad"; } function statusLabel(st, t) { if (st === "applied" || st === "already") return t("status.applied"); + if (st === "off") return t("status.skipped"); if (st === "pending") return t("status.pending"); if (st === "unmatched") return t("status.unmatched"); if (st === "skipped") return t("status.skipped"); @@ -1096,6 +1107,61 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds }); } + function HooksDenySection({ onSaved }) { + const t = useT(); + const [cfg, setCfg] = useState(null); + const [notice, setNotice] = useState({ kind: "idle", text: "" }); + const [busy, setBusy] = useState(false); + + useEffect(() => { + apiJson("/dsh-purge/hooks-deny") + .then((d) => { if (d && d.ok) setCfg({ hooksDenyBypass: d.hooksDenyBypass !== false }); }) + .catch(() => {}); + }, []); + + const save = (hooksDenyBypass) => { + if (!cfg || busy) return; + setCfg({ hooksDenyBypass }); + setBusy(true); + apiJson("/dsh-purge/hooks-deny", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ hooksDenyBypass }), + }) + .then((d) => { + if (d && d.ok) { + setCfg({ hooksDenyBypass: d.hooksDenyBypass === true }); + setNotice({ kind: "ok", text: t("saved.hooksDeny") }); + if (typeof onSaved === "function") onSaved(); + } else { + setNotice({ kind: "error", text: t("err.save", { error: (d && d.error) || "" }) }); + } + }) + .catch((e) => setNotice({ kind: "error", text: t("err.save", { error: e.message }) })) + .finally(() => setBusy(false)); + }; + + if (!cfg) return null; + return h("div", { className: "dshp-cr", style: { marginTop: 12 } }, + h("div", { className: "dshp-sub" }, + h("h4", null, t("hooksDeny.title")), + noticeNode(notice), + ), + h("p", { className: "dshp-hint", style: { margin: "0 0 4px", color: "var(--dshp-mute)", fontSize: 12 } }, t("hooksDeny.hint")), + h("div", { className: "dshp-cr-row" }, + h("label", null, + h("input", { + type: "checkbox", + checked: cfg.hooksDenyBypass === true, + disabled: busy, + onChange: (e) => save(e.target.checked), + }), + t("hooksDeny.bypass"), + ), + ), + ); + } + function ContinueRetrySection() { const t = useT(); const [cfg, setCfg] = useState(null); @@ -1597,9 +1663,36 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds const restoreOverride = useCallback(() => { if (!defaultOverride) return; + const tr = t; + const ticket = ++actionTicket.current; overrideRef.current = defaultOverride; setOverride(defaultOverride); - setNotice({ kind: "ok", text: t("saved.restoreInject") }); + setPatchBusy(true); + setNotice({ kind: "idle", text: "" }); + apiJson("/dsh-purge/override", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ content: defaultOverride }), + }) + .then((d) => { + if (ticket !== actionTicket.current) return; + if (!d || !d.ok) { + setNotice({ kind: "error", text: tr("err.save", { error: (d && d.error) || "" }) }); + return; + } + if (typeof d.content === "string") { + overrideRef.current = d.content; + setOverride(d.content); + } + setNotice({ kind: "ok", text: tr("saved.restoreInject") }); + }) + .catch((e) => { + if (ticket !== actionTicket.current) return; + setNotice({ kind: "error", text: tr("err.save", { error: e.message }) }); + }) + .finally(() => { + if (ticket === actionTicket.current) setPatchBusy(false); + }); }, [defaultOverride, t]); const waitHostAfterUninstall = useCallback((tr) => { @@ -1777,6 +1870,7 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds ), h("div", { className: "dshp-bar", "aria-hidden": "true" }, h("i", { style: { width: pct + "%" } })), h(PatchGroups, { state: s }), + h(HooksDenySection, { onSaved: loadAll }), h("div", { className: "dshp-row", style: { marginTop: 14 } }, h(Btn, { kind: "primary", disabled: patchBusy || uninstallBusy || !overrideLoaded, onClick: () => doAction("apply", "action.apply") }, patchBusy ? t("btn.apply.busy") : t("btn.apply")), h(Btn, { kind: "danger", disabled: patchBusy || uninstallBusy, onClick: () => doAction("revert", "action.revert") }, t("btn.revert")), diff --git a/cordis.patch.yml b/cordis.patch.yml index 00d5c74..3e7de13 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -49,6 +49,7 @@ continueMax: 3 continueText: "继续" capabilityProtocol: true + hooksDenyBypass: true # 演练台:预设 + 技能落地(本插件 lib/redteam) - id: dsh-purge-redteam diff --git a/lib/continue-retry.js b/lib/continue-retry.js index 8dca8d1..fabc5bf 100644 --- a/lib/continue-retry.js +++ b/lib/continue-retry.js @@ -17,10 +17,22 @@ const PERMANENT_CODES = new Set([ "INVALID", "INVALID_REQUEST", "QUOTA", + "ACCOUNT_QUOTA", "BILLING", "MODEL_NOT_FOUND", "CONTEXT_OVERFLOW", "CONTEXT_LENGTH", + "CONTEXT_WINDOW_EXCEEDED", + "NO_ADAPTER", + "MISSING_CREDENTIAL", + "INVALID_CREDENTIAL", +]); + +/** Official already retried these; a new "继续" turn cannot clear them. */ +const NO_CONTINUE_CODES = new Set([ + ...PERMANENT_CODES, + "RATE_LIMIT", + "TRANSPORT", ]); const ABNORMAL_KINDS = new Set(["error", "aborted", "interrupted", "max-tokens"]); @@ -87,8 +99,15 @@ export function isAbnormalReason(reason) { return Boolean(reason && ABNORMAL_KINDS.has(reason.kind)); } +export function failureCodeOf(reason) { + const raw = reason?.error?.code ?? reason?.failure?.code ?? reason?.code; + return String(raw || "").toUpperCase(); +} + export function shouldAutoContinue(reason) { - return isAbnormalReason(reason) && !isUserAbort(reason); + if (!isAbnormalReason(reason) || isUserAbort(reason)) return false; + const code = failureCodeOf(reason); + return !code || !NO_CONTINUE_CODES.has(code); } export function isPermanentFailure(code) { @@ -107,8 +126,7 @@ export function makeContinueMessage(text) { role: "user", content: [{ type: "text", text: body }], source: { - kind: "plugin", - plugin: "dsh-purge", + kind: "dsh-purge", form: "notice", summary: "continue", }, @@ -195,7 +213,8 @@ export function hasFreshHumanTurn(events) { const after = end ? list.filter((event) => (event?.seq || 0) > end.seq) : list; return after.some((event) => { if (event?.type !== "user/message") return false; - return event.data?.source?.kind !== "plugin"; + const kind = event.data?.source?.kind; + return kind !== "plugin" && kind !== "dsh-purge"; }); } diff --git a/lib/core.js b/lib/core.js index f013bcc..d915ff7 100644 --- a/lib/core.js +++ b/lib/core.js @@ -28,6 +28,7 @@ import { import { adapterFor, detectSurface } from "./surface.js"; import { hostPromptKeepsInject } from "./host-clean.js"; import { openSlot } from "./table-read.js"; +import * as hooksDeny from "./hooks-deny.js"; // 无归档时用 node:fs;app.asar 还在时改写真实的 resources/app,避免新建文件 ENOENT。 const fs = hostFs; @@ -1775,6 +1776,11 @@ async function resolveAiBaseForApply(aiBase, options = {}) { } export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) { + const settings = options.hooksDeny?.settings || getHooksDenySettings(); + const pick = options.hooksDeny?.selectPatches || hooksDeny.selectPatches; + const selected = pick(patches, settings); + const hookDenyRestoreFailed = []; + const hookDenyRestoreChanged = []; const hosts = []; const seen = new Set(); for (const raw of enumeratePatchAiBases()) { @@ -1784,7 +1790,12 @@ export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) if (seen.has(key)) continue; seen.add(key); await backupAll(aiBase); - const report = await applyPatches(aiBase, patches, options); + if (settings.hooksDenyBypass === false) { + const restored = await restoreHookDenyForBases([aiBase]); + hookDenyRestoreFailed.push(...restored.failed); + hookDenyRestoreChanged.push(...restored.changed); + } + const report = await applyPatches(aiBase, selected, options); hosts.push({ aiBase, report, @@ -1793,7 +1804,12 @@ export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) flash: silenceCmdFlash(aiBase), }); } - return { hosts, report: mergeApplyReports(hosts.map((h) => h.report)) }; + return { + hosts, + report: mergeApplyReports(hosts.map((h) => h.report)), + hookDenyRestoreFailed, + hookDenyRestoreChanged, + }; } export async function revertAllHosts(options = {}) { @@ -4267,6 +4283,47 @@ const NEW_TOOL_PATCHES = [ ], markers: ["[dsh-purge] prepare assemble before this step"], }, + { + id: 81, + name: "HUNG_PROMPT_EVERY_STEP", + layer: "代码", + layer_en: "Code", + desc: "每一步用同一份 prompt-inject 全文,第二轮不再把注入换掉 / keep the hung prompt-inject on every step", + file: ["agent-loop"], + skipIfMarked: true, + replacements: [ + { + pattern: + "\t\tconst dshPurgePrepare = globalThis.__dshPurgePrepareAssemble;\n" + + "\t\tif (typeof dshPurgePrepare === \"function\") {\n" + + "\t\t\ttry { dshPurgePrepare(this.loopCtx); } catch { /* [dsh-purge] prepare assemble before this step */ }\n" + + "\t\t}\n" + + "\t\tconst assembly = await this.loopCtx.systemPrompt.assemble(assembleContextFor(this, signal));", + replace: + "\t\tconst dshPurgePrepare = globalThis.__dshPurgePrepareAssemble;\n" + + "\t\tlet dshPurgePrompt = null;\n" + + "\t\tif (typeof dshPurgePrepare === \"function\") {\n" + + "\t\t\ttry { dshPurgePrompt = dshPurgePrepare(this.loopCtx); } catch { /* [dsh-purge] prepare assemble before this step */ }\n" + + "\t\t}\n" + + "\t\tconst dshPurgeAssemble = dshPurgePrompt && typeof dshPurgePrompt.assemble === \"function\" ? dshPurgePrompt : this.loopCtx.systemPrompt;\n" + + "\t\tconst assembly = await dshPurgeAssemble.assemble(assembleContextFor(this, signal));", + }, + { + pattern: + "\t\tconst { assembly } = decision;\n" + + "\t\tconst renderedPrompt = renderPrompt(assembly);", + replace: + "\t\tconst { assembly } = decision;\n" + + "\t\tlet renderedPrompt = renderPrompt(assembly);\n" + + "\t\tconst dshPurgeHung = typeof globalThis.__dshPurgeHungPrompt === \"function\" ? globalThis.__dshPurgeHungPrompt() : \"\";\n" + + "\t\tconst dshPurgeNeedle = String(dshPurgeHung || \"\").trim().slice(0, 96);\n" + + "\t\tif (dshPurgeNeedle && !String(renderedPrompt || \"\").includes(dshPurgeNeedle)) {\n" + + "\t\t\trenderedPrompt = String(dshPurgeHung).trim() + (renderedPrompt ? \"\\n\\n\" + renderedPrompt : \"\"); // [dsh-purge] hang full prompt-inject every step\n" + + "\t\t}", + }, + ], + markers: ["[dsh-purge] hang full prompt-inject every step"], + }, { id: 66, name: "SYSTEM_PROMPT_RENDER_GUARD", @@ -5026,6 +5083,16 @@ const NEW_TOOL_PATCHES = [ '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";\n' + '\t\t\tagent.steer(createUserMessage({', }, + { + pattern: + '\t\tif (merged.decision === "deny") {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";\n' + + '\t\t\tagent.steer(createUserMessage({', + replace: + '\t\tif (merged.decision === "deny") {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";\n' + + '\t\t\tagent.steer(createUserMessage({', + }, ], markers: ["[dsh-purge] Stop hook steer disabled"], }, @@ -5046,9 +5113,53 @@ const NEW_TOOL_PATCHES = [ '\t\tif (merged.decision === "deny") { /* [dsh-purge] UserPromptSubmit deny→allow */ }\n' + '\t\telse if (merged.decision === "__dsh_purge_deny_disabled__") { /* [dsh-purge] pre-step reject disabled */ }', }, + { + pattern: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, ], markers: ["[dsh-purge] UserPromptSubmit deny→allow"], }, + { + id: 78, + name: "OVERLAY_RESTORE_FROM_BAK", + layer: "代码", + layer_en: "Code", + desc: "声明过的补丁文件不见时,从 .dshpurge.bak 拷回再加载 / restore a missing declared overlay from its bak", + file: ["app-boot"], + optional: true, + skipIfMarked: true, + replacements: [ + { + pattern: + "function loadOverlayPatches(binName, file) {\n" + + "\tlet content;\n" + + "\ttry {\n" + + "\t\tcontent = readFileSync(file, \"utf8\");\n" + + "\t} catch (error) {\n" + + "\t\tthrow new Error(`${binName}: failed to read overlay ${file}: ${String(error)}`);\n" + + "\t}\n" + + "\treturn parsePatchList(binName, file, content, \"overlay\");\n" + + "}", + replace: + "function loadOverlayPatches(binName, file) {\n" + + "\tlet content;\n" + + "\ttry {\n" + + "\t\tcontent = readFileSync(file, \"utf8\");\n" + + "\t} catch (error) {\n" + + "\t\tconst bak = file + \".dshpurge.bak\"; // [dsh-purge] restore missing overlay from bak\n" + + "\t\tif (error && error.code === \"ENOENT\" && fs.existsSync(bak)) {\n" + + "\t\t\ttry { fs.copyFileSync(bak, file); content = readFileSync(file, \"utf8\"); }\n" + + "\t\t\tcatch { /* bak restore failed */ }\n" + + "\t\t}\n" + + "\t\tif (content === void 0) throw new Error(`${binName}: failed to read overlay ${file}: ${String(error)}`);\n" + + "\t}\n" + + "\treturn parsePatchList(binName, file, content, \"overlay\");\n" + + "}", + }, + ], + markers: ["[dsh-purge] restore missing overlay from bak"], + }, ]; export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES]; @@ -5181,6 +5292,79 @@ export async function dropStaleUserProfilePatchBackups(dshHome = findDshHome()) return dropped; } +const BAK_SUFFIX = ".dshpurge.bak"; + +function shouldRestoreOriginal(original, bak) { + if (isUserProfilePatchFile(original)) return false; + let bakStat; + try { + bakStat = fs.statSync(bak); + } catch { + return false; + } + if (!bakStat.isFile() || bakStat.size <= 0) return false; + try { + const st = fs.statSync(original); + if (!st.isFile() || st.size > 0) return false; + } catch (e) { + if (!e || e.code !== "ENOENT") return false; + } + return true; +} + +/** + * 正式文件不见、或被写成空文件时,从旁边的 .dshpurge.bak 拷回去。 + * 不删 bak。targetFiles 只认还在的文件,所以丢了以后还原/应用都看不见这份备份。 + * @returns 已拷回的正式路径 + */ +export function restoreMissingOriginalsFromBak(aiBase) { + const restored = []; + if (!aiBase || !isDir(aiBase)) return restored; + const roots = [aiBase]; + const nested = path.join(aiBase, "dsh", "node_modules", "@deepseek-ai"); + if (isDir(nested)) roots.push(nested); + const visit = (dir, depth) => { + if (depth > 5) return; + let ents = []; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const ent of ents) { + if (ent.name === "node_modules" || ent.name === ".git") continue; + const fp = path.join(dir, ent.name); + if (ent.isDirectory()) { + visit(fp, depth + 1); + continue; + } + if (!ent.isFile() || !ent.name.endsWith(BAK_SUFFIX)) continue; + const original = fp.slice(0, -BAK_SUFFIX.length); + if (!shouldRestoreOriginal(original, fp)) continue; + try { + fs.copyFileSync(fp, original); + restored.push(original); + } catch { + /* 文件被占用时下次启动再试 */ + } + } + }; + for (const root of roots) visit(root, 0); + return restored; +} + +export function restoreMissingOriginalsAllHosts() { + const restored = []; + for (const aiBase of enumeratePatchAiBases()) { + try { + restored.push(...restoreMissingOriginalsFromBak(aiBase)); + } catch { + /* 一个宿主失败不挡住其余 */ + } + } + return restored; +} + export async function backupAll(aiBase) { const files = targetFiles(aiBase); const made = []; @@ -5217,6 +5401,7 @@ async function sameFileBytes(left, right) { } export async function revertAll(aiBase, options = {}) { + restoreMissingOriginalsFromBak(aiBase); const files = targetFiles(aiBase); const reverted = []; const skipped = []; @@ -5518,6 +5703,9 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { "agent-loop": allExisting([ ...nestedPkg(aiBase, "dsh-agent-loop", "lib", "index.js"), ]), + "app-boot": allExisting([ + ...nestedPkg(aiBase, "dsh-app-boot", "lib", "index.js"), + ]), "conversation-client": allExisting([ ...nestedPkg(aiBase, "dsh-client-ui-conversation", "lib", "client.js"), ]), @@ -5850,6 +6038,20 @@ function fileKeysOf(p) { return Array.isArray(p.file) ? p.file : [p.file]; } +export function hookDenyPaths(aiBase) { + const files = targetFiles(aiBase); + const out = []; + for (const p of ALL_PATCHES) { + if (!hooksDeny.HOOK_DENY_PATCH_IDS.includes(p.id)) continue; + for (const key of fileKeysOf(p)) { + for (const fp of pathsOf(files, key)) { + if (fp && !out.includes(fp)) out.push(fp); + } + } + } + return out; +} + function patchReplacements(p) { if (Array.isArray(p.replacements)) return p.replacements; return (p.patterns ?? []).map((pat) => ({ pattern: pat, replace: p.replace })); @@ -5937,7 +6139,9 @@ export function applyReplacementsToText(text, patch, fp = "") { } const needle = asLf(pattern); if (!out.includes(needle)) continue; - out = out.split(needle).join(written); + const next = out.split(needle).join(written); + if (next === out) continue; + out = next; changed = true; } if (crlf) out = out.replace(/\n/g, "\r\n"); @@ -5956,7 +6160,7 @@ function rollupPatchStatus({ applied, already, missing, notFound, lastError, key return "pattern_not_found"; } -const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "skipped", "na"]); +const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "skipped", "na", "off"]); export function patchAppliesHere(patch, surface = detectSurface()) { const want = patch?.surfaces; @@ -6009,6 +6213,48 @@ async function saveText(p, text) { return true; } +export const hookDenyIo = { + hookDenyPaths, + loadText, + saveText, +}; + +let hooksDenySettings = null; +let hooksDenyConfigValue; + +export function setHooksDenyConfigValue(value) { + hooksDenyConfigValue = value; +} + +export function refreshHooksDenySettings() { + hooksDenySettings = Object.freeze( + hooksDeny.loadHookDenySettings(findDshHome(), hooksDenyConfigValue), + ); + return hooksDenySettings; +} + +export function getHooksDenySettings() { + if (!hooksDenySettings) return refreshHooksDenySettings(); + return hooksDenySettings; +} + +export function setHooksDenySettings(patch) { + const saved = hooksDeny.saveHookDenySettings(findDshHome(), patch); + hooksDenySettings = Object.freeze({ hooksDenyBypass: saved.hooksDenyBypass }); + return saved; +} + +export async function restoreHookDenyForBases(bases) { + const failed = []; + const changed = []; + for (const aiBase of bases || []) { + const r = await hooksDeny.restoreHookDenyOfficial(aiBase, hookDenyIo); + changed.push(...r.changed); + failed.push(...r.sentinelLeft, ...r.misses); + } + return { changed, failed }; +} + async function repairPluginCordisYaml() { const fp = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cordis.patch.yml"); if (!isFile(fp)) return; @@ -6018,6 +6264,7 @@ async function repairPluginCordisYaml() { } export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {}) { + restoreMissingOriginalsFromBak(aiBase); const files = targetFiles(aiBase); const report = []; const preserveClientBundles = options.preserveClientBundles === true; @@ -6180,6 +6427,7 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) { else if (skipped > 0) status[p.id] = "skipped"; else status[p.id] = p.optional ? "na" : "missing_file"; } + await hooksDeny.annotateHookDenyStatus(status, getHooksDenySettings(), aiBase, hookDenyIo); return status; } @@ -6790,7 +7038,7 @@ export function editOverride(dshHome) { /** 列表上的“已就绪”:已写入、或当前版本不需要 / 组件未装(与 apply 的 soft-ok 对齐)。 */ export function patchStatusReady(status, patch = null) { - if (status === "applied" || status === "already") return true; + if (status === "applied" || status === "already" || status === "off") return true; if (status === "skipped" || status === "missing_file") return true; if (status === "na") return false; if (status === "pattern_not_found" && patch?.strictFiles) return false; @@ -6825,7 +7073,7 @@ export async function gatherState() { patches_total += 1; if (s === "applied") patches_applied += 1; if (s === "pending") patches_pending += 1; - if (s === "skipped" || s === "missing_file") patches_skipped += 1; + if (s === "skipped" || s === "missing_file" || s === "off") patches_skipped += 1; if (patchStatusReady(s, p)) patches_ready += 1; } let shim_cmd = "missing"; @@ -6868,5 +7116,6 @@ export async function gatherState() { override_path: findOverrideFile(dshHome), override_status: await overrideStatus(dshHome), asar_still_sealed: desktopAsarStillSealed(), + hooks_deny_bypass: getHooksDenySettings().hooksDenyBypass, }; } diff --git a/lib/hooks-deny.js b/lib/hooks-deny.js new file mode 100644 index 0000000..20f0daf --- /dev/null +++ b/lib/hooks-deny.js @@ -0,0 +1,217 @@ +// #80:hooks deny / ask 旁路的开关、反向写回官方形态、状态标注。 +// 本模块不 import core.js(core 在需要时回调本模块,避免循环依赖)。 +import fs from "node:fs"; +import path from "node:path"; + +/** #80 产品语义:这四条永远同开关,不拆开。 */ +export const HOOK_DENY_PATCH_IDS = Object.freeze([30, 31, 64, 65]); + +const DEFAULT_SETTINGS = Object.freeze({ hooksDenyBypass: true }); +const SETTINGS_FILE = "hooks-deny.json"; + +/** 补丁 30/31 写出的死字符串;它出现即代表「旁路还开着」。 */ +const DISABLED_SENTINEL = "__dsh_purge_deny_disabled__"; + +const MARKER_STOP = "[dsh-purge] Stop hook steer disabled"; +const MARKER_SUBMIT = "[dsh-purge] UserPromptSubmit deny→allow"; + +/** + * 反向替换表。find 必须逐字命中本插件写出的形态。 + * R1a 活文件(30+65 同一轮):65 把 reject 行写成 `=== "deny"` 空壳。 + * R1a2 二次应用:30 没有 skipIfMarked,会再把空壳里的 `"deny"` 改成死字符串。 + * R1b:只打了 30、还没打 65。 + * R2a / R2b 必须连 body 的 kind 一起匹配,不能只认行首。 + */ +const REVERSES = Object.freeze([ + { + id: "R1a", + find: + '\t\tif (merged.decision === "deny") { /* [dsh-purge] UserPromptSubmit deny→allow */ }\n' + + '\t\telse if (merged.decision === "__dsh_purge_deny_disabled__") { /* [dsh-purge] pre-step reject disabled */ }', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, + { + id: "R1a2", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */' + + ' { /* [dsh-purge] UserPromptSubmit deny→allow */ }\n' + + '\t\telse if (merged.decision === "__dsh_purge_deny_disabled__") { /* [dsh-purge] pre-step reject disabled */ }', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, + { + id: "R1b", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ return { kind: "reject" };', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, + { + id: "R2a", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ return {\n' + + '\t\t\tkind: "deny",', + replace: '\t\tif (merged.decision === "deny") return {\n\t\t\tkind: "deny",', + }, + { + id: "R2b", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ return {\n' + + '\t\t\tkind: "block",', + replace: '\t\tif (merged.decision === "deny") return {\n\t\t\tkind: "block",', + }, + { + id: "R3", + find: '\t\tif (merged.decision === "ask") return next(); /* [dsh-purge] hooks ask→allow */', + replace: + '\t\tif (merged.decision === "ask") return {\n' + + '\t\t\tkind: "ask",\n' + + '\t\t\t...merged.reason !== void 0 ? { reason: merged.reason } : {}\n' + + '\t\t};', + }, + { + id: "R5a", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ {\n' + + '\t\t\treturn; // [dsh-purge] Stop hook steer disabled\n', + replace: '\t\tif (merged.decision === "deny") {\n', + }, + { + id: "R5b", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";', + replace: + '\t\tif (merged.decision === "deny") {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";', + }, +]); + +const SENTINEL_RULE = Object.freeze({ + id: "R0", + find: '"__dsh_purge_deny_disabled__"', + replace: '"deny"', +}); + +export function applyHookDenyReverses(text) { + let out = String(text || ""); + const hits = []; + for (const rule of REVERSES) { + if (!out.includes(rule.find)) continue; + out = out.split(rule.find).join(rule.replace); + hits.push(rule.id); + } + if (hits.length === 0 && out.includes(DISABLED_SENTINEL)) { + const next = out.split(SENTINEL_RULE.find).join(SENTINEL_RULE.replace); + if (next !== out) { + out = next; + hits.push("R0"); + } + } + return { text: out, hits }; +} + +export function hookFileLooksBypassed(text) { + const hay = String(text || ""); + return hay.includes(DISABLED_SENTINEL) || hay.includes(MARKER_STOP) || hay.includes(MARKER_SUBMIT); +} + +/** + * 把 aiBase 上这四条补丁涉及的文件写回官方形态。 + * @returns {{ files: string[], changed: string[], misses: string[], sentinelLeft: string[], hitsByFile: Record