mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-27 17:40:22 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c711311c34 | ||
|
|
b8d9b4db9a | ||
|
|
c29d78b291 | ||
|
|
075839af86 | ||
|
|
0f91546cc0 | ||
|
|
10a597d6ff |
No files matched your search
@@ -129,8 +129,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
|
||||
const TARGETS = ["AGENTS.md", "CLAUDE.md"];
|
||||
const PATCH_GROUPS = [
|
||||
{ key: "prompt", ids: [1, 2, 3, 4, 5, 25, 26, 27, 28, 32, 43, 50, 53, 54] },
|
||||
{ key: "code", ids: [6, 7, 8, 42, 44, 45, 46, 51, 52] },
|
||||
{ key: "prompt", ids: [1, 2, 3, 4, 5, 25, 26, 28, 32, 43, 50, 53, 54] },
|
||||
{ key: "code", ids: [6, 7, 8, 42, 45, 46, 51, 52, 55, 56] },
|
||||
{ key: "engine", ids: [9, 10, 11, 12, 13, 14, 15, 16, 35] },
|
||||
{ key: "tools", ids: [17, 18, 19, 21, 22, 23, 24, 29, 30, 31, 33, 34, 36, 37, 48] },
|
||||
{ key: "compat", ids: [38, 39, 40] },
|
||||
@@ -191,12 +191,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"status.applied": "已应用",
|
||||
"status.pending": "待应用",
|
||||
"status.skipped": "跳过",
|
||||
"apply.hint": "待应用=原文还在。跳过=当前版本不需要或组件未安装,再点也不会变。",
|
||||
"apply.hint": "点应用会把提示词框里的全文写入并打补丁,不必再点保存。待应用=原文还在。跳过=当前版本不需要或组件未安装。",
|
||||
"warn.noRoot": "未定位到当前宿主的 @deepseek-ai,清洗不会生效。请完全退出后再打开本宿主,在本页点「应用」。桌面端安装目录可以是任意盘符,不要用官方 dsh 去清桌面端。",
|
||||
"warn.noRoot.desktop": "官方客户端的代码在 app.asar 里。点「应用」会解开并自动重启,不用另跑脚本。第三方 DSH Desktop 直接点「应用」。",
|
||||
"unpack.restarting": "补丁已写入。点「重启」后客户端会自己重新打开。",
|
||||
"restart.fullQuit": "正在重启,客户端会自己重新打开。",
|
||||
"warn.noInject": "默认只注入可编辑提示词。启用规则集后以规则集为主。两边都空会提示必须添加。Skill 不顶替提示词。",
|
||||
"warn.noInject": "官方始终用默认提示词。红队开了规则集就只用规则集;没开时用去掉 CTF 的默认提示词,再接红队操作。两边都空会提示必须添加。",
|
||||
"need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。",
|
||||
"btn.restoreInject": "恢复默认",
|
||||
"saved.restoreInject": "已填入默认提示词,点保存写入",
|
||||
@@ -351,7 +351,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"patch.24": "preset fetch 启用",
|
||||
"patch.25": "去掉官方默认身份(功能提示词不动)",
|
||||
"patch.26": "minimal:去掉默认身份并打开 inject",
|
||||
"patch.27": "dsh-liangshen(梁神):去掉默认身份(可选)",
|
||||
"patch.28": "dsh-liangshen(梁神):phase-1 保留注入段",
|
||||
"patch.29": "dsh-tool-web:外部 untrusted 拦截→可执行",
|
||||
"patch.30": "dsh-hooks-claude-code:deny→allow",
|
||||
@@ -367,7 +366,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"patch.40": "complete 预设仍保留注入",
|
||||
"patch.42": "设置页旧接口",
|
||||
"patch.43": "网页预设去掉默认身份",
|
||||
"patch.44": "压缩设置仍看本机范围",
|
||||
"patch.45": "官方桌面更新交接",
|
||||
"patch.46": "官方更新脚本只用英文",
|
||||
"patch.47": "OAuth 不再插入 Claude 身份",
|
||||
@@ -378,6 +376,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"patch.52": "会话日志默认不上传",
|
||||
"patch.53": "网页提示去掉禁止另开服务器",
|
||||
"patch.54": "交付物提示去掉多余禁止",
|
||||
"patch.55": "每一步替换第一条系统提示",
|
||||
"patch.56": "回退只藏被撤掉的那一轮",
|
||||
"status.unlocated": "未定位",
|
||||
"metric.unlocated": "还没定位到本机 Harness",
|
||||
"rewind.label": "回退",
|
||||
@@ -459,12 +459,12 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"status.applied": "Applied",
|
||||
"status.pending": "Pending",
|
||||
"status.skipped": "Skipped",
|
||||
"apply.hint": "Pending = original text still present. Skipped = not needed for this version or component not installed.",
|
||||
"apply.hint": "Apply writes the prompt in the box and the patches. A separate save is unnecessary. Pending = original text still present. Skipped = not needed for this version or the component is not installed.",
|
||||
"warn.noRoot": "Could not find this host’s @deepseek-ai tree, so Apply will not patch anything. Fully quit and reopen this host, then Apply here. Desktop may live on any drive; do not use official dsh to purge Desktop.",
|
||||
"warn.noRoot.desktop": "Official Harness keeps its code in app.asar. Apply unpacks it and restarts the app. Third-party DSH Desktop: just Apply.",
|
||||
"unpack.restarting": "Patches are written. Click Restart and the client opens again by itself.",
|
||||
"restart.fullQuit": "Restarting. The client will open again by itself.",
|
||||
"warn.noInject": "By default only the editable prompt is injected. An enabled rule set takes over. If both are empty you will be asked to add a prompt. Skills do not replace the prompt.",
|
||||
"warn.noInject": "Official mode always uses the default prompt. Red team uses only the active rule set; otherwise it uses the default prompt without the CTF section, then the red team steps. If both are empty you will be asked to add a prompt.",
|
||||
"need.prompt": "Both the prompt and the rule set are empty. Add a prompt, or enable a rule that has content.",
|
||||
"btn.restoreInject": "Reset default",
|
||||
"saved.restoreInject": "Default prompt loaded. Save to write.",
|
||||
@@ -619,7 +619,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"patch.24": "preset fetch on",
|
||||
"patch.25": "Strip official default identity (keep feature prompts)",
|
||||
"patch.26": "minimal: strip identity, open inject",
|
||||
"patch.27": "dsh-liangshen: strip default identity (optional)",
|
||||
"patch.28": "dsh-liangshen: keep inject in phase-1",
|
||||
"patch.29": "dsh-tool-web: untrusted framing → usable data",
|
||||
"patch.30": "dsh-hooks-claude-code: deny→allow",
|
||||
@@ -635,7 +634,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"patch.40": "Keep inject when a complete prompt is set",
|
||||
"patch.42": "Settings legacy API",
|
||||
"patch.43": "Strip identity from web presets",
|
||||
"patch.44": "Compaction keeps local scope",
|
||||
"patch.45": "Official desktop update handoff",
|
||||
"patch.46": "Official update script stays ASCII",
|
||||
"patch.47": "OAuth no longer inserts Claude identity",
|
||||
@@ -646,6 +644,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"patch.52": "Session log upload off by default",
|
||||
"patch.53": "Web prompt drops do-not-start",
|
||||
"patch.54": "Deliverable prompt drops extra prohibition",
|
||||
"patch.55": "Replace the first system prompt every step",
|
||||
"patch.56": "Rewind hides only the cut range",
|
||||
"status.unlocated": "Not located",
|
||||
"metric.unlocated": "This install was not found yet",
|
||||
"rewind.label": "Undo",
|
||||
@@ -1136,6 +1136,8 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
const [channel, setChannel] = useState("stable");
|
||||
const [pick, setPick] = useState({ stable: "", beta: "" });
|
||||
const actionTicket = useRef(0);
|
||||
const overrideRef = useRef("");
|
||||
overrideRef.current = override;
|
||||
|
||||
const syncPicks = (d) => {
|
||||
const versions = (d && d.versions) || [];
|
||||
@@ -1340,12 +1342,13 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
fetch("/dsh-purge/" + action, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(action === "apply" ? { content: override } : {}),
|
||||
body: JSON.stringify(action === "apply" ? { content: overrideRef.current } : {}),
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if (ticket !== actionTicket.current) return;
|
||||
const applyEmptyBlocked = action === "apply" && promptBoxEmpty(override) && (!d || d.injectSource !== "rule");
|
||||
const posted = action === "apply" ? overrideRef.current : override;
|
||||
const applyEmptyBlocked = action === "apply" && promptBoxEmpty(posted) && (!d || d.injectSource !== "rule");
|
||||
if (responseNeedsPrompt(d) || applyEmptyBlocked) {
|
||||
rejectNeedPrompt(tr);
|
||||
return;
|
||||
@@ -1420,7 +1423,7 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
run();
|
||||
return;
|
||||
}
|
||||
bothInjectEmpty(override).then((empty) => {
|
||||
bothInjectEmpty(overrideRef.current).then((empty) => {
|
||||
if (ticket !== actionTicket.current) return;
|
||||
if (empty) {
|
||||
rejectNeedPrompt(tr);
|
||||
@@ -1428,7 +1431,7 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
}
|
||||
run();
|
||||
});
|
||||
}, [loadAll, override, rejectNeedPrompt]);
|
||||
}, [loadAll, rejectNeedPrompt]);
|
||||
|
||||
const saveOverride = useCallback(() => {
|
||||
const tr = t;
|
||||
@@ -1440,12 +1443,12 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
fetch("/dsh-purge/override", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ content: override }),
|
||||
body: JSON.stringify({ content: overrideRef.current }),
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if (ticket !== actionTicket.current) return;
|
||||
if (!d.ok || responseNeedsPrompt(d) || (promptBoxEmpty(override) && d.injectSource !== "rule")) {
|
||||
if (!d.ok || responseNeedsPrompt(d) || (promptBoxEmpty(overrideRef.current) && d.injectSource !== "rule")) {
|
||||
rejectNeedPrompt(tr);
|
||||
return;
|
||||
}
|
||||
@@ -1460,7 +1463,7 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
if (ticket === actionTicket.current) setPatchBusy(false);
|
||||
});
|
||||
};
|
||||
bothInjectEmpty(override).then((empty) => {
|
||||
bothInjectEmpty(overrideRef.current).then((empty) => {
|
||||
if (ticket !== actionTicket.current) return;
|
||||
if (empty) {
|
||||
rejectNeedPrompt(tr);
|
||||
@@ -1468,10 +1471,11 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
}
|
||||
go();
|
||||
});
|
||||
}, [override, t, rejectNeedPrompt]);
|
||||
}, [t, rejectNeedPrompt]);
|
||||
|
||||
const restoreOverride = useCallback(() => {
|
||||
if (!defaultOverride) return;
|
||||
overrideRef.current = defaultOverride;
|
||||
setOverride(defaultOverride);
|
||||
setNotice({ kind: "ok", text: t("saved.restoreInject") });
|
||||
}, [defaultOverride, t]);
|
||||
@@ -1711,7 +1715,10 @@ body .dshp-dock:has(.dshp-root[data-theme="dusk"]) .dshp-dock-body .dshp-switch
|
||||
h("textarea", {
|
||||
className: "dshp-area",
|
||||
value: override,
|
||||
onChange: (e) => setOverride(e.target.value),
|
||||
onChange: (e) => {
|
||||
overrideRef.current = e.target.value;
|
||||
setOverride(e.target.value);
|
||||
},
|
||||
spellCheck: false,
|
||||
placeholder: "",
|
||||
}),
|
||||
@@ -7246,8 +7253,9 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert
|
||||
const text = String(value || "").trim();
|
||||
if (!text) return false;
|
||||
if (text === "redteam") return true;
|
||||
if (/红队/.test(text)) return true;
|
||||
if (/^red[\s_-]*team$/i.test(text)) return true;
|
||||
const label = text.replace(/不是红队/g, "").replace(/非红队/g, "");
|
||||
if (/红队/.test(label)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -7298,7 +7306,7 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert
|
||||
try {
|
||||
const labels = document.querySelectorAll("[class*='PfFEtG_label'], [title*='红队'], [title*='RedTeam']");
|
||||
for (const el of labels) {
|
||||
if (isRedteamPresetId(el.textContent) || /红队/.test(String(el.textContent || ""))) return true;
|
||||
if (isRedteamPresetId(el.textContent)) return true;
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return false;
|
||||
|
||||
+323
-51
@@ -11,7 +11,18 @@ import {
|
||||
revertHideConsoleFromBin,
|
||||
} from "./hide-console.js";
|
||||
import * as desktop from "./desktop.js";
|
||||
import { asarArchiveIsFile, extractAsar, hostFs, overlayAsarUnpacked, renameAsarAside } from "./extract-asar.js";
|
||||
import {
|
||||
asarArchiveIsFile,
|
||||
asarFileIdentity,
|
||||
commitExtractedDir,
|
||||
extractAsarToSide,
|
||||
shouldExtractAsar,
|
||||
hostFs,
|
||||
newestPreservedDir,
|
||||
overlayAsarUnpacked,
|
||||
renameAsarAside,
|
||||
restoreExtractedDir,
|
||||
} from "./extract-asar.js";
|
||||
import { adapterFor, detectSurface } from "./surface.js";
|
||||
import { openSlot } from "./table-read.js";
|
||||
|
||||
@@ -1626,22 +1637,95 @@ export function sealedAsarHandoff(input = {}) {
|
||||
return { exe, asar, swapAsar: true };
|
||||
}
|
||||
|
||||
/** 官方 app.asar 解开到 resources/app。点「应用」时调用,不要求用户先跑脚本。 */
|
||||
function unpackedAsarStampPath() {
|
||||
return path.join(findDshHome(), "dsh-purge", "unpacked-asar.json");
|
||||
}
|
||||
|
||||
export function readUnpackedAsarStamp() {
|
||||
try {
|
||||
const raw = JSON.parse(hostFs.readFileSync(unpackedAsarStampPath(), "utf8"));
|
||||
const size = Number(raw.size);
|
||||
const mtimeMs = Number(raw.mtimeMs);
|
||||
if (!Number.isFinite(size) || !Number.isFinite(mtimeMs)) return null;
|
||||
return { size, mtimeMs };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeUnpackedAsarStamp(identity) {
|
||||
if (!identity || !Number.isFinite(identity.size) || !Number.isFinite(identity.mtimeMs)) return;
|
||||
const fp = unpackedAsarStampPath();
|
||||
hostFs.mkdirSync(path.dirname(fp), { recursive: true });
|
||||
hostFs.writeFileSync(fp, `${JSON.stringify({ size: identity.size, mtimeMs: identity.mtimeMs })}\n`, "utf8");
|
||||
}
|
||||
|
||||
/** 目录已经在用、归档不在时,记住旁边 .bak 的大小和时间。同一份再出现就不重新解。 */
|
||||
export function rememberUnpackedArchive() {
|
||||
if (readUnpackedAsarStamp()) return;
|
||||
const exe = desktop.findDesktopAppExecutable();
|
||||
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return;
|
||||
const asar = desktop.appAsarPath(exe);
|
||||
if (!asar || asarArchiveIsFile(asar)) return;
|
||||
const ident = asarFileIdentity(`${asar}.bak`);
|
||||
if (ident) writeUnpackedAsarStamp(ident);
|
||||
}
|
||||
|
||||
/** 当前目录还不能当宿主时,把升级脚本或上一次换目录挪走的那一份放回去。能用的目录不动。 */
|
||||
function restoreUnusableExtract(appDir, prev) {
|
||||
if (aiBaseUnderAppDir(appDir)) return false;
|
||||
const saved = prev || newestPreservedDir(appDir);
|
||||
if (!saved) return false;
|
||||
return restoreExtractedDir(appDir, saved);
|
||||
}
|
||||
|
||||
/** 官方 app.asar 解开到 resources/app。目录已能用且归档没变时直接改文件,不重新解包。 */
|
||||
export async function openSealedDesktopHost(options = {}) {
|
||||
const handoff = sealedAsarHandoff();
|
||||
if (!handoff) return { aiBase: null, swapAsar: false };
|
||||
if (!handoff) return { aiBase: null, swapAsar: false, extracted: false, prev: "", appDir: "", archive: null };
|
||||
const appDir = desktop.appDirForExecutable(handoff.exe);
|
||||
let aiBase = options.forceExtract ? null : aiBaseUnderAppDir(appDir);
|
||||
if (!aiBase) {
|
||||
await extractAsar(handoff.asar, appDir);
|
||||
aiBase = aiBaseUnderAppDir(appDir);
|
||||
const archive = asarFileIdentity(handoff.asar);
|
||||
const recorded = readUnpackedAsarStamp();
|
||||
let aiBase = aiBaseUnderAppDir(appDir);
|
||||
const extract = shouldExtractAsar({
|
||||
usable: Boolean(aiBase),
|
||||
identity: archive,
|
||||
recorded,
|
||||
upgrade: options.upgrade === true,
|
||||
});
|
||||
let extracted = false;
|
||||
let prev = "";
|
||||
if (extract) {
|
||||
try {
|
||||
const side = extractAsarToSide(handoff.asar, appDir);
|
||||
overlayAsarUnpacked(handoff.asar, side.next);
|
||||
if (!aiBaseUnderAppDir(side.next)) {
|
||||
try { hostFs.rmSync(side.next, { recursive: true, force: true }); } catch { /* 半成品留在旁边,不覆盖正在用的目录 */ }
|
||||
throw new Error(`已解开 ${handoff.asar},但里面没有 @deepseek-ai`);
|
||||
}
|
||||
const committed = commitExtractedDir(appDir, side.next);
|
||||
prev = committed.prev || "";
|
||||
extracted = true;
|
||||
aiBase = aiBaseUnderAppDir(appDir);
|
||||
} catch (error) {
|
||||
try { restoreUnusableExtract(appDir, prev); } catch { /* 放回失败时旧目录仍留在旁边 */ }
|
||||
throw error;
|
||||
}
|
||||
} else if (aiBase) {
|
||||
overlayAsarUnpacked(handoff.asar, appDir);
|
||||
if (archive && !recorded) writeUnpackedAsarStamp(archive);
|
||||
}
|
||||
overlayAsarUnpacked(handoff.asar, appDir);
|
||||
if (!aiBase) {
|
||||
restoreUnusableExtract(appDir, prev);
|
||||
throw new Error(`已解开 ${handoff.asar},但 ${appDir} 下没有 @deepseek-ai`);
|
||||
}
|
||||
resetPathMemo();
|
||||
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar };
|
||||
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar, extracted, prev, appDir, archive: extracted ? archive : null };
|
||||
}
|
||||
|
||||
export function restoreSealedExtract(appDir, prev) {
|
||||
const saved = prev || newestPreservedDir(appDir);
|
||||
return restoreExtractedDir(appDir, saved);
|
||||
}
|
||||
|
||||
export function scheduleSealedDesktopRestart(handoff) {
|
||||
@@ -2056,22 +2140,6 @@ const PATCHES = [
|
||||
],
|
||||
markers: [' prefix: ""'],
|
||||
},
|
||||
{
|
||||
id: 44, name: "COMPACTION_INSTANT_SETTINGS_SCOPE", layer: "代码", layer_en: "Code",
|
||||
desc: "即时压缩网页端改用 configForms / compaction client uses configForms",
|
||||
file: "compaction-instant-client",
|
||||
replacements: [
|
||||
{
|
||||
pattern: 'var inject = ["slots", "locale", "connection", "remote", "settingsScope"];',
|
||||
replace: 'var inject = ["slots", "locale", "connection", "remote", "configForms"];',
|
||||
},
|
||||
{
|
||||
pattern: "var controller = new CardController(ctx.settingsScope.bind({ namespace: SETTINGS_NAMESPACE }), [",
|
||||
replace: "var controller = new CardController(ctx.configForms.get(SETTINGS_NAMESPACE), [",
|
||||
},
|
||||
],
|
||||
markers: ["ctx.configForms.get(SETTINGS_NAMESPACE)"],
|
||||
},
|
||||
{
|
||||
id: 5, name: "APPROVAL_NEVER_SENTENCE", layer: "提示词", layer_en: "Prompt",
|
||||
desc: "审批提示句限制 / approval sentence",
|
||||
@@ -2616,29 +2684,6 @@ const NEW_TOOL_PATCHES = [
|
||||
"personaPrefix: !!js process.env.DSH_SYSTEM_PROMPT ?? ''",
|
||||
],
|
||||
},
|
||||
{
|
||||
// 梁神 phase-1 只留 persona,滤掉 inject。
|
||||
id: 27, name: "LIANGSHEN_PERSONA_PURGE", layer: "提示词", layer_en: "Prompt",
|
||||
desc: "插件 dsh-liangshen(梁神):拒绝锁→可执行(可选) / @linxin666/dsh-liangshen",
|
||||
file: ["preset-liangshen", "preset-liangshen-pkg"],
|
||||
optional: true, // only when liangshen is installed; text drifts by version
|
||||
replacements: [
|
||||
{
|
||||
// 0.1.5 persona 不认 text,改写到 prefix。
|
||||
pattern: "name: '@deepseek-ai/dsh-persona'\n config:\n text:",
|
||||
replace: "name: '@deepseek-ai/dsh-persona'\n config:\n prefix:",
|
||||
},
|
||||
{
|
||||
pattern: "text: You are a helpful software engineer assistant.",
|
||||
replace: 'prefix: ""',
|
||||
},
|
||||
],
|
||||
markersAny: true,
|
||||
markers: [
|
||||
'prefix: ""',
|
||||
"[dsh-purge] identity stripped",
|
||||
],
|
||||
},
|
||||
{
|
||||
// phase-1 白名单放行 dsh-purge section。
|
||||
id: 28, name: "LIANGSHEN_PHASE1_KEEP_INJECT", layer: "提示词", layer_en: "Prompt",
|
||||
@@ -3592,6 +3637,212 @@ const NEW_TOOL_PATCHES = [
|
||||
],
|
||||
markers: ["[dsh-purge] deliverable prohibition removed"],
|
||||
},
|
||||
{
|
||||
id: 55,
|
||||
name: "SYSTEM_PROMPT_REPLACE_HEAD",
|
||||
layer: "代码",
|
||||
layer_en: "Code",
|
||||
desc: "每一步用当前整段系统提示替换第一条,避免旧提示被钉住 / replace the first system prompt every step",
|
||||
file: ["agent-loop"],
|
||||
replacements: [
|
||||
{
|
||||
pattern: 'inHistory: preparedCall?.systemPromptUpdate === "in-history",',
|
||||
replace: "inHistory: false, // [dsh-purge] system prompt replaces the first node",
|
||||
},
|
||||
],
|
||||
markers: ["[dsh-purge] system prompt replaces the first node"],
|
||||
},
|
||||
{
|
||||
id: 56,
|
||||
name: "REWIND_HIDE_CUT_ONLY",
|
||||
layer: "代码",
|
||||
layer_en: "Code",
|
||||
desc: "回退只藏被撤掉的那一轮 / rewind hides only the cut range",
|
||||
file: ["conversation-client"],
|
||||
optional: true,
|
||||
replacements: [
|
||||
{
|
||||
pattern:
|
||||
"\t\tfunction rewindVisibleEntries(entries) {\n" +
|
||||
"\t\t\tconst list = Array.isArray(entries) ? entries : [...entries];\n" +
|
||||
"\t\t\tlet latest = null;\n" +
|
||||
"\t\t\tfor (const entry of list) {\n" +
|
||||
"\t\t\t\tconst event = entry && entry.event;\n" +
|
||||
"\t\t\t\tif (!isRewindMarker(event)) continue;\n" +
|
||||
"\t\t\t\tif (latest === null || event.seq > latest.seq) latest = event;\n" +
|
||||
"\t\t\t}\n" +
|
||||
"\t\t\tif (latest === null) return list;\n" +
|
||||
"\t\t\tconst hidden = /* @__PURE__ */ new Set();\n" +
|
||||
"\t\t\tif (Array.isArray(latest.sourceEventSeqs)) {\n" +
|
||||
"\t\t\t\tfor (const seq of latest.sourceEventSeqs) hidden.add(seq);\n" +
|
||||
"\t\t\t}\n" +
|
||||
"\t\t\thidden.add(latest.seq);\n" +
|
||||
"\t\t\treturn list.filter((entry) => {\n" +
|
||||
"\t\t\t\tconst event = entry && entry.event;\n" +
|
||||
"\t\t\t\tif (!event || hidden.has(event.seq)) return false;\n" +
|
||||
"\t\t\t\tif (event.seq > latest.seq) return true;\n" +
|
||||
"\t\t\t\treturn event.type === \"system/message\";\n" +
|
||||
"\t\t\t});\n" +
|
||||
"\t\t}",
|
||||
replace:
|
||||
"\t\tfunction rewindVisibleEntries(entries) {\n" +
|
||||
"\t\t\tconst list = Array.isArray(entries) ? entries : [...entries];\n" +
|
||||
"\t\t\tconst hidden = /* @__PURE__ */ new Set();\n" +
|
||||
"\t\t\tfor (const entry of list) {\n" +
|
||||
"\t\t\t\tconst event = entry && entry.event;\n" +
|
||||
"\t\t\t\tif (!isRewindMarker(event)) continue;\n" +
|
||||
"\t\t\t\thidden.add(event.seq);\n" +
|
||||
"\t\t\t\tconst op = event.surfaceOp;\n" +
|
||||
"\t\t\t\tif (op && typeof op.startSeq === \"number\" && typeof op.endSeq === \"number\" && op.endSeq >= op.startSeq && op.endSeq - op.startSeq < 100000) {\n" +
|
||||
"\t\t\t\t\tfor (let seq = op.startSeq; seq <= op.endSeq; seq += 1) hidden.add(seq);\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tconst raw = event.sourceEventSeqs;\n" +
|
||||
"\t\t\t\tif (Array.isArray(raw)) {\n" +
|
||||
"\t\t\t\t\tfor (const row of raw) {\n" +
|
||||
"\t\t\t\t\t\tif (typeof row === \"number\") hidden.add(row);\n" +
|
||||
"\t\t\t\t\t\telse if (Array.isArray(row) && row.length === 2 && typeof row[0] === \"number\" && typeof row[1] === \"number\" && row[1] >= row[0] && row[1] - row[0] < 100000) {\n" +
|
||||
"\t\t\t\t\t\t\tfor (let seq = row[0]; seq <= row[1]; seq += 1) hidden.add(seq);\n" +
|
||||
"\t\t\t\t\t\t}\n" +
|
||||
"\t\t\t\t\t}\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tconst cutEnd = op && typeof op.endSeq === \"number\" ? op.endSeq : event.seq;\n" +
|
||||
"\t\t\t\tlet turnStart = null;\n" +
|
||||
"\t\t\t\tlet turnEnd = null;\n" +
|
||||
"\t\t\t\tfor (const row of list) {\n" +
|
||||
"\t\t\t\t\tconst ev = row && row.event;\n" +
|
||||
"\t\t\t\t\tif (!ev || ev.seq >= event.seq) continue;\n" +
|
||||
"\t\t\t\t\tif (ev.type === \"turn/start\") turnStart = ev.seq;\n" +
|
||||
"\t\t\t\t\tif (ev.type === \"turn/end\" && ev.seq >= cutEnd && turnEnd === null) turnEnd = ev.seq;\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tif (turnStart !== null) {\n" +
|
||||
"\t\t\t\t\tconst last = turnEnd === null ? event.seq : turnEnd;\n" +
|
||||
"\t\t\t\t\tfor (const row of list) {\n" +
|
||||
"\t\t\t\t\t\tconst ev = row && row.event;\n" +
|
||||
"\t\t\t\t\t\tif (!ev || ev.seq < turnStart || ev.seq > last) continue;\n" +
|
||||
"\t\t\t\t\t\tif (ev.type === \"system/message\") continue;\n" +
|
||||
"\t\t\t\t\t\thidden.add(ev.seq);\n" +
|
||||
"\t\t\t\t\t}\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t}\n" +
|
||||
"\t\t\tif (hidden.size === 0) return list;\n" +
|
||||
"\t\t\treturn list.filter((entry) => {\n" +
|
||||
"\t\t\t\tconst event = entry && entry.event;\n" +
|
||||
"\t\t\t\treturn !!event && !hidden.has(event.seq);\n" +
|
||||
"\t\t\t});\n" +
|
||||
"\t\t} // [dsh-purge] rewind hides only the cut range",
|
||||
},
|
||||
{
|
||||
pattern:
|
||||
"\t\t/**\n" +
|
||||
"\t\t* Session-owned incremental engine that assembles business Contexts from a\n" +
|
||||
"\t\t* contiguous Event window and materializes registered view snapshots.\n" +
|
||||
"\t\t*/\n" +
|
||||
"\t\tvar ConversationNodeAssembler = class {",
|
||||
replace:
|
||||
"\t\t/**\n" +
|
||||
"\t\t* Session-owned incremental engine that assembles business Contexts from a\n" +
|
||||
"\t\t* contiguous Event window and materializes registered view snapshots.\n" +
|
||||
"\t\t*/\n" +
|
||||
"\t\tfunction isRewindMarker(event) {\n" +
|
||||
"\t\t\tif (!event || event.type !== \"user/message\") return false;\n" +
|
||||
"\t\t\tconst id = event.data && event.data.id;\n" +
|
||||
"\t\t\tif (typeof id !== \"string\" || id.indexOf(\"rewind-\") !== 0) return false;\n" +
|
||||
"\t\t\tconst op = event.surfaceOp;\n" +
|
||||
"\t\t\treturn !!op && op !== \"append\" && op.op === \"replace\";\n" +
|
||||
"\t\t}\n" +
|
||||
"\t\tfunction rewindVisibleEntries(entries) {\n" +
|
||||
"\t\t\tconst list = Array.isArray(entries) ? entries : [...entries];\n" +
|
||||
"\t\t\tconst hidden = /* @__PURE__ */ new Set();\n" +
|
||||
"\t\t\tfor (const entry of list) {\n" +
|
||||
"\t\t\t\tconst event = entry && entry.event;\n" +
|
||||
"\t\t\t\tif (!isRewindMarker(event)) continue;\n" +
|
||||
"\t\t\t\thidden.add(event.seq);\n" +
|
||||
"\t\t\t\tconst op = event.surfaceOp;\n" +
|
||||
"\t\t\t\tif (op && typeof op.startSeq === \"number\" && typeof op.endSeq === \"number\" && op.endSeq >= op.startSeq && op.endSeq - op.startSeq < 100000) {\n" +
|
||||
"\t\t\t\t\tfor (let seq = op.startSeq; seq <= op.endSeq; seq += 1) hidden.add(seq);\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tconst raw = event.sourceEventSeqs;\n" +
|
||||
"\t\t\t\tif (Array.isArray(raw)) {\n" +
|
||||
"\t\t\t\t\tfor (const row of raw) {\n" +
|
||||
"\t\t\t\t\t\tif (typeof row === \"number\") hidden.add(row);\n" +
|
||||
"\t\t\t\t\t\telse if (Array.isArray(row) && row.length === 2 && typeof row[0] === \"number\" && typeof row[1] === \"number\" && row[1] >= row[0] && row[1] - row[0] < 100000) {\n" +
|
||||
"\t\t\t\t\t\t\tfor (let seq = row[0]; seq <= row[1]; seq += 1) hidden.add(seq);\n" +
|
||||
"\t\t\t\t\t\t}\n" +
|
||||
"\t\t\t\t\t}\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tconst cutEnd = op && typeof op.endSeq === \"number\" ? op.endSeq : event.seq;\n" +
|
||||
"\t\t\t\tlet turnStart = null;\n" +
|
||||
"\t\t\t\tlet turnEnd = null;\n" +
|
||||
"\t\t\t\tfor (const row of list) {\n" +
|
||||
"\t\t\t\t\tconst ev = row && row.event;\n" +
|
||||
"\t\t\t\t\tif (!ev || ev.seq >= event.seq) continue;\n" +
|
||||
"\t\t\t\t\tif (ev.type === \"turn/start\") turnStart = ev.seq;\n" +
|
||||
"\t\t\t\t\tif (ev.type === \"turn/end\" && ev.seq >= cutEnd && turnEnd === null) turnEnd = ev.seq;\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tif (turnStart !== null) {\n" +
|
||||
"\t\t\t\t\tconst last = turnEnd === null ? event.seq : turnEnd;\n" +
|
||||
"\t\t\t\t\tfor (const row of list) {\n" +
|
||||
"\t\t\t\t\t\tconst ev = row && row.event;\n" +
|
||||
"\t\t\t\t\t\tif (!ev || ev.seq < turnStart || ev.seq > last) continue;\n" +
|
||||
"\t\t\t\t\t\tif (ev.type === \"system/message\") continue;\n" +
|
||||
"\t\t\t\t\t\thidden.add(ev.seq);\n" +
|
||||
"\t\t\t\t\t}\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t}\n" +
|
||||
"\t\t\tif (hidden.size === 0) return list;\n" +
|
||||
"\t\t\treturn list.filter((entry) => {\n" +
|
||||
"\t\t\t\tconst event = entry && entry.event;\n" +
|
||||
"\t\t\t\treturn !!event && !hidden.has(event.seq);\n" +
|
||||
"\t\t\t});\n" +
|
||||
"\t\t} // [dsh-purge] rewind hides only the cut range\n" +
|
||||
"\t\tvar ConversationNodeAssembler = class {",
|
||||
},
|
||||
{
|
||||
pattern:
|
||||
"\t\t\treplaceWindow(entries, hasMore) {\n" +
|
||||
"\t\t\t\tthis.contexts.clear();",
|
||||
replace:
|
||||
"\t\t\treplaceWindow(entries, hasMore) {\n" +
|
||||
"\t\t\t\tentries = rewindVisibleEntries(entries);\n" +
|
||||
"\t\t\t\tthis.contexts.clear();",
|
||||
},
|
||||
],
|
||||
markers: ["[dsh-purge] rewind hides only the cut range"],
|
||||
},
|
||||
{
|
||||
id: 57,
|
||||
name: "DEEPSEEK_SYSTEM_ROLE",
|
||||
layer: "代码",
|
||||
layer_en: "Code",
|
||||
desc: "deepseek.com 的系统提示词固定走 system,思维链不动 / keep deepseek.com instructions on system",
|
||||
file: ["pi-ai-completions"],
|
||||
optional: true,
|
||||
skipIfMarked: true,
|
||||
replacements: [
|
||||
{
|
||||
pattern: 'const instructionRole = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";',
|
||||
replace: 'const instructionRole = model.reasoning && compat.supportsDeveloperRole && !String(model.baseUrl || "").toLowerCase().includes("deepseek.com") ? "developer" : "system"; // [dsh-purge] deepseek.com keeps system role',
|
||||
},
|
||||
],
|
||||
markers: ["[dsh-purge] deepseek.com keeps system role"],
|
||||
},
|
||||
{
|
||||
id: 58,
|
||||
name: "REWIND_SKIP_DERIVE",
|
||||
layer: "代码",
|
||||
layer_en: "Code",
|
||||
desc: "回退空标记不进模型请求 / rewind markers stay off the model transcript",
|
||||
file: ["session"],
|
||||
optional: true,
|
||||
skipIfMarked: true,
|
||||
replacements: [
|
||||
{
|
||||
pattern: '\t\tcase "user/message": return event.data;',
|
||||
replace: '\t\tcase "user/message":\n\t\t\tif (typeof event.data?.id === "string" && event.data.id.indexOf("rewind-") === 0) return null;\n\t\t\treturn event.data; // [dsh-purge] rewind markers stay off the model transcript',
|
||||
},
|
||||
],
|
||||
markers: ["[dsh-purge] rewind markers stay off the model transcript"],
|
||||
},
|
||||
];
|
||||
|
||||
export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES];
|
||||
@@ -4000,6 +4251,15 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
|
||||
"deliverables-prompt": allExisting([
|
||||
...nestedPkg(aiBase, "dsh-client-ui-deliverables", "lib", "index.js"),
|
||||
]),
|
||||
"session": allExisting([
|
||||
...nestedPkg(aiBase, "dsh-session", "lib", "index.js"),
|
||||
]),
|
||||
"agent-loop": allExisting([
|
||||
...nestedPkg(aiBase, "dsh-agent-loop", "lib", "index.js"),
|
||||
]),
|
||||
"conversation-client": allExisting([
|
||||
...nestedPkg(aiBase, "dsh-client-ui-conversation", "lib", "client.js"),
|
||||
]),
|
||||
};
|
||||
return filterTargetFiles(files);
|
||||
}
|
||||
@@ -5008,7 +5268,7 @@ export async function readOverrideForUi(dshHome) {
|
||||
}
|
||||
}
|
||||
const customized = await isUserCustomizedOverride(dshHome);
|
||||
const show = customized ? disk : defaultContent;
|
||||
const show = normalizeOverride(disk) ? disk : defaultContent;
|
||||
return {
|
||||
path: fp,
|
||||
exists,
|
||||
@@ -5020,11 +5280,10 @@ export async function readOverrideForUi(dshHome) {
|
||||
};
|
||||
}
|
||||
|
||||
/** 插件加载时同步落下默认提示词,避免第一轮 assemble 读到空文件。 */
|
||||
/** 插件加载时同步落下默认提示词,避免第一轮 assemble 读到空文件。磁盘是空的就写入,不管有没有点过保存。 */
|
||||
export function seedOverrideSync(dshHome) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
fs.mkdirSync(dshHome, { recursive: true });
|
||||
if (readOverrideStateSync(dshHome).customized === true) return "exists";
|
||||
let disk = "";
|
||||
try {
|
||||
if (fs.existsSync(fp)) disk = fs.readFileSync(fp, "utf8");
|
||||
@@ -5042,6 +5301,19 @@ export async function installOverride(dshHome, force = false) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
await fsp.mkdir(dshHome, { recursive: true });
|
||||
if (!force && await isUserCustomizedOverride(dshHome)) return "exists";
|
||||
if (!force && fs.existsSync(fp)) {
|
||||
let disk = "";
|
||||
try {
|
||||
disk = await loadText(fp);
|
||||
} catch {
|
||||
disk = "";
|
||||
}
|
||||
const bundled = defaultOverrideText();
|
||||
if (normalizeOverride(disk) && normalizeOverride(disk) !== normalizeOverride(bundled)) {
|
||||
await markOverrideCustomized(dshHome, true, disk);
|
||||
return "exists";
|
||||
}
|
||||
}
|
||||
const bundled = defaultOverrideText();
|
||||
if (!normalizeOverride(bundled)) return fs.existsSync(fp) ? "empty" : "missing";
|
||||
await fsp.writeFile(fp, bundled, "utf8");
|
||||
|
||||
@@ -120,6 +120,39 @@ export function asarArchiveIsFile(p) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 用大小和修改时间认出是不是同一份归档。 */
|
||||
export function asarFileIdentity(asarPath) {
|
||||
try {
|
||||
const st = archiveFs().statSync(asarPath);
|
||||
if (!st.isFile()) return null;
|
||||
return { size: st.size, mtimeMs: Math.round(st.mtimeMs) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function sameAsarIdentity(left, right) {
|
||||
return Boolean(
|
||||
left && right
|
||||
&& left.size === right.size
|
||||
&& left.mtimeMs === right.mtimeMs,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可用目录配同一份归档:不解包。
|
||||
* 目录不在,或记录过的归档大小/时间变了:解一次。
|
||||
* 升级标记碰上另一份归档,同样解一次。目录还在、又没记录过、也不是升级:先认这份归档,不解。
|
||||
*/
|
||||
export function shouldExtractAsar({ usable, identity, recorded, upgrade }) {
|
||||
if (!identity) return false;
|
||||
if (!usable) return true;
|
||||
const same = sameAsarIdentity(identity, recorded);
|
||||
if (upgrade && !same) return true;
|
||||
if (recorded && !same) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function readHeader(fd, afs) {
|
||||
const pre = Buffer.alloc(16);
|
||||
if (afs.readSync(fd, pre, 0, 16, 0) !== 16) throw new Error("asar header truncated");
|
||||
@@ -224,6 +257,91 @@ export function overlayAsarUnpacked(asarPath, destDir) {
|
||||
return { copied };
|
||||
}
|
||||
|
||||
function discardDir(dir) {
|
||||
if (!dir) return;
|
||||
try { diskFs().rmSync(dir, { recursive: true, force: true }); } catch { /* 残留目录下次再清 */ }
|
||||
}
|
||||
|
||||
/** 解到目标旁边的目录。失败时删掉半成品,不碰已经在用的那一份。 */
|
||||
export function extractAsarToSide(asarPath, destDir) {
|
||||
const next = `${destDir}.dshpurge-next`;
|
||||
discardDir(next);
|
||||
try {
|
||||
const count = extractAsar(asarPath, next);
|
||||
return { next, count };
|
||||
} catch (error) {
|
||||
discardDir(next);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** 解开完成之后才把旧目录挪走、新目录换上。换不上就把旧目录放回去。 */
|
||||
export function commitExtractedDir(destDir, nextDir) {
|
||||
const fs = diskFs();
|
||||
if (!nextDir || !fs.existsSync(nextDir)) throw new Error("解包目录不存在");
|
||||
let prev = "";
|
||||
if (fs.existsSync(destDir)) {
|
||||
prev = `${destDir}.dshpurge-prev`;
|
||||
if (fs.existsSync(prev)) prev = `${destDir}.dshpurge-prev-${Date.now()}`;
|
||||
fs.renameSync(destDir, prev);
|
||||
}
|
||||
try {
|
||||
fs.renameSync(nextDir, destDir);
|
||||
} catch (error) {
|
||||
if (prev && !fs.existsSync(destDir)) {
|
||||
try { fs.renameSync(prev, destDir); } catch { /* 调用方再试一次放回 */ }
|
||||
}
|
||||
discardDir(nextDir);
|
||||
throw error;
|
||||
}
|
||||
return { prev };
|
||||
}
|
||||
|
||||
/** 升级脚本事先挪走的旧目录。补丁没写完时用它放回去。 */
|
||||
export function newestPreservedDir(destDir) {
|
||||
const fs = diskFs();
|
||||
const parent = path.dirname(destDir);
|
||||
const prefix = `${path.basename(destDir)}.dshpurge-prev`;
|
||||
let names = [];
|
||||
try { names = fs.readdirSync(parent); } catch { return ""; }
|
||||
let best = "";
|
||||
let bestTime = -1;
|
||||
for (const name of names) {
|
||||
if (name !== prefix && !name.startsWith(`${prefix}-`)) continue;
|
||||
const full = path.join(parent, name);
|
||||
let time = 0;
|
||||
try { time = fs.statSync(full).mtimeMs; } catch { continue; }
|
||||
if (time >= bestTime) {
|
||||
best = full;
|
||||
bestTime = time;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** 补丁没写完时,把刚才挪走的旧目录放回原处。 */
|
||||
export function restoreExtractedDir(destDir, prev) {
|
||||
const fs = diskFs();
|
||||
if (!prev || !fs.existsSync(prev)) return false;
|
||||
let failed = "";
|
||||
if (fs.existsSync(destDir)) {
|
||||
failed = `${destDir}.dshpurge-failed-${Date.now()}`;
|
||||
fs.renameSync(destDir, failed);
|
||||
}
|
||||
try {
|
||||
fs.renameSync(prev, destDir);
|
||||
} catch (error) {
|
||||
if (failed && !fs.existsSync(destDir)) {
|
||||
try { fs.renameSync(failed, destDir); } catch { /* 旧目录仍在 prev */ }
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (failed) {
|
||||
try { fs.rmSync(failed, { recursive: true, force: true }); } catch { /* 坏目录留着不影响已放回的那一份 */ }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function extractAsar(asarPath, destDir) {
|
||||
const afs = archiveFs();
|
||||
const fd = afs.openSync(asarPath, "r");
|
||||
|
||||
+142
-18
@@ -98,6 +98,10 @@ function stripHarnessPersona(text) {
|
||||
/You are a coding agent powered by the \{\{model\}\} model\. Your working directory is \{\{cwd\}\}\.?\s*/g,
|
||||
"Working directory: {{cwd}}. ",
|
||||
)
|
||||
.replace(
|
||||
/The DeepSeek Harness implementation checkout is at [\s\S]*?Use this checkout only to inspect or extend DSH itself\.?\s*/g,
|
||||
"",
|
||||
)
|
||||
.replace(
|
||||
/You are a coding agent powered by the [^\n.]+ model, running on the DeepSeek Harness\.?\s*/g,
|
||||
"",
|
||||
@@ -140,19 +144,34 @@ function withoutRedteamPreset(sections) {
|
||||
});
|
||||
}
|
||||
|
||||
/** 每次组装都把提示词放到最前。已经嵌在后面的同一份正文拆出来,避免宿主段落挡在前面。 */
|
||||
const OWN_SERVER_MARK = "OWN SERVERS — EXACT LIST ONLY";
|
||||
|
||||
function injectNeedles(inject) {
|
||||
const text = String(inject || "").trim();
|
||||
if (!text) return [];
|
||||
const at = text.indexOf(OWN_SERVER_MARK);
|
||||
const base = at >= 0 ? text.slice(0, at).trim() : "";
|
||||
const needles = [text];
|
||||
if (base && base !== text) needles.push(base);
|
||||
return needles;
|
||||
}
|
||||
|
||||
/** 每次组装都把提示词放到最前。后面段落里的同一份正文拆掉,避免再拼一份。 */
|
||||
function leadWithInject(sections, inject) {
|
||||
const text = String(inject || "").trim();
|
||||
if (!text) return sections;
|
||||
const needles = injectNeedles(text);
|
||||
const rest = [];
|
||||
for (const section of sections) {
|
||||
if (!section || section.name === "dsh-purge") continue;
|
||||
const body = typeof section.text === "string" ? section.text : "";
|
||||
if (!body.includes(text)) {
|
||||
if (!needles.some((needle) => body.includes(needle))) {
|
||||
rest.push(section);
|
||||
continue;
|
||||
}
|
||||
const next = body.split(text).join("").replace(/\n{3,}/g, "\n\n").trim();
|
||||
let next = body;
|
||||
for (const needle of needles) next = next.split(needle).join("");
|
||||
next = next.replace(/\n{3,}/g, "\n\n").trim();
|
||||
if (!next) continue;
|
||||
rest.push({ ...section, text: next });
|
||||
}
|
||||
@@ -161,6 +180,8 @@ function leadWithInject(sections, inject) {
|
||||
|
||||
/** 红队预设里要留下来的操作说明起点。这句前面的「你是红队指挥」身份句丢掉。 */
|
||||
const REDTEAM_OPS_MARK = "## 运行环境前提";
|
||||
const REDTEAM_LEAD_IDENTITY = "## 你是谁、你不做什么";
|
||||
const REDTEAM_OPS_NOTE = "身份和规则以上面的提示词为准。下面只补充红队调度步骤,不改写上面的身份。";
|
||||
|
||||
function redteamOpsBody(text) {
|
||||
const raw = String(text || "");
|
||||
@@ -169,32 +190,94 @@ function redteamOpsBody(text) {
|
||||
return raw.slice(at).trim();
|
||||
}
|
||||
|
||||
/** prompt-inject.md 后部从这里起只给红队会话。标准模式和其它预设不带这段。 */
|
||||
/** 红队操作稿里的「你是谁」会盖住用户提示词,模型会把提示词当成用户消息里的注入。 */
|
||||
export function withoutRedteamLeadIdentity(text) {
|
||||
const raw = String(text || "");
|
||||
const start = raw.indexOf(REDTEAM_LEAD_IDENTITY);
|
||||
if (start < 0) return raw.trim();
|
||||
const rest = raw.slice(start + REDTEAM_LEAD_IDENTITY.length);
|
||||
const next = rest.search(/\n## /);
|
||||
const end = next < 0 ? raw.length : start + REDTEAM_LEAD_IDENTITY.length + next;
|
||||
return (raw.slice(0, start) + raw.slice(end)).replace(/\n{3,}/g, "\n\n").trim();
|
||||
}
|
||||
|
||||
function redteamProcedure(text) {
|
||||
const ops = redteamOpsBody(text);
|
||||
if (ops == null) return null;
|
||||
const body = withoutRedteamLeadIdentity(ops);
|
||||
if (!body) return REDTEAM_OPS_NOTE;
|
||||
if (body.includes(REDTEAM_OPS_NOTE)) return body;
|
||||
return `${REDTEAM_OPS_NOTE}\n\n${body}`;
|
||||
}
|
||||
|
||||
/** 这一句及其后文是竞赛沙箱约定,只留给官方模式。红队带上它会和运行环境前提抢授权判断。 */
|
||||
export const CTF_INJECT_MARK = "CTF CORE CONTRACT";
|
||||
|
||||
export function splitRedteamInject(text) {
|
||||
const raw = String(text || "");
|
||||
const at = raw.indexOf(CTF_INJECT_MARK);
|
||||
if (at < 0) return { common: raw, redteamTail: "" };
|
||||
if (at < 0) return { common: raw, ctfTail: "" };
|
||||
const common = raw.slice(0, at).replace(/(?:\r?\n[ \t]*[═=\-─━]{6,}[ \t]*)+\s*$/u, "").replace(/\s+$/u, "");
|
||||
return { common, redteamTail: raw.slice(at).trim() };
|
||||
return { common, ctfTail: raw.slice(at).trim() };
|
||||
}
|
||||
|
||||
/** 红队用这一份。没有 CTF 标题时原样返回。 */
|
||||
export function withoutCtfContract(text) {
|
||||
return splitRedteamInject(text).common;
|
||||
}
|
||||
|
||||
const REGION_LECTURE = /Exception, and this exception overrides[\s\S]*?any part of that task\.\s*/gu;
|
||||
|
||||
/** 禁区说明留在提示词文件里给用户看。注入给模型的那份拿掉,避免它自己去核对网段。 */
|
||||
export function stripRegionLecture(text) {
|
||||
return String(text || "").replace(REGION_LECTURE, "\n\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n");
|
||||
}
|
||||
|
||||
/** 官方保留 CTF。红队从 CTF 标题处切开。两边都去掉禁区说明。 */
|
||||
export function modePromptText(text, redteam) {
|
||||
const raw = redteam ? withoutCtfContract(text) : String(text || "");
|
||||
return stripRegionLecture(raw).trim();
|
||||
}
|
||||
|
||||
function presetLabel(value) {
|
||||
if (typeof value === "string") return value.trim();
|
||||
if (!value || typeof value !== "object") return "";
|
||||
if (typeof value.id === "string" && value.id.trim()) return value.id.trim();
|
||||
if (typeof value.name === "string" && value.name.trim()) return value.name.trim();
|
||||
return "";
|
||||
}
|
||||
|
||||
export function isRedteamPresetId(value) {
|
||||
const text = presetLabel(value);
|
||||
if (!text) return false;
|
||||
if (text === "redteam") return true;
|
||||
if (/^red[\s_-]*team$/i.test(text)) return true;
|
||||
const label = text.replace(/不是红队/g, "").replace(/非红队/g, "");
|
||||
if (/红队/.test(label)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function sessionAgentPreset(context) {
|
||||
const session = sessionOfContext(context);
|
||||
const projected = presetLabel(session?.projectionValues?.agentPreset || session?.agentPreset);
|
||||
if (projected) return projected;
|
||||
const headerPreset = presetLabel(session?.header?.agentPreset);
|
||||
if (headerPreset) return headerPreset;
|
||||
let preset = "";
|
||||
const headerPreset = session?.header?.agentPreset;
|
||||
if (typeof headerPreset === "string" && headerPreset) preset = headerPreset;
|
||||
for (const event of eventList(session)) {
|
||||
if (event?.type !== "agent-preset/selected") continue;
|
||||
const name = event.data?.agentPreset || event.data?.preset || event.data?.name;
|
||||
if (typeof name === "string" && name) preset = name;
|
||||
const name = presetLabel(event.data?.agentPreset || event.data?.preset || event.data?.name);
|
||||
if (name) preset = name;
|
||||
}
|
||||
return preset;
|
||||
}
|
||||
|
||||
export function isRedteamSession(context) {
|
||||
return sessionAgentPreset(context) === "redteam";
|
||||
const session = sessionForInject(context);
|
||||
if (session && session !== sessionOfContext(context)) {
|
||||
return isRedteamPresetId(sessionAgentPreset({ session }));
|
||||
}
|
||||
return isRedteamPresetId(sessionAgentPreset(context));
|
||||
}
|
||||
|
||||
function writePurgeSection(sections, inject) {
|
||||
@@ -223,9 +306,42 @@ function sessionOfContext(context) {
|
||||
return context?.agent?.session || context?.session || null;
|
||||
}
|
||||
|
||||
function inheritsParentPrompt(session) {
|
||||
const header = session?.header;
|
||||
if (!header?.parentSession) return false;
|
||||
return header.origin === "subagent" || (header.delegationDepth ?? 0) > 0;
|
||||
}
|
||||
|
||||
function parentSessionRecord(context, parentId) {
|
||||
const ctx = context?.agent?.ctx || context?.ctx;
|
||||
if (!ctx || !parentId) return null;
|
||||
try {
|
||||
const registry = ctx.agents || ctx.get?.("agents");
|
||||
const parent = registry?.get?.(parentId);
|
||||
if (parent?.session) return parent.session;
|
||||
} catch {
|
||||
/* 父会话不在这条注册表上时,用子会话自己的预设。 */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 子代理沿父会话走到主会话,注入和主会话同一份。 */
|
||||
export function sessionForInject(context) {
|
||||
let session = sessionOfContext(context);
|
||||
const seen = new Set();
|
||||
while (session && !seen.has(session)) {
|
||||
seen.add(session);
|
||||
if (!inheritsParentPrompt(session)) return session;
|
||||
const parent = parentSessionRecord(context, session.header.parentSession);
|
||||
if (!parent || parent === session) return session;
|
||||
session = parent;
|
||||
}
|
||||
return sessionOfContext(context);
|
||||
}
|
||||
|
||||
export function isRedteamSubagent(context) {
|
||||
const header = sessionOfContext(context)?.header;
|
||||
return header?.origin === "subagent" && header?.agentPreset === "redteam";
|
||||
return header?.origin === "subagent" && isRedteamSession(context);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -238,7 +354,7 @@ function attachInjectToRedteamPersona(sections, inject, roleText, cardText) {
|
||||
const role = typeof roleText === "string" ? roleText.trim() : "";
|
||||
const card = typeof cardText === "string" ? cardText.trim() : "";
|
||||
const next = sections.map((section) => {
|
||||
const ops = redteamOpsBody(section?.text);
|
||||
const ops = redteamProcedure(section?.text);
|
||||
if (ops == null) return section;
|
||||
attached = true;
|
||||
const parts = [];
|
||||
@@ -418,8 +534,6 @@ function foldInjectIntoPersona(sections, injectText) {
|
||||
return [{ name: "deployment:persona-prefix", text: inject, order }, ...out];
|
||||
}
|
||||
|
||||
const OWN_SERVER_MARK = "OWN SERVERS — EXACT LIST ONLY";
|
||||
|
||||
function withOwnServers(injectText) {
|
||||
const text = String(injectText || "").trim();
|
||||
if (!text) return text;
|
||||
@@ -454,8 +568,9 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
|
||||
}
|
||||
}
|
||||
|
||||
const injectText = withOwnServers(collectInjectText(purge, opts.fallbackInject));
|
||||
const redteam = isRedteamSession(opts.context);
|
||||
const rawInject = modePromptText(collectInjectText(purge, opts.fallbackInject), redteam);
|
||||
const injectText = withOwnServers(rawInject);
|
||||
// #29: 不要把上一条 system/message 全文钉回 sections。
|
||||
// 默认留下 dsh-purge 段。0.1.5 在 waterfall 之后若 complete:true,只认这段把注入抄进最终提示词;
|
||||
// 提前折进 persona 再删掉本段,重启加载该逻辑后注入会丢。
|
||||
@@ -463,9 +578,18 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
|
||||
const extras = withoutHardcodedExec(opts.dropPurgeAfterFold
|
||||
? purge.filter((section) => section.name !== "dsh-purge")
|
||||
: purge);
|
||||
let sections = [...folded, ...extras];
|
||||
let sections = [...folded, ...extras].map((section) => {
|
||||
if (!section || typeof section.text !== "string") return section;
|
||||
const cut = modePromptText(section.text, redteam);
|
||||
return cut === section.text ? section : { ...section, text: cut };
|
||||
});
|
||||
if (!redteam) sections = withoutRedteamPreset(sections);
|
||||
else sections = attachInjectToRedteamPersona(sections, injectText);
|
||||
else {
|
||||
const withOps = attachInjectToRedteamPersona(sections, injectText, opts.roleText, opts.cardText);
|
||||
sections = withOps === sections
|
||||
? insertRoleSection(insertCardSection(sections, opts.cardText), opts.roleText)
|
||||
: withOps;
|
||||
}
|
||||
assembled.sections = leadWithInject(sections, injectText);
|
||||
return assembled;
|
||||
}
|
||||
+38
-8
@@ -12,7 +12,7 @@ import {
|
||||
isRedteamSession,
|
||||
rewritePromptAssembly,
|
||||
} from "./identity.js";
|
||||
import { installSubagentRoleCapture } from "./redteam/role-section.js";
|
||||
import { installSubagentRoleCapture, resolveSubagentRoleText } from "./redteam/role-section.js";
|
||||
import * as rewind from "./rewind.js";
|
||||
import * as continueRetry from "./continue-retry.js";
|
||||
import * as uninstaller from "./uninstall.js";
|
||||
@@ -188,9 +188,9 @@ export function registerPromptSections(ctx, config, _injectFile) {
|
||||
name: "dsh-purge",
|
||||
order: GLOBAL_PROMPT_ORDER,
|
||||
interpolate: false,
|
||||
text: () => {
|
||||
text: (context) => {
|
||||
if (!injectAllowedNow(config)) return "";
|
||||
return rules.resolveInjectText(core.findDshHome()).text;
|
||||
return rules.resolveModeInject(core.findDshHome(), isRedteamSession(context));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -234,21 +234,31 @@ function installMnemonMessageStrip(ctx, config = {}) {
|
||||
|
||||
function rewriteLiveAssembly(config, assembled, context) {
|
||||
const enabled = config.enabled !== false;
|
||||
const redteam = enabled && isRedteamSession(context);
|
||||
const inject = enabled ? readInjectFallback(context) : "";
|
||||
return rewritePromptAssembly(assembled, {
|
||||
fallbackInject: inject,
|
||||
dropMnemon: config.stripMnemon !== false,
|
||||
dropPurgeAfterFold: false,
|
||||
context,
|
||||
roleText: redteam ? resolveSubagentRoleText(context) : "",
|
||||
});
|
||||
}
|
||||
|
||||
/** Cordis 的 ctx 是 Proxy:未声明 inject 时点属性会抛 "cannot get property ... without inject",所以两段都要包 try。 */
|
||||
function permissionPresetsOf(ctx) {
|
||||
if (ctx?.permissionPresets && typeof ctx.permissionPresets.set === "function") return ctx.permissionPresets;
|
||||
try {
|
||||
const direct = ctx?.permissionPresets;
|
||||
if (direct && typeof direct.set === "function") return direct;
|
||||
} catch {
|
||||
/* 未 inject 这项服务时,Cordis 代理会抛,不能让新会话的全开权限钉死失败。 */
|
||||
}
|
||||
try {
|
||||
const svc = ctx?.get?.("permissionPresets");
|
||||
if (svc && typeof svc.set === "function") return svc;
|
||||
} catch {}
|
||||
} catch {
|
||||
/* 没有这项服务。 */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -284,6 +294,24 @@ function installFreshFullAccess(ctx) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function installRewindDeriveFilter(ctx) {
|
||||
if (!ctx || ctx.__dshPurgeRewindDerive) return;
|
||||
ctx.__dshPurgeRewindDerive = true;
|
||||
const wrapOne = (session) => {
|
||||
try { rewind.wrapSessionDeriveMessages(session); } catch { /* ignore */ }
|
||||
};
|
||||
try {
|
||||
const store = ctx.get?.("sessions");
|
||||
const all = typeof store?.all === "function" ? store.all()
|
||||
: typeof store?.list === "function" ? store.list()
|
||||
: [];
|
||||
for (const session of all || []) wrapOne(session);
|
||||
} catch { /* ignore */ }
|
||||
try {
|
||||
ctx.on("session/created", (session) => wrapOne(session));
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
function installIdentityOverride(ctx, config = {}) {
|
||||
if (typeof ctx.on !== "function") return;
|
||||
installSubagentRoleCapture(ctx);
|
||||
@@ -318,13 +346,14 @@ function shimNeedsPatch(state) {
|
||||
}
|
||||
|
||||
async function settleInstalledPatches(config, ctx) {
|
||||
try { core.rememberUnpackedArchive(); } catch { /* 没有官方安装目录时不必记归档 */ }
|
||||
if (officialUpdate.upgradeMarkerExists(process.execPath)) {
|
||||
const upgraded = await reapply.reapplyInstalled({ scheduleSwap: false, forceExtract: true });
|
||||
officialUpdate.clearUpgradeMarker(process.execPath);
|
||||
const upgraded = await reapply.reapplyInstalled({ scheduleSwap: false, upgrade: true });
|
||||
if (!upgraded.ok) {
|
||||
log(config, "official upgrade reapply failed:", upgraded.error || "");
|
||||
return "reapply-failed";
|
||||
}
|
||||
officialUpdate.clearUpgradeMarker(process.execPath);
|
||||
officialUpdate.clearStaleExtractedApps(process.execPath);
|
||||
log(config, "official upgrade reapplied; restarting onto the new build");
|
||||
try {
|
||||
@@ -787,6 +816,7 @@ export function apply(ctx, config) {
|
||||
installIdentityOverride(ctx, cfg);
|
||||
installRegionGate(ctx);
|
||||
installFreshFullAccess(ctx);
|
||||
installRewindDeriveFilter(ctx);
|
||||
installMnemonMessageStrip(ctx, cfg);
|
||||
const injectFile = core.findOverrideFile(core.findDshHome());
|
||||
registerPromptSections(ctx, cfg, injectFile);
|
||||
@@ -1262,7 +1292,7 @@ function installWebServer(ctx, cfg) {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (typeof body?.content === "string") {
|
||||
if (typeof body?.content === "string" && core.normalizeOverride(body.content)) {
|
||||
await core.saveOverrideContent(state.dsh_home, body.content);
|
||||
}
|
||||
await core.backupAll(state.ai_base);
|
||||
|
||||
+482
-111
@@ -1,23 +1,96 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promises as dns } from "node:dns";
|
||||
import { findDshHome } from "./core.js";
|
||||
|
||||
const REGION_NAME = {
|
||||
CN: "中国大陆",
|
||||
HK: "香港",
|
||||
MO: "澳门",
|
||||
};
|
||||
|
||||
const SUFFIXES = [
|
||||
[".cn", "CN"],
|
||||
[".hk", "HK"],
|
||||
[".mo", "MO"],
|
||||
[".xn--fiqs8s", "CN"],
|
||||
[".xn--fiqz9s", "CN"],
|
||||
[".xn--j6w193g", "HK"],
|
||||
[".xn--mix082f", "MO"],
|
||||
[".xn--55qx5d", "CN"],
|
||||
[".xn--io0a7i", "CN"],
|
||||
[".xn--55qw42g", "CN"],
|
||||
[".xn--zfr164b", "CN"],
|
||||
[".xn--czru2d", "CN"],
|
||||
[".xn--hxt814e", "CN"],
|
||||
[".xn--fiq228c5hs", "CN"],
|
||||
[".xn--3bst00m", "CN"],
|
||||
[".xn--ses554g", "CN"],
|
||||
[".中国", "CN"],
|
||||
[".中國", "CN"],
|
||||
[".公司", "CN"],
|
||||
[".网络", "CN"],
|
||||
[".網絡", "CN"],
|
||||
[".公益", "CN"],
|
||||
[".政务", "CN"],
|
||||
[".商城", "CN"],
|
||||
[".网店", "CN"],
|
||||
[".中文网", "CN"],
|
||||
[".集团", "CN"],
|
||||
[".网址", "CN"],
|
||||
[".在线", "CN"],
|
||||
[".移动", "CN"],
|
||||
[".我爱你", "CN"],
|
||||
[".香港", "HK"],
|
||||
[".澳门", "MO"],
|
||||
[".澳門", "MO"],
|
||||
[".com.cn", "CN"],
|
||||
[".net.cn", "CN"],
|
||||
[".org.cn", "CN"],
|
||||
[".gov.cn", "CN"],
|
||||
[".edu.cn", "CN"],
|
||||
[".ac.cn", "CN"],
|
||||
[".mil.cn", "CN"],
|
||||
[".ah.cn", "CN"],
|
||||
[".bj.cn", "CN"],
|
||||
[".cq.cn", "CN"],
|
||||
[".fj.cn", "CN"],
|
||||
[".gd.cn", "CN"],
|
||||
[".gs.cn", "CN"],
|
||||
[".gx.cn", "CN"],
|
||||
[".gz.cn", "CN"],
|
||||
[".ha.cn", "CN"],
|
||||
[".hb.cn", "CN"],
|
||||
[".he.cn", "CN"],
|
||||
[".hi.cn", "CN"],
|
||||
[".hl.cn", "CN"],
|
||||
[".hn.cn", "CN"],
|
||||
[".jl.cn", "CN"],
|
||||
[".js.cn", "CN"],
|
||||
[".jx.cn", "CN"],
|
||||
[".ln.cn", "CN"],
|
||||
[".nm.cn", "CN"],
|
||||
[".nx.cn", "CN"],
|
||||
[".qh.cn", "CN"],
|
||||
[".sc.cn", "CN"],
|
||||
[".sd.cn", "CN"],
|
||||
[".sh.cn", "CN"],
|
||||
[".sn.cn", "CN"],
|
||||
[".sx.cn", "CN"],
|
||||
[".tj.cn", "CN"],
|
||||
[".xj.cn", "CN"],
|
||||
[".xz.cn", "CN"],
|
||||
[".yn.cn", "CN"],
|
||||
[".zj.cn", "CN"],
|
||||
[".hk.cn", "HK"],
|
||||
[".mo.cn", "MO"],
|
||||
[".cn", "CN"],
|
||||
[".com.hk", "HK"],
|
||||
[".edu.hk", "HK"],
|
||||
[".gov.hk", "HK"],
|
||||
[".idv.hk", "HK"],
|
||||
[".net.hk", "HK"],
|
||||
[".org.hk", "HK"],
|
||||
[".hk", "HK"],
|
||||
[".com.mo", "MO"],
|
||||
[".edu.mo", "MO"],
|
||||
[".gov.mo", "MO"],
|
||||
[".net.mo", "MO"],
|
||||
[".org.mo", "MO"],
|
||||
[".mo", "MO"],
|
||||
];
|
||||
|
||||
const FILE_SUFFIX = new Set([
|
||||
@@ -27,11 +100,6 @@ const FILE_SUFFIX = new Set([
|
||||
"ini", "bak", "patch", "diff", "sh", "ps1", "cmd", "exe",
|
||||
]);
|
||||
|
||||
const SKIP_KEYS = new Set([
|
||||
"content", "old_string", "new_string", "text", "patch", "code",
|
||||
"file_text", "body", "diff",
|
||||
]);
|
||||
|
||||
const ranges = loadRanges();
|
||||
const v4 = ranges.v4;
|
||||
const v6 = ranges.v6.map((row) => ({
|
||||
@@ -40,9 +108,70 @@ const v6 = ranges.v6.map((row) => ({
|
||||
region: row[2],
|
||||
})).filter((row) => row.value != null);
|
||||
|
||||
const lookupCache = new Map();
|
||||
const hostLookupCache = new Map();
|
||||
const LOOKUP_TTL_MS = 10 * 60 * 1000;
|
||||
const LOOKUP_LIMIT = 12;
|
||||
const LOOKUP_CONCURRENCY = 6;
|
||||
const DENIAL = "不行,这是严令禁止的";
|
||||
|
||||
const CF_V4 = [
|
||||
"173.245.48.0/20",
|
||||
"103.21.244.0/22",
|
||||
"103.22.200.0/22",
|
||||
"103.31.4.0/22",
|
||||
"141.101.64.0/18",
|
||||
"108.162.192.0/18",
|
||||
"190.93.240.0/20",
|
||||
"188.114.96.0/20",
|
||||
"197.234.240.0/22",
|
||||
"198.41.128.0/17",
|
||||
"162.158.0.0/15",
|
||||
"104.16.0.0/13",
|
||||
"104.24.0.0/14",
|
||||
"172.64.0.0/13",
|
||||
"131.0.72.0/22",
|
||||
];
|
||||
|
||||
const CF_V6 = [
|
||||
["2400:cb00::", 32],
|
||||
["2606:4700::", 32],
|
||||
["2803:f800::", 32],
|
||||
["2405:b500::", 32],
|
||||
["2405:8100::", 32],
|
||||
["2a06:98c0::", 29],
|
||||
["2c0f:f248::", 32],
|
||||
];
|
||||
|
||||
const VENDOR_NS = [
|
||||
"aliyun.com",
|
||||
"aliyuncs.com",
|
||||
"alibabadns.com",
|
||||
"alidns.com",
|
||||
"hichina.com",
|
||||
"dnspod.com",
|
||||
"dnspod.net",
|
||||
"dnsv1.com",
|
||||
"dnsv2.com",
|
||||
"dnsv3.com",
|
||||
"dnsv4.com",
|
||||
"dnsv5.com",
|
||||
"qcloud.com",
|
||||
"myqcloud.com",
|
||||
"tencent.com",
|
||||
"tencentcs.com",
|
||||
"huaweicloud.com",
|
||||
"hwclouds.com",
|
||||
"baidubce.com",
|
||||
"bdydns.com",
|
||||
"volces.com",
|
||||
"volcengine.com",
|
||||
"ctyun.cn",
|
||||
"ucloud.cn",
|
||||
"qingcloud.com",
|
||||
"ksyun.com",
|
||||
"jdcloud.com",
|
||||
];
|
||||
|
||||
const ATTACK = /渗透|攻击|打穿|打下|打站|入侵|拿下|拿壳|拿权限|爆破|提权|webshell|getshell|端口扫描|pentest|\bexploit\b|\battack\b|\bbreach\b|\bpwn\b/i;
|
||||
|
||||
function loadRanges() {
|
||||
try {
|
||||
@@ -167,6 +296,21 @@ function addHost(raw, hosts) {
|
||||
hosts.add(host);
|
||||
}
|
||||
|
||||
function inFilePath(sample, index) {
|
||||
const prev = sample[index - 1];
|
||||
return prev === "/" || prev === "\\";
|
||||
}
|
||||
|
||||
/** 网址里的主机照收。裸名字要像域名:路径片段、文件后缀、两段的 .mo 文件名丢掉。 */
|
||||
function keepBareDomain(sample, index, name) {
|
||||
if (inFilePath(sample, index)) return false;
|
||||
const labels = name.split(".");
|
||||
const tail = labels[labels.length - 1];
|
||||
if (FILE_SUFFIX.has(tail)) return false;
|
||||
if (labels.length === 2 && tail === "mo") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function collectFromText(text, hosts) {
|
||||
const sample = String(text || "").slice(0, 32768);
|
||||
const url = /\b(?:[a-z][a-z0-9+.-]*:\/\/)([^/?#\s]+)/gi;
|
||||
@@ -175,35 +319,14 @@ function collectFromText(text, hosts) {
|
||||
for (const match of sample.matchAll(ipv4)) hosts.add(match[0]);
|
||||
const ipv6 = /\b(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}\b/gi;
|
||||
for (const match of sample.matchAll(ipv6)) hosts.add(match[0]);
|
||||
if (/[\\/]/.test(sample)) return;
|
||||
const domain = /\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\b/gi;
|
||||
for (const match of sample.matchAll(domain)) {
|
||||
const name = match[0].toLowerCase();
|
||||
const tail = name.slice(name.lastIndexOf(".") + 1);
|
||||
if (FILE_SUFFIX.has(tail)) continue;
|
||||
if (!keepBareDomain(sample, match.index, name)) continue;
|
||||
hosts.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
function collect(value, key, hosts) {
|
||||
if (typeof value === "string") {
|
||||
if (SKIP_KEYS.has(String(key || "")) && value.length > 200) return;
|
||||
collectFromText(value, hosts);
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collect(item, key, hosts);
|
||||
return;
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
for (const [childKey, child] of Object.entries(value)) collect(child, childKey, hosts);
|
||||
}
|
||||
}
|
||||
|
||||
function blocked(label, region) {
|
||||
return { label, region, regionName: REGION_NAME[region] || region };
|
||||
}
|
||||
|
||||
async function addressesOf(host) {
|
||||
const found = [];
|
||||
const records = await Promise.race([
|
||||
@@ -232,23 +355,6 @@ async function addressesOf(host) {
|
||||
return found;
|
||||
}
|
||||
|
||||
async function regionOfResolved(host) {
|
||||
const now = Date.now();
|
||||
const cached = lookupCache.get(host);
|
||||
if (cached && now - cached.at < LOOKUP_TTL_MS) return cached.region;
|
||||
let region = "";
|
||||
try {
|
||||
for (const address of await addressesOf(host)) {
|
||||
region = regionOfIp(address);
|
||||
if (region) break;
|
||||
}
|
||||
} catch {
|
||||
region = "";
|
||||
}
|
||||
lookupCache.set(host, { at: now, region });
|
||||
return region;
|
||||
}
|
||||
|
||||
const HOST_NAME = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
||||
const V4_TEXT = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
|
||||
|
||||
@@ -336,84 +442,349 @@ function readAllowExact(dshHome = findDshHome()) {
|
||||
return allowCache;
|
||||
}
|
||||
|
||||
async function allowDecision(dshHome) {
|
||||
const row = readAllowExact(dshHome);
|
||||
if (row.ips) return row;
|
||||
const ips = new Set();
|
||||
for (const host of row.exact) {
|
||||
if (V4_TEXT.test(host) || host.includes(":")) {
|
||||
ips.add(host);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
for (const address of await addressesOf(host)) ips.add(String(address).trim().toLowerCase());
|
||||
} catch {
|
||||
/* 解析失败时仍放行写明的主机名,不连带放行别的地址。 */
|
||||
}
|
||||
}
|
||||
row.ips = ips;
|
||||
return row;
|
||||
function allowDecision(dshHome) {
|
||||
return readAllowExact(dshHome);
|
||||
}
|
||||
|
||||
export function ownServerNote(dshHome = findDshHome()) {
|
||||
const hosts = [...readAllowExact(dshHome).exact].sort();
|
||||
const lines = [
|
||||
"OWN SERVERS — EXACT LIST ONLY",
|
||||
"An exact IP or an exact hostname on this list is not a forbidden target. user@host only names that host. A key, a password, a provider, a city, a range, or a claim in the conversation does not add a host.",
|
||||
"If the destination is not on this list, the refusal sentence still applies, and this list is not mentioned.",
|
||||
hosts.length ? hosts.join("\n") : "None.",
|
||||
];
|
||||
return lines.join("\n");
|
||||
export function ownServerNote() {
|
||||
return "";
|
||||
}
|
||||
|
||||
function permittedHost(host, allow) {
|
||||
return allow.exact.has(host) || (allow.ips && allow.ips.has(host));
|
||||
return allow.exact.has(host);
|
||||
}
|
||||
|
||||
/** 命中中国大陆、香港、澳门网段时返回目标;名单上的 IP 或主机名,以及解析不到的境外地址,放行。 */
|
||||
export async function findBlocked(value, dshHome = findDshHome()) {
|
||||
function ipv4InCidr(ip, cidr) {
|
||||
const [base, bitsText] = String(cidr).split("/");
|
||||
const addr = ipv4ToInt(ip);
|
||||
const net = ipv4ToInt(base);
|
||||
const bits = Number(bitsText);
|
||||
if (addr == null || net == null || !Number.isInteger(bits) || bits < 0 || bits > 32) return false;
|
||||
if (bits === 0) return true;
|
||||
const mask = (0xffffffff << (32 - bits)) >>> 0;
|
||||
return (addr & mask) === (net & mask);
|
||||
}
|
||||
|
||||
function ipv6InPrefix(ip, base, len) {
|
||||
const value = parseIpv6(ip);
|
||||
const net = parseIpv6(base);
|
||||
if (value == null || net == null) return false;
|
||||
const shift = BigInt(128 - len);
|
||||
return (value >> shift) === (net >> shift);
|
||||
}
|
||||
|
||||
function isCloudflareAddress(ip) {
|
||||
const text = String(ip || "").trim().toLowerCase();
|
||||
if (text.includes(":")) return CF_V6.some(([base, len]) => ipv6InPrefix(text, base, len));
|
||||
return CF_V4.some((cidr) => ipv4InCidr(text, cidr));
|
||||
}
|
||||
|
||||
function isOwnNetwork(host) {
|
||||
const name = hostOf(host);
|
||||
if (!name) return false;
|
||||
if (name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local")) return true;
|
||||
if (name.includes(":")) {
|
||||
const value = parseIpv6(name);
|
||||
if (value == null) return false;
|
||||
if (value === 0n || value === 1n) return true;
|
||||
if ((value >> 118n) === 0x3fan) return true;
|
||||
if ((value >> 121n) === 0x7en) return true;
|
||||
return false;
|
||||
}
|
||||
const value = ipv4ToInt(name);
|
||||
return value != null && isSkippedV4(value);
|
||||
}
|
||||
|
||||
function isIp(host) {
|
||||
return V4_TEXT.test(host) || host.includes(":");
|
||||
}
|
||||
|
||||
function nsHit(nameservers, suffixes) {
|
||||
for (const raw of nameservers || []) {
|
||||
const name = String(raw || "").trim().toLowerCase().replace(/\.$/, "");
|
||||
if (!name) continue;
|
||||
if (suffixes.some((suffix) => name === suffix || name.endsWith(`.${suffix}`))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function coveredByCloudflare(addresses, nameservers) {
|
||||
if (nsHit(nameservers, ["cloudflare.com"])) return true;
|
||||
const pub = (addresses || []).map((item) => String(item || "").trim()).filter((item) => item && !isOwnNetwork(item));
|
||||
return pub.length > 0 && pub.every(isCloudflareAddress);
|
||||
}
|
||||
|
||||
function taskHit(label, kind) {
|
||||
return { label, kind };
|
||||
}
|
||||
|
||||
/** 纯判断:后缀优先,Cloudflare 只放过还没被后缀命中的名字。厂商看 NS,也看地址的反向名字。 */
|
||||
export function decisionFromLookup({ host, addresses = [], nameservers = [], pointers = [] } = {}) {
|
||||
const name = hostOf(host);
|
||||
if (!name || isOwnNetwork(name)) return null;
|
||||
if (regionOfSuffix(name)) return taskHit(name, "domain");
|
||||
if (isIp(name)) return regionOfIp(name) ? taskHit(name, "range") : null;
|
||||
if (coveredByCloudflare(addresses, nameservers)) return null;
|
||||
for (const address of addresses) {
|
||||
if (regionOfIp(address)) return taskHit(name, "range");
|
||||
}
|
||||
if (nsHit(nameservers, VENDOR_NS) || nsHit(pointers, VENDOR_NS)) return taskHit(name, "server");
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isAttackTask(text) {
|
||||
return ATTACK.test(String(text || ""));
|
||||
}
|
||||
|
||||
function hostsInTask(text) {
|
||||
const hosts = new Set();
|
||||
collect(value, "", hosts);
|
||||
const allow = await allowDecision(dshHome);
|
||||
const sample = String(text || "").slice(0, 32768);
|
||||
collectFromText(sample, hosts);
|
||||
const labeled = /(?:[a-z0-9\u00a1-\uffff](?:[a-z0-9\u00a1-\uffff-]{0,61}[a-z0-9\u00a1-\uffff])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59}|[\u4e00-\u9fff]{2,12})/giu;
|
||||
for (const match of sample.matchAll(labeled)) {
|
||||
const name = match[0].toLowerCase().replace(/\.$/, "");
|
||||
if (!keepBareDomain(sample, match.index, name)) continue;
|
||||
addHost(name, hosts);
|
||||
}
|
||||
return hosts;
|
||||
}
|
||||
|
||||
async function pointersOf(addresses) {
|
||||
const names = [];
|
||||
const list = [];
|
||||
const seen = new Set();
|
||||
for (const raw of addresses || []) {
|
||||
const address = String(raw || "").trim().toLowerCase();
|
||||
if (!address || seen.has(address) || isOwnNetwork(address)) continue;
|
||||
seen.add(address);
|
||||
list.push(address);
|
||||
if (list.length >= 4) break;
|
||||
}
|
||||
await Promise.all(list.map(async (address) => {
|
||||
try {
|
||||
const rows = await Promise.race([
|
||||
dns.reverse(address).catch(() => []),
|
||||
new Promise((resolve) => setTimeout(() => resolve([]), 1500)),
|
||||
]);
|
||||
if (!Array.isArray(rows)) return;
|
||||
for (const row of rows) {
|
||||
const name = String(row || "").trim().toLowerCase().replace(/\.$/, "");
|
||||
if (name) names.push(name);
|
||||
}
|
||||
} catch {
|
||||
/* 反向解析失败不当成命中。 */
|
||||
}
|
||||
}));
|
||||
return names;
|
||||
}
|
||||
|
||||
async function firstHit(items, worker) {
|
||||
const list = Array.isArray(items) ? items : [];
|
||||
if (!list.length) return null;
|
||||
let cursor = 0;
|
||||
let found = null;
|
||||
const width = Math.min(LOOKUP_CONCURRENCY, list.length);
|
||||
const run = async () => {
|
||||
while (found == null && cursor < list.length) {
|
||||
const host = list[cursor];
|
||||
cursor += 1;
|
||||
const hit = await worker(host);
|
||||
if (hit && found == null) found = hit;
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: width }, () => run()));
|
||||
return found;
|
||||
}
|
||||
|
||||
async function nameserversOf(host) {
|
||||
const records = await Promise.race([
|
||||
dns.resolveNs(host).catch(() => []),
|
||||
new Promise((resolve) => setTimeout(() => resolve([]), 1500)),
|
||||
]);
|
||||
return Array.isArray(records) ? records.map((item) => String(item).trim().toLowerCase()) : [];
|
||||
}
|
||||
|
||||
async function lookupHost(host) {
|
||||
const now = Date.now();
|
||||
const cached = hostLookupCache.get(host);
|
||||
if (cached && now - cached.at < LOOKUP_TTL_MS) return cached.lookup;
|
||||
const lookup = { addresses: [], nameservers: [], pointers: [] };
|
||||
try {
|
||||
lookup.addresses = await addressesOf(host);
|
||||
} catch {
|
||||
lookup.addresses = [];
|
||||
}
|
||||
try {
|
||||
lookup.nameservers = await nameserversOf(host);
|
||||
} catch {
|
||||
lookup.nameservers = [];
|
||||
}
|
||||
if (lookup.addresses.length && !coveredByCloudflare(lookup.addresses, lookup.nameservers)) {
|
||||
lookup.pointers = await pointersOf(lookup.addresses);
|
||||
}
|
||||
if (lookup.addresses.length || lookup.nameservers.length || lookup.pointers.length) {
|
||||
hostLookupCache.set(host, { at: now, lookup });
|
||||
}
|
||||
return lookup;
|
||||
}
|
||||
|
||||
export async function classifyHost(host, dshHome = findDshHome()) {
|
||||
const name = hostOf(host);
|
||||
if (!name) return null;
|
||||
const allow = allowDecision(dshHome);
|
||||
if (permittedHost(name, allow)) return null;
|
||||
if (isOwnNetwork(name) || regionOfSuffix(name) || isIp(name)) {
|
||||
return decisionFromLookup({ host: name });
|
||||
}
|
||||
const looked = await lookupHost(name);
|
||||
return decisionFromLookup({
|
||||
host: name,
|
||||
addresses: looked.addresses,
|
||||
nameservers: looked.nameservers,
|
||||
pointers: looked.pointers,
|
||||
});
|
||||
}
|
||||
|
||||
export async function taskTargetHit(text, dshHome = findDshHome()) {
|
||||
if (!isAttackTask(text)) return null;
|
||||
const allow = allowDecision(dshHome);
|
||||
const pending = [];
|
||||
for (const host of hosts) {
|
||||
if (permittedHost(host, allow)) continue;
|
||||
const suffix = regionOfSuffix(host);
|
||||
if (suffix) return blocked(host, suffix);
|
||||
const ip = regionOfIp(host);
|
||||
if (ip) return blocked(host, ip);
|
||||
if (host.includes(".") && !V4_TEXT.test(host) && !host.includes(":")) {
|
||||
pending.push(host);
|
||||
for (const host of hostsInTask(text)) {
|
||||
const name = hostOf(host);
|
||||
if (!name || permittedHost(name, allow) || isOwnNetwork(name)) continue;
|
||||
if (regionOfSuffix(name)) return taskHit(name, "domain");
|
||||
if (isIp(name)) {
|
||||
if (regionOfIp(name)) return taskHit(name, "range");
|
||||
continue;
|
||||
}
|
||||
pending.push(name);
|
||||
}
|
||||
return firstHit(pending, (host) => classifyHost(host, dshHome));
|
||||
}
|
||||
|
||||
function messageBody(message) {
|
||||
if (typeof message?.content === "string") return message.content;
|
||||
if (!Array.isArray(message?.content)) return typeof message?.text === "string" ? message.text : "";
|
||||
return message.content.map((block) => {
|
||||
if (typeof block === "string") return block;
|
||||
if (block && block.type === "text" && typeof block.text === "string") return block.text;
|
||||
return "";
|
||||
}).join("\n");
|
||||
}
|
||||
|
||||
function humanTaskText(message) {
|
||||
if (!message || typeof message !== "object") return "";
|
||||
if (message.role && message.role !== "user") return "";
|
||||
const kind = message.source?.kind;
|
||||
if (kind && kind !== "user") return "";
|
||||
const text = messageBody(message);
|
||||
if (/^\s*Current runtime context\b/i.test(text)) return "";
|
||||
return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "\n").trim();
|
||||
}
|
||||
|
||||
function sessionOf(payload) {
|
||||
const agent = payload?.agent;
|
||||
if (agent?.session && typeof agent.session.append === "function") return agent.session;
|
||||
if (payload?.session && typeof payload.session.append === "function") return payload.session;
|
||||
return null;
|
||||
}
|
||||
|
||||
async function denialMessage() {
|
||||
try {
|
||||
const mod = await import("@deepseek-ai/dsh-llm");
|
||||
if (typeof mod.createAssistantMessage === "function") {
|
||||
return mod.createAssistantMessage({
|
||||
content: [{ type: "text", text: DENIAL }],
|
||||
source: { provider: "dsh-purge", model: "task-gate" },
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
/* 宿主包不在这条导入路径上时用手写消息。 */
|
||||
}
|
||||
return {
|
||||
id: randomUUID(),
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: DENIAL }],
|
||||
source: { kind: "model", provider: "dsh-purge", model: "task-gate" },
|
||||
};
|
||||
}
|
||||
|
||||
function denialStream() {
|
||||
return [
|
||||
{ type: "block-start", index: 0, blockType: "text" },
|
||||
{ type: "text-delta", index: 0, text: DENIAL },
|
||||
{ type: "block-end", index: 0, block: { type: "text", text: DENIAL } },
|
||||
{ type: "finish", reason: "stop" },
|
||||
];
|
||||
}
|
||||
|
||||
async function appendDenial(session, turn, step) {
|
||||
session.append("assistant/message", {
|
||||
turn,
|
||||
step,
|
||||
message: await denialMessage(),
|
||||
stream: denialStream(),
|
||||
}, { surfaceOp: "append" });
|
||||
}
|
||||
|
||||
async function parkDenial(payload) {
|
||||
const session = sessionOf(payload);
|
||||
const turn = Number(payload?.turn);
|
||||
const step = Number(payload?.step);
|
||||
if (!session || !Number.isSafeInteger(turn) || step !== 1) return false;
|
||||
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
|
||||
let opened = false;
|
||||
try {
|
||||
for (const message of messages) {
|
||||
session.append("user/message", message, { surfaceOp: "append" });
|
||||
}
|
||||
session.append("step/start", { turn, step });
|
||||
opened = true;
|
||||
await appendDenial(session, turn, step);
|
||||
session.append("step/end", { turn, step });
|
||||
return true;
|
||||
} catch {
|
||||
try {
|
||||
if (!opened) session.append("step/start", { turn, step });
|
||||
await appendDenial(session, turn, step);
|
||||
session.append("step/end", { turn, step });
|
||||
return true;
|
||||
} catch {
|
||||
if (opened) {
|
||||
try { session.append("step/end", { turn, step }); } catch { /* 步已经合不上时,交给宿主收尾。 */ }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const batch = pending.slice(0, LOOKUP_LIMIT);
|
||||
const resolved = await Promise.all(batch.map((host) => regionOfResolved(host)));
|
||||
for (let i = 0; i < batch.length; i += 1) {
|
||||
if (resolved[i]) return blocked(batch[i], resolved[i]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function installRegionGate(ctx) {
|
||||
if (!ctx || typeof ctx.on !== "function") return;
|
||||
const hook = async (exec, next) => {
|
||||
const hook = async (payload, next) => {
|
||||
const forward = () => (typeof next === "function" ? next() : { kind: "enter", messages: payload?.messages || [] });
|
||||
if (Number(payload?.step) !== 1) return forward();
|
||||
let hit = null;
|
||||
try {
|
||||
const hit = await findBlocked(exec?.arguments);
|
||||
if (hit) {
|
||||
return {
|
||||
kind: "deny",
|
||||
reason: "不行,这是严令禁止的",
|
||||
};
|
||||
}
|
||||
const messages = Array.isArray(payload?.messages) ? payload.messages : [];
|
||||
const task = messages.map(humanTaskText).filter(Boolean).join("\n");
|
||||
if (!task || !isAttackTask(task)) return forward();
|
||||
hit = await taskTargetHit(task);
|
||||
} catch {
|
||||
return next();
|
||||
return forward();
|
||||
}
|
||||
return next();
|
||||
if (!hit) return forward();
|
||||
try {
|
||||
const parked = await parkDenial(payload);
|
||||
if (parked) return { kind: "enter", messages: [] };
|
||||
} catch {
|
||||
/* 禁止句没写上时不能把这一轮收成空白。 */
|
||||
}
|
||||
return forward();
|
||||
};
|
||||
const arm = () => {
|
||||
if (ctx.__dshPurgeRegionGate) return;
|
||||
try {
|
||||
ctx.on("tools/pre-execute", hook, { global: true, prepend: true });
|
||||
ctx.on("agent/pre-step", hook, { global: true, prepend: true });
|
||||
ctx.__dshPurgeRegionGate = true;
|
||||
} catch {
|
||||
/* 宿主还没有这条事件时,下一拍再挂。 */
|
||||
|
||||
+28
-6
@@ -77,33 +77,55 @@ export async function reapplyInstalled(options = {}) {
|
||||
core.applyRuntimeEnv();
|
||||
let aiBase = null;
|
||||
let handoff = null;
|
||||
let freshExtract = null;
|
||||
try {
|
||||
const state = await core.gatherState();
|
||||
aiBase = state.ai_base;
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e) };
|
||||
}
|
||||
if (!aiBase || options.forceExtract === true) {
|
||||
const sealed = core.sealedAsarHandoff();
|
||||
if (!aiBase || sealed) {
|
||||
try {
|
||||
const opened = await core.openSealedDesktopHost({ forceExtract: options.forceExtract === true });
|
||||
const opened = await core.openSealedDesktopHost({ upgrade: options.upgrade === true });
|
||||
if (opened.aiBase) aiBase = opened.aiBase;
|
||||
if (opened.swapAsar) handoff = opened;
|
||||
if (opened.extracted) freshExtract = opened;
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e) };
|
||||
}
|
||||
} else {
|
||||
handoff = core.sealedAsarHandoff();
|
||||
core.rememberUnpackedArchive();
|
||||
}
|
||||
if (!aiBase) return { ok: false, error: core.missingAiBaseMessage() };
|
||||
const reverted = await core.revertAll(aiBase);
|
||||
await core.revertAllShims();
|
||||
// 刚解开的是官方原件。已经在用的目录仍先还原再按这一版重打。
|
||||
const reverted = freshExtract ? { reverted: [] } : await core.revertAll(aiBase);
|
||||
if (!freshExtract) await core.revertAllShims();
|
||||
await core.backupAll(aiBase);
|
||||
const report = await core.applyPatches(aiBase);
|
||||
await core.patchAllShims();
|
||||
const flash = core.silenceCmdFlash(aiBase);
|
||||
const summary = core.summarizeApplyReport(report);
|
||||
const clean = summary.failed.length === 0 && flash.ok === true && core.hostCleanMarkersPresent(aiBase);
|
||||
if (clean) writeAppliedStamp(installedRev());
|
||||
if (!clean && freshExtract) {
|
||||
const restored = core.restoreSealedExtract(freshExtract.appDir, freshExtract.prev);
|
||||
return {
|
||||
ok: false,
|
||||
error: restored ? "清洗没有完成,已放回上一份解开目录" : "清洗没有完成",
|
||||
restored,
|
||||
version: pluginVersion(),
|
||||
reverted: 0,
|
||||
applied: summary.applied || 0,
|
||||
failed: summary.failed.length,
|
||||
renamed: false,
|
||||
needsFullQuit: false,
|
||||
cmdFlashOk: flash.ok === true,
|
||||
};
|
||||
}
|
||||
if (clean) {
|
||||
writeAppliedStamp(installedRev());
|
||||
if (freshExtract?.archive) core.writeUnpackedAsarStamp(freshExtract.archive);
|
||||
}
|
||||
let renamed = false;
|
||||
if (clean && handoff?.asar && options.scheduleSwap !== false) {
|
||||
const swapped = core.scheduleSealedDesktopRestart(handoff);
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { isRedteamSession } from '../identity.js'
|
||||
import { redteamRoot } from './platform-config.js'
|
||||
|
||||
const ROLE_TAG = /^[ \t]*redteamRole:[ \t]*(recon|assess|vuln-scan|exploit|internal)[ \t]*$/im
|
||||
@@ -33,15 +34,16 @@ function remember(agent, role) {
|
||||
for (const id of ids) roleBySession.set(String(id), role)
|
||||
}
|
||||
|
||||
function isRedteamChild(session) {
|
||||
function isRedteamChild(session, agent) {
|
||||
const header = session?.header
|
||||
return header?.origin === 'subagent' && header?.agentPreset === 'redteam'
|
||||
if (header?.origin !== 'subagent' && !((header?.delegationDepth ?? 0) > 0)) return false
|
||||
return isRedteamSession({ session, agent: agent ? { ...agent, session } : { session } })
|
||||
}
|
||||
|
||||
export function noteClaimedMessage(payload) {
|
||||
const agent = payload?.agent
|
||||
const session = agent?.session
|
||||
if (!isRedteamChild(session)) return
|
||||
if (!isRedteamChild(session, agent)) return
|
||||
const role = parseRedteamRole(textOfMessage(payload?.message))
|
||||
if (!role) return
|
||||
remember(agent, role)
|
||||
@@ -99,9 +101,9 @@ function readRoleFile(engagementId, role) {
|
||||
|
||||
export function resolveSubagentRoleText(context) {
|
||||
try {
|
||||
const session = context?.agent?.session || context?.session
|
||||
if (!isRedteamChild(session)) return ''
|
||||
const agent = context?.agent
|
||||
const session = agent?.session || context?.session
|
||||
if (!isRedteamChild(session, agent)) return ''
|
||||
const sessionId = session?.id ?? agent?.id
|
||||
let role = sessionId !== undefined && sessionId !== null
|
||||
? roleBySession.get(String(sessionId)) || ''
|
||||
|
||||
+89
-32
@@ -116,20 +116,23 @@ export function pendingInboxInserts(events) {
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function lastTurnSubagentIds(events) {
|
||||
export function lastTurnSubagentIds(events, fromSeq = -1) {
|
||||
const list = Array.isArray(events) ? events : [];
|
||||
let lastStart = -1;
|
||||
for (let i = list.length - 1; i >= 0; i -= 1) {
|
||||
if (list[i]?.type === "turn/start") {
|
||||
lastStart = list[i].seq;
|
||||
break;
|
||||
let floor = Number(fromSeq);
|
||||
if (!Number.isFinite(floor) || floor < 0) {
|
||||
floor = -1;
|
||||
for (let i = list.length - 1; i >= 0; i -= 1) {
|
||||
if (list[i]?.type === "turn/start") {
|
||||
floor = list[i].seq;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lastStart < 0) return [];
|
||||
if (floor < 0) return [];
|
||||
const ids = [];
|
||||
const seen = new Set();
|
||||
for (const event of list) {
|
||||
if (!event || event.seq < lastStart) continue;
|
||||
if (!event || event.seq < floor) continue;
|
||||
if (event.type !== "subagent/catalog" && event.type !== "subagent/descriptor") continue;
|
||||
const id = event.data?.childId || event.data?.sessionId || event.data?.id;
|
||||
if (!id || seen.has(id)) continue;
|
||||
@@ -141,18 +144,47 @@ export function lastTurnSubagentIds(events) {
|
||||
|
||||
export function planRewind(events) {
|
||||
const list = Array.isArray(events) ? events : [];
|
||||
const turnStarts = list.filter((event) => event?.type === "turn/start");
|
||||
const lastStart = turnStarts[turnStarts.length - 1];
|
||||
const usersInLastTurn = lastStart
|
||||
? list.filter((event) => isHumanUserEvent(event) && event.seq >= lastStart.seq)
|
||||
: [];
|
||||
const lastUser = usersInLastTurn[0]
|
||||
|| list.filter(isHumanUserEvent).at(-1);
|
||||
const lastUser = list.filter(isHumanUserEvent).at(-1);
|
||||
if (!lastUser) {
|
||||
return { ok: false, error: "没有可回退的上一句" };
|
||||
}
|
||||
const text = userTextFromEvent(lastUser);
|
||||
return { ok: true, mode: "input", text };
|
||||
return {
|
||||
ok: true,
|
||||
mode: "input",
|
||||
text: userTextFromEvent(lastUser),
|
||||
fromSeq: lastUser.seq,
|
||||
};
|
||||
}
|
||||
|
||||
function isRewindMarkerEvent(event) {
|
||||
if (!event || event.type !== "user/message") return false;
|
||||
const id = event.data?.id;
|
||||
return typeof id === "string" && id.startsWith("rewind-");
|
||||
}
|
||||
|
||||
/** 回退标记只占表面位置,不能再进下一轮模型请求。 */
|
||||
export function isRewindDerivedMessage(message) {
|
||||
if (!message) return true;
|
||||
const id = message.id;
|
||||
return typeof id === "string" && id.startsWith("rewind-");
|
||||
}
|
||||
|
||||
/** 只拿掉 fromSeq 及之后的表面节点。系统提示停在节点 0 时不动它。前面连续的回退空标记一并清掉,避免下一次发送还带着上一轮。 */
|
||||
export function cutSurfaceNodes(nodes, fromSeq, eventAt) {
|
||||
const list = (Array.isArray(nodes) ? nodes : []).map((seq) => Number(seq));
|
||||
const floor = Number(fromSeq);
|
||||
let startIdx = list.findIndex((seq) => Number.isFinite(floor) ? seq >= floor : true);
|
||||
if (startIdx < 0) return [];
|
||||
const lookup = typeof eventAt === "function" ? eventAt : () => null;
|
||||
if (startIdx === 0 && lookup(list[0])?.type === "system/message") startIdx = 1;
|
||||
while (startIdx > 0) {
|
||||
const prev = lookup(list[startIdx - 1]);
|
||||
if (!prev || prev.type === "system/message" || !isRewindMarkerEvent(prev)) break;
|
||||
startIdx -= 1;
|
||||
}
|
||||
if (startIdx === 0 && lookup(list[0])?.type === "system/message") startIdx = 1;
|
||||
if (startIdx >= list.length) return [];
|
||||
return list.slice(startIdx);
|
||||
}
|
||||
|
||||
function rememberDraft(sessionId, text, parentId) {
|
||||
@@ -283,6 +315,24 @@ function getAgent(ctx, sessionId) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 回退后下一句按新请求开,不要接着上一轮的 request/header series。 */
|
||||
function resetRequestSeries(ctx, sessionId) {
|
||||
const agent = getAgent(ctx, sessionId);
|
||||
if (!agent) return;
|
||||
try { agent.requestHeaderLogged = false; } catch { /* ignore */ }
|
||||
try { agent.requestSurfaceGeneration = -1; } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
export function wrapSessionDeriveMessages(session) {
|
||||
if (!session || typeof session.deriveMessages !== "function" || session.__dshPurgeRewindDerive) return session;
|
||||
const orig = session.deriveMessages.bind(session);
|
||||
session.deriveMessages = function deriveMessagesWithoutRewind() {
|
||||
return orig().filter((message) => !isRewindDerivedMessage(message));
|
||||
};
|
||||
session.__dshPurgeRewindDerive = true;
|
||||
return session;
|
||||
}
|
||||
|
||||
async function disarmRewoundSession(ctx, sessionId) {
|
||||
if (!sessionId) return;
|
||||
const controller = service(ctx, "sessionController");
|
||||
@@ -387,14 +437,14 @@ function derivedStillContains(session, text) {
|
||||
}
|
||||
if (!Array.isArray(messages)) return false;
|
||||
for (const message of messages) {
|
||||
if (!message || message.role === "system") continue;
|
||||
if (!message || message.role === "system" || isRewindDerivedMessage(message)) continue;
|
||||
if (flatMessageText(message).includes(needle)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 留在当前会话。把系统提示后面的可见记录从模型请求里拿掉,不另开会话。 */
|
||||
function clearModelHistory(session, text) {
|
||||
/** 留在当前会话。只把 fromSeq 起的这一轮从模型请求里拿掉,更早的轮次留着。 */
|
||||
function clearModelHistory(session, text, fromSeq = 0) {
|
||||
if (!session || typeof session.append !== "function" || !session.surface) {
|
||||
throw new Error("没有清掉之前发送的内容");
|
||||
}
|
||||
@@ -407,15 +457,13 @@ function clearModelHistory(session, text) {
|
||||
}
|
||||
const events = typeof session.snapshotEvents === "function" ? session.snapshotEvents() : [];
|
||||
const eventAt = (seq) => events.find((event) => event?.seq === seq) || session.eventAt?.(seq);
|
||||
let startIdx = 0;
|
||||
if (eventAt(nodes[0])?.type === "system/message") startIdx = 1;
|
||||
if (startIdx >= nodes.length) {
|
||||
const shadowed = cutSurfaceNodes(nodes, fromSeq, eventAt);
|
||||
if (shadowed.length === 0) {
|
||||
if (derivedStillContains(session, text)) {
|
||||
throw new Error("没有清掉之前发送的内容");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const shadowed = nodes.slice(startIdx).map((seq) => Number(seq));
|
||||
const startSeq = shadowed[0];
|
||||
const endSeq = shadowed[shadowed.length - 1];
|
||||
if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq)) {
|
||||
@@ -430,32 +478,33 @@ function clearModelHistory(session, text) {
|
||||
surfaceOp: { op: "replace", startSeq, endSeq },
|
||||
sourceEventSeqs: shadowed,
|
||||
});
|
||||
if (derivedStillContains(session, text)) {
|
||||
const left = new Set((session.surface.nodes || []).map((seq) => Number(seq)));
|
||||
if (shadowed.some((seq) => left.has(seq))) {
|
||||
throw new Error("没有清掉之前发送的内容");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function rewindOneSession(ctx, controller, sessionId) {
|
||||
async function rewindOneSession(ctx, controller, sessionId, options = {}) {
|
||||
let log = await readSessionLog(ctx, sessionId);
|
||||
if (lastOpenTurn(log.events)) {
|
||||
try { ignoreSettled(controller.cancel?.({ sessionId })); } catch { /* ignore */ }
|
||||
log = await waitTurnClosed(ctx, sessionId);
|
||||
}
|
||||
const plan = planRewind(log.events);
|
||||
const plan = options.full
|
||||
? { ok: true, mode: "input", text: lastHumanUserText(log.events), fromSeq: 0 }
|
||||
: planRewind(log.events);
|
||||
if (!plan.ok) return plan;
|
||||
|
||||
await disarmRewoundSession(ctx, sessionId);
|
||||
const session = liveSession(ctx, sessionId);
|
||||
const session = wrapSessionDeriveMessages(liveSession(ctx, sessionId));
|
||||
let cleared = false;
|
||||
try {
|
||||
cleared = clearModelHistory(session, plan.text);
|
||||
cleared = clearModelHistory(session, plan.text, plan.fromSeq);
|
||||
} catch (err) {
|
||||
return { ok: false, error: errorText(err) };
|
||||
}
|
||||
if (derivedStillContains(session, plan.text)) {
|
||||
return { ok: false, error: "没有清掉之前发送的内容" };
|
||||
}
|
||||
resetRequestSeries(ctx, sessionId);
|
||||
|
||||
const rec = rememberDraft(sessionId, plan.text, sessionId);
|
||||
return {
|
||||
@@ -499,8 +548,16 @@ export async function applyRewind(ctx, sessionId, mode) {
|
||||
if (sessionId !== target.sessionId) {
|
||||
try { ignoreSettled(controller.cancel?.({ sessionId })); } catch { /* ignore */ }
|
||||
}
|
||||
const preview = planRewind(target.log?.events || []);
|
||||
const children = preview.ok ? lastTurnSubagentIds(target.log.events, preview.fromSeq) : [];
|
||||
const result = await rewindOneSession(ctx, controller, target.sessionId);
|
||||
if (!result.ok) return result;
|
||||
for (const childId of children) {
|
||||
if (!childId || childId === target.sessionId) continue;
|
||||
if (!liveSession(ctx, childId)) continue;
|
||||
const child = await rewindOneSession(ctx, controller, childId, { full: true });
|
||||
if (!child.ok) return child;
|
||||
}
|
||||
return { ...result, sourceId: sessionId, mode: "round" };
|
||||
}
|
||||
|
||||
|
||||
+19
-9
@@ -1,7 +1,8 @@
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { findDshHome, findOverrideFile, normalizeOverride } from "./core.js";
|
||||
import { defaultOverrideText, findDshHome, findOverrideFile, normalizeOverride } from "./core.js";
|
||||
import { modePromptText } from "./identity.js";
|
||||
|
||||
const RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
||||
const MAX_RULE_BYTES = 256 * 1024;
|
||||
@@ -181,25 +182,34 @@ export function overrideFileText(dshHome) {
|
||||
}
|
||||
}
|
||||
|
||||
function promptOrDefault(dshHome) {
|
||||
const disk = normalizeOverride(overrideFileText(dshHome));
|
||||
if (disk) return disk;
|
||||
return normalizeOverride(defaultOverrideText());
|
||||
}
|
||||
|
||||
/** 没启用规则集时只注入可编辑提示词。启用规则集后以规则集为主。两边都空则不注入。 */
|
||||
export function resolveInjectText(dshHome) {
|
||||
const ruleId = activeRuleId(dshHome);
|
||||
const rule = normalizeOverride(activeRuleText(dshHome));
|
||||
if (rule) return { text: rule, source: "rule", ruleId };
|
||||
const prompt = normalizeOverride(overrideFileText(dshHome));
|
||||
const prompt = promptOrDefault(dshHome);
|
||||
if (prompt) return { text: prompt, source: "prompt", ruleId: null };
|
||||
return { text: "", source: "none", ruleId };
|
||||
}
|
||||
|
||||
/** 红队在当前正文之外,再带上另一份没有重复的提示词或规则集。 */
|
||||
/**
|
||||
* 官方始终用默认提示词全文,含 CTF,不读规则集。
|
||||
* 红队开了规则集就只用规则集,不带默认提示词。
|
||||
* 红队没开规则集时用默认提示词,去掉 CTF。操作说明由组装接在后面。
|
||||
* 禁区说明不进模型。
|
||||
*/
|
||||
export function resolveModeInject(dshHome, redteam) {
|
||||
const prompt = normalizeOverride(overrideFileText(dshHome));
|
||||
const prompt = promptOrDefault(dshHome);
|
||||
if (!redteam) return modePromptText(prompt, false);
|
||||
const rule = normalizeOverride(activeRuleText(dshHome));
|
||||
if (!redteam) return rule || prompt;
|
||||
const parts = [];
|
||||
if (prompt) parts.push(prompt);
|
||||
if (rule && rule !== prompt) parts.push(rule);
|
||||
return parts.join("\n\n");
|
||||
if (rule) return modePromptText(rule, true);
|
||||
return modePromptText(prompt, true);
|
||||
}
|
||||
|
||||
export async function activateRule(dshHome, id) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dsh-purge",
|
||||
"version": "1.1.43",
|
||||
"version": "1.1.44",
|
||||
"description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,内嵌演练台;不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
|
||||
@@ -1,3 +1,25 @@
|
||||
# 1.1.44
|
||||
|
||||
## 中文
|
||||
|
||||
- 版本升级到 1.1.44。
|
||||
- 官方桌面解开 `app.asar` 时先写到旁边的目录,解开完成才换上 `resources/app`。目录里已经有宿主之后只改这些文件。同一份归档又出现时只把它挪开。归档的大小或时间变了,或目录不在了,才再解一次。解包卡住或补丁没写完,把上一份放回去,升级标记留到下次再试。
|
||||
- 回退上一轮只撤掉最后一条已经发出的消息和它的回复,更早的轮次留在对话里,也从模型请求里拿掉。连续回退后留下的空标记不再进下一轮请求,下一句按新消息发。
|
||||
- 可编辑提示词整份放在系统提示最前,同一份正文不再拼第二遍。每一步用当前这一份替换第一条系统提示。
|
||||
- deepseek.com 的系统提示固定走 system,思维链照旧发送。
|
||||
- 地区拦截只看这次任务里的目标。自己的服务器只认名单上的那一个地址或主机名。禁止句写上之后才结束这一轮。
|
||||
- 官方始终用带 CTF 的默认提示词。红队开了规则集就只用规则集;否则用去掉 CTF 的默认提示词,再接红队操作。子代理跟主会话吃同一份。磁盘没有提示词时启动就用默认那份,不必先点保存。
|
||||
|
||||
## English
|
||||
|
||||
- Version 1.1.44.
|
||||
- Unpacking `app.asar` writes beside `resources/app` and swaps in only after the unpack finishes. Once that directory is usable, later starts only edit those files. The same archive showing up again is moved aside. A new size or mtime, or a missing directory, is unpacked once. If unpacking sticks or that patch round does not finish, the previous directory is put back and the upgrade marker stays for the next start.
|
||||
- Rewinding the previous round removes only that sent message and its reply. Earlier rounds stay on screen and leave the next model request. Leftover rewind markers stay off the next model request, so the next send is a new message.
|
||||
- The editable prompt is placed once at the front of the system prompt. Each step replaces the first system prompt with that current text.
|
||||
- Instructions for deepseek.com stay on the system role. Thinking is still sent.
|
||||
- The region check looks only at this task's target. An own server is allowed only when that exact address or hostname is on the list. The turn ends after the denial sentence is written.
|
||||
- Official mode always uses the default prompt, including CTF. Red team uses only the active rule set, or the default prompt without CTF followed by the red team steps. Subagents receive the same inject as the main session. If the prompt file is empty, startup uses the bundled default without requiring Save.
|
||||
|
||||
# 1.1.43
|
||||
|
||||
## 中文
|
||||
|
||||
Reference in new issue
Block a user