fix: 发布 1.1.66,Hooks 开关与会话来源

清洗页可关掉 hooks deny 旁路。继续/拒答续跑改用官方允许的来源 kind,限流和传输失败不再自动续一轮。

Closes #80. Closes #81.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-10-09 01:32:17 +08:00
1 parent 76e64d65e0
commit 09bac57f2c
13 files changed
+789 -59

No files matched your search

+23 -4
View File
@@ -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";
});
}
+255 -6
View File
@@ -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,
};
}
+217
View File
@@ -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<string, string[]> }}
*/
export async function restoreHookDenyOfficial(aiBase, io) {
const result = { files: [], changed: [], misses: [], sentinelLeft: [], hitsByFile: {} };
if (!aiBase || !io) return result;
const paths = io.hookDenyPaths(aiBase);
for (const fp of paths) {
result.files.push(fp);
let text;
try {
text = await io.loadText(fp);
} catch {
result.misses.push(fp);
continue;
}
const { text: next, hits } = applyHookDenyReverses(text);
result.hitsByFile[fp] = hits;
if (hits.length === 0) {
if (next.includes(DISABLED_SENTINEL)) result.sentinelLeft.push(fp);
continue;
}
try {
const wrote = await io.saveText(fp, next);
if (wrote) result.changed.push(fp);
} catch {
result.misses.push(fp);
}
if (next.includes(DISABLED_SENTINEL)) result.sentinelLeft.push(fp);
}
return result;
}
export async function annotateHookDenyStatus(status, settings, aiBase, io) {
if (!status || !aiBase || settings?.hooksDenyBypass !== false) return status;
const paths = io.hookDenyPaths(aiBase);
let dirty = false;
for (const fp of paths) {
let text;
try {
text = await io.loadText(fp);
} catch {
continue;
}
if (hookFileLooksBypassed(text)) {
dirty = true;
break;
}
}
for (const id of HOOK_DENY_PATCH_IDS) {
const prev = status[id];
if (prev === "na" || prev === "missing_file") continue;
status[id] = dirty ? "pending" : "skipped";
}
return status;
}
export function hookDenySettingsPath(dshHome) {
return path.join(dshHome, "dsh-purge", SETTINGS_FILE);
}
export function loadHookDenySettings(dshHome, configValue) {
let file = {};
try {
const fp = hookDenySettingsPath(dshHome);
if (fs.existsSync(fp)) {
const parsed = JSON.parse(fs.readFileSync(fp, "utf8"));
if (parsed && typeof parsed === "object") file = parsed;
}
} catch {
file = {};
}
const pick = [file.hooksDenyBypass, configValue, DEFAULT_SETTINGS.hooksDenyBypass];
const value = pick.find((v) => typeof v === "boolean");
return { hooksDenyBypass: value === undefined ? true : value };
}
export function saveHookDenySettings(dshHome, patch) {
const fp = hookDenySettingsPath(dshHome);
fs.mkdirSync(path.dirname(fp), { recursive: true });
const current = loadHookDenySettings(dshHome);
const next = {
hooksDenyBypass: typeof patch?.hooksDenyBypass === "boolean"
? patch.hooksDenyBypass
: current.hooksDenyBypass,
};
const tmp = `${fp}.${process.pid}.tmp`;
fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, "utf8");
try {
if (fs.existsSync(fp)) fs.unlinkSync(fp);
} catch { /* rename 覆盖 */ }
fs.renameSync(tmp, fp);
return { ok: true, ...next, path: fp };
}
export function selectPatches(patches, settings) {
if (settings?.hooksDenyBypass !== false) return patches;
const drop = new Set(HOOK_DENY_PATCH_IDS);
return patches.filter((p) => !drop.has(p.id));
}
+17
View File
@@ -729,6 +729,23 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
: withOps;
}
assembled.sections = sanitizeAssemblySections(leadWithInject(sections, injectText, protocol));
if (injectText) {
const needle = injectText.slice(0, 80);
const has = assembled.sections.some((section) => (
typeof section?.text === "string" && needle && section.text.includes(needle)
));
if (!has) {
assembled.sections = [
{
name: "dsh-purge",
text: injectText,
interpolate: false,
order: GLOBAL_PROMPT_ORDER + 1,
},
...assembled.sections.filter((section) => section && section.name !== "dsh-purge"),
];
}
}
if (!Array.isArray(assembled.contexts)) assembled.contexts = [];
if (!Array.isArray(assembled.tools)) assembled.tools = [];
return assembled;
+83 -10
View File
@@ -58,6 +58,7 @@ const DEFAULTS = {
refusalRecoverText: "",
// Codex 风格:教模型主动发现 skill / MCP;不改官方注册与工具面。
capabilityProtocol: true,
hooksDenyBypass: true,
};
const log = (config, ...args) => {
@@ -162,11 +163,26 @@ function injectAllowedNow(config) {
/** 提示词框自改 > prompt-inject.md > 加密默认(见 rules.resolveInjectText)。 */
function refreshHungOperator(dshHome = core.findDshHome()) {
const home = dshHome || core.findDshHome();
const home = core.pinDshHome() || dshHome || core.findDshHome();
try { core.syncPromptInjectOnDiskSync(home); } catch { /* 同步失败仍按 resolve 走 */ }
const resolved = rules.resolveInjectText(home);
core.hangOperatorPrompt(resolved.text);
return resolved;
const text = resolved.text || core.normalizeOverride(core.defaultOverrideText()) || "";
if (text) {
core.hangOperatorPrompt(text);
// 与点「保存」同一钉钉:不点保存,组装也要读到这一份全文。
core.rememberCommittedOverride(home, text);
}
return { ...resolved, text: text || resolved.text };
}
function installHungPromptGlobal() {
globalThis.__dshPurgeHungPrompt = () => {
try {
return refreshHungOperator(core.findDshHome()).text || "";
} catch {
return core.hungOperatorPrompt() || "";
}
};
}
function injectSnapshot(dshHome = core.findDshHome()) {
@@ -269,7 +285,7 @@ export function registerPromptSections(ctx, config, _injectFile) {
function readInjectFallback(context) {
let home = "";
try { home = core.findDshHome(); } catch { home = ""; }
const raw = rules.ensureOperatorBody(home);
const raw = refreshHungOperator(home).text || rules.ensureOperatorBody(home);
if (!raw) return "";
let redteam = false;
try { redteam = isRedteamSession(context); } catch { redteam = false; }
@@ -418,7 +434,7 @@ function installIdentityOverride(ctx, config = {}) {
// 切换预设会换掉 assemble。pre-step 瀑布在 assemble 之后才跑,第一次发送包不上。
// 宿主在 assemble 之前调用这个函数,用的就是当前模式自己的 systemPrompt。
const prepareAssemble = (loopCtx) => {
try { rules.ensureOperatorBody(core.findDshHome()); } catch { /* 主目录还没有提示词 */ }
try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ }
const prompt = loopCtx && loopCtx.systemPrompt;
if (prompt) {
try {
@@ -428,8 +444,10 @@ function installIdentityOverride(ctx, config = {}) {
} catch { /* 这一层代理包不上时,下面再包插件自己的 */ }
}
wrapAssemble();
return prompt || null;
};
globalThis.__dshPurgePrepareAssemble = prepareAssemble;
installHungPromptGlobal();
// complete:true 会在 waterfall 之后盖掉 sections;包住 assemble 返回值,每轮都补回注入。
wrapAssemble();
const started = Date.now();
@@ -442,7 +460,7 @@ function installIdentityOverride(ctx, config = {}) {
try { ctx.on("session/created", wrapAssemble); } catch { /* ignore */ }
try {
ctx.on("agent-preset/selected", () => {
try { rules.ensureOperatorBody(core.findDshHome()); } catch { /* 主目录还没有提示词 */ }
try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ }
wrapAssemble();
}, { global: true });
} catch { /* ignore */ }
@@ -581,6 +599,14 @@ async function autoApply(config) {
const sanitized = core.sanitizeDesktopCommandRuntimes();
if (sanitized.length) log(config, "desktop runtime sanitized:", JSON.stringify(sanitized));
core.refreshHooksDenySettings();
if (core.getHooksDenySettings().hooksDenyBypass === false) {
const restored = await core.restoreHookDenyForBases(core.enumeratePatchAiBases());
if (restored.failed.length) {
log(config, "hooks-deny restore leftover:", restored.failed.join(","));
}
}
const state = await core.gatherState();
if (!state.ai_base) {
log(config, "skip auto-apply: plugin root not found");
@@ -696,7 +722,8 @@ async function handlePurgeCommand(rawInput, config) {
lines.push("Desktop: host-commands 密封目录只清理不注入;bak 禁止写进 bin(issue #9)。");
const summary = core.summarizeApplyReport(report);
const hostWritten = core.allPatchHostsWritten(applyMulti.hosts) || core.hostCleanMarkersPresent(state.ai_base);
const complete = summary.failed.length === 0 && flash.ok === true && hostWritten;
const hookDenyRestoreFailed = (applyMulti.hookDenyRestoreFailed || []).length > 0;
const complete = summary.failed.length === 0 && flash.ok === true && hostWritten && !hookDenyRestoreFailed;
const promptReady = summary.failed.length > 0 && summary.failed.every((item) => item.status === "pattern_not_found");
const shouldRestart = applyShouldRestart({
complete: complete || (promptReady && hostWritten),
@@ -1004,6 +1031,19 @@ async function handleSkillsCommand(rawInput) {
export function apply(ctx, config) {
const cfg = { ...DEFAULTS, ...(config || {}) };
if (!cfg.enabled) return;
core.setHooksDenyConfigValue(cfg.hooksDenyBypass);
core.refreshHooksDenySettings();
try {
const home = core.pinDshHome() || core.findDshHome();
installHungPromptGlobal();
refreshHungOperator(home);
} catch { /* 主目录还没有时,组装会再挂内置默认 */ }
try {
const restored = core.restoreMissingOriginalsAllHosts();
if (restored.length) log(cfg, "restored missing overlay from bak:", restored.join(","));
} catch (e) {
console.warn("[dsh-purge] restore bak:", String(e && e.message ? e.message : e));
}
const life = watchContextLife(ctx);
if (!life.alive) {
console.warn("[dsh-purge] skip apply: inactive context");
@@ -1080,7 +1120,7 @@ export function apply(ctx, config) {
function applyHostHooks(ctx, cfg) {
try {
const home = core.pinDshHome() || core.findDshHome();
rules.ensureOperatorBody(home);
refreshHungOperator(home);
} catch { /* 主目录尚未就绪 */ }
installIdentityOverride(ctx, cfg);
installRegionGate(ctx);
@@ -1349,6 +1389,7 @@ function installWebServer(ctx, cfg) {
boot_full_quit: bootFullQuit,
update: updater.lastUpdateResult(),
...updater.channelPublic(),
hooks_deny_bypass: core.getHooksDenySettings().hooksDenyBypass,
...(await skills.skillsStatus(core.findDshHome()).catch(() => ({ skills: [] }))),
});
} catch (e) {
@@ -1356,6 +1397,37 @@ function installWebServer(ctx, cfg) {
}
},
}, "dsh-purge: status");
registerPluginRoute({
kind: "exact",
path: "/dsh-purge/hooks-deny",
handler: async (request, response) => {
if (request.method === "GET") {
try {
const settings = core.refreshHooksDenySettings();
sendJson(response, 200, { ok: true, hooksDenyBypass: settings.hooksDenyBypass });
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
}
return;
}
if (request.method === "POST") {
try {
const body = await readJsonBody(request);
if (typeof body?.hooksDenyBypass !== "boolean") {
sendJson(response, 400, { ok: false, error: "hooksDenyBypass must be boolean" });
return;
}
const saved = core.setHooksDenySettings({ hooksDenyBypass: body.hooksDenyBypass });
sendJson(response, 200, { ok: true, hooksDenyBypass: saved.hooksDenyBypass });
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
}
return;
}
response.writeHead(405, { allow: "GET, POST" });
response.end();
},
}, "dsh-purge: hooks-deny");
registerPluginRoute({
kind: "exact",
path: "/dsh-purge/last-user",
@@ -1511,7 +1583,7 @@ function installWebServer(ctx, cfg) {
});
return;
}
if (incoming !== null) {
if (typeof incoming === "string" && core.normalizeOverride(incoming)) {
await core.saveOverrideContent(state.dsh_home, incoming);
}
const httpMulti = await core.applyPatchesAllHosts(core.ALL_PATCHES, {
@@ -1530,7 +1602,8 @@ function installWebServer(ctx, cfg) {
const summary = core.summarizeApplyReport(report);
const hostWritten =
core.allPatchHostsWritten(httpMulti.hosts) || core.hostCleanMarkersPresent(state.ai_base);
const complete = summary.failed.length === 0 && flash.ok === true && hostWritten;
const hookDenyRestoreFailed = (httpMulti.hookDenyRestoreFailed || []).length > 0;
const complete = summary.failed.length === 0 && flash.ok === true && hostWritten && !hookDenyRestoreFailed;
const sealedNow = core.desktopAsarStillSealed();
const promptReady = summary.failed.length > 0 && summary.failed.every((item) => item.status === "pattern_not_found");
if (flash.ok === true && (complete || promptReady) && hostWritten) {
+33
View File
@@ -299,6 +299,39 @@ export const POINT_STAGE_OVERRIDE = {
'boundary-physical': 'boundary', 'boundary-supply': 'boundary',
}
/**
* 得分点的短名:报告正文、索引表、链路表用它。
* 合并后的得分点全名太长,放不进表头;全名仍写在每条明细的「得分点」一行。
*/
export const POINT_SHORT_NAME = {
'domain-control': '域名控制',
'terminal-access': '终端权限',
'server-host': '服务器主机',
'db-credential': '数据库凭据',
'web-app': 'Web 应用',
'central-system': '集权系统',
'bigdata-system': '大数据系统',
'netdev': '网络设备',
'netdev-redirect': '网络重定向',
'netdev-implant': '网络设备植入',
'iiot': '工业互联网',
'cloud-platform': '云管理平台',
'iot-platform': '物联网平台',
'secdev': '安全设备',
'file-storage': '文件存储',
'ai-agent': '模型智能体',
'model-compute': '算力 / 知识库系统',
'model-data': '模型数据系统',
'computepower-admin': '算力基础设施',
'computepower-cards': '算力卡资源',
'boundary-logical': '进入逻辑隔离内网',
'boundary-strong': '进入强隔离内网',
'boundary-physical': '进入物理隔离内网',
'boundary-supply': '供应链 / 云服务通道',
'iot-corenet': '物联网打入核心网',
'core-system': '核心系统(旧口径)',
}
/**
* 自动推导一条得分属于哪个阶段(用户已确认:自动推导,允许显式覆盖):
* ① 显式 stage_code 优先
+1 -2
View File
@@ -39,8 +39,7 @@ export function makeRecoverMessage(text) {
role: "user",
content: [{ type: "text", text: body }],
source: {
kind: "plugin",
plugin: "dsh-purge",
kind: "dsh-purge",
form: "notice",
summary: "refusal-recover",
},