fix: 发布 1.1.44,提示词按模式注入并让子代理吃到同一份。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-10-01 19:18:15 +08:00
1 parent b47ebfb976
commit 2ecce304db
10 files changed
+816 -221

No files matched your search

+106 -50
View File
@@ -13,8 +13,10 @@ import {
import * as desktop from "./desktop.js";
import {
asarArchiveIsFile,
asarFileIdentity,
commitExtractedDir,
extractAsarToSide,
shouldExtractAsar,
hostFs,
newestPreservedDir,
overlayAsarUnpacked,
@@ -1635,6 +1637,40 @@ export function sealedAsarHandoff(input = {}) {
return { exe, asar, swapAsar: true };
}
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;
@@ -1643,15 +1679,23 @@ function restoreUnusableExtract(appDir, prev) {
return restoreExtractedDir(appDir, saved);
}
/** 官方 app.asar 解开到 resources/app。已有解开目录时直接用,不重新解包。 */
/** 官方 app.asar 解开到 resources/app。目录已能用且归档没变时直接改文件,不重新解包。 */
export async function openSealedDesktopHost(options = {}) {
const handoff = sealedAsarHandoff();
if (!handoff) return { aiBase: null, swapAsar: false, extracted: false, prev: "", appDir: "" };
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);
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 (!aiBase) {
if (extract) {
try {
const side = extractAsarToSide(handoff.asar, appDir);
overlayAsarUnpacked(handoff.asar, side.next);
@@ -1667,15 +1711,16 @@ export async function openSealedDesktopHost(options = {}) {
try { restoreUnusableExtract(appDir, prev); } catch { /* 放回失败时旧目录仍留在旁边 */ }
throw error;
}
} else {
} else if (aiBase) {
overlayAsarUnpacked(handoff.asar, appDir);
if (archive && !recorded) writeUnpackedAsarStamp(archive);
}
if (!aiBase) {
restoreUnusableExtract(appDir, prev);
throw new Error(`已解开 ${handoff.asar},但 ${appDir} 下没有 @deepseek-ai`);
}
resetPathMemo();
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar, extracted, prev, appDir };
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar, extracted, prev, appDir, archive: extracted ? archive : null };
}
export function restoreSealedExtract(appDir, prev) {
@@ -2095,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",
@@ -2655,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",
@@ -3686,8 +3692,18 @@ const NEW_TOOL_PATCHES = [
"\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\tif (Array.isArray(event.sourceEventSeqs)) {\n" +
"\t\t\t\t\tfor (const seq of event.sourceEventSeqs) hidden.add(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 entry of raw) {\n" +
"\t\t\t\t\t\tif (typeof entry === \"number\") hidden.add(entry);\n" +
"\t\t\t\t\t\telse if (Array.isArray(entry) && entry.length === 2 && typeof entry[0] === \"number\" && typeof entry[1] === \"number\" && entry[1] >= entry[0] && entry[1] - entry[0] < 100000) {\n" +
"\t\t\t\t\t\t\tfor (let seq = entry[0]; seq <= entry[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}\n" +
"\t\t\tif (hidden.size === 0) return list;\n" +
@@ -3723,8 +3739,18 @@ const NEW_TOOL_PATCHES = [
"\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\tif (Array.isArray(event.sourceEventSeqs)) {\n" +
"\t\t\t\t\tfor (const seq of event.sourceEventSeqs) hidden.add(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 entry of raw) {\n" +
"\t\t\t\t\t\tif (typeof entry === \"number\") hidden.add(entry);\n" +
"\t\t\t\t\t\telse if (Array.isArray(entry) && entry.length === 2 && typeof entry[0] === \"number\" && typeof entry[1] === \"number\" && entry[1] >= entry[0] && entry[1] - entry[0] < 100000) {\n" +
"\t\t\t\t\t\t\tfor (let seq = entry[0]; seq <= entry[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}\n" +
"\t\t\tif (hidden.size === 0) return list;\n" +
@@ -3747,6 +3773,23 @@ const NEW_TOOL_PATCHES = [
],
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"],
},
];
export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES];
@@ -5169,7 +5212,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,
@@ -5203,6 +5246,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");
+33
View File
@@ -120,6 +120,39 @@ export function asarArchiveIsFile(p) {
}
}
/** 用大小和修改时间认出是不是同一份归档。 */
export function asarFileIdentity(asarPath) {
try {
const st = archiveFs().statSync(asarPath);
if (!st.isFile()) return null;
return { size: st.size, mtimeMs: Math.round(st.mtimeMs) };
} catch {
return null;
}
}
export function sameAsarIdentity(left, right) {
return Boolean(
left && right
&& left.size === right.size
&& left.mtimeMs === right.mtimeMs,
);
}
/**
* 可用目录配同一份归档:不解包。
* 目录不在,或记录过的归档大小/时间变了:解一次。
* 升级标记碰上另一份归档,同样解一次。目录还在、又没记录过、也不是升级:先认这份归档,不解。
*/
export function shouldExtractAsar({ usable, identity, recorded, upgrade }) {
if (!identity) return false;
if (!usable) return true;
const same = sameAsarIdentity(identity, recorded);
if (upgrade && !same) return true;
if (recorded && !same) return true;
return false;
}
function readHeader(fd, afs) {
const pre = Buffer.alloc(16);
if (afs.readSync(fd, pre, 0, 16, 0) !== 16) throw new Error("asar header truncated");
+120 -13
View File
@@ -180,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 || "");
@@ -188,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) {
@@ -242,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);
}
/**
@@ -257,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 = [];
@@ -471,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 再删掉本段,重启加载该逻辑后注入会丢。
@@ -480,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;
}
+17 -7
View File
@@ -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,30 @@ 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) : "",
});
}
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;
}
@@ -318,8 +327,9 @@ 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 });
const upgraded = await reapply.reapplyInstalled({ scheduleSwap: false, upgrade: true });
if (!upgraded.ok) {
log(config, "official upgrade reapply failed:", upgraded.error || "");
return "reapply-failed";
@@ -1262,7 +1272,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
View File
@@ -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 {
/* 宿主还没有这条事件时,下一拍再挂。 */
+8 -4
View File
@@ -84,9 +84,10 @@ export async function reapplyInstalled(options = {}) {
} 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;
@@ -94,7 +95,7 @@ export async function reapplyInstalled(options = {}) {
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() };
// 刚解开的是官方原件。已经在用的目录仍先还原再按这一版重打。
@@ -121,7 +122,10 @@ export async function reapplyInstalled(options = {}) {
cmdFlashOk: flash.ok === true,
};
}
if (clean) writeAppliedStamp(installedRev());
if (clean) {
writeAppliedStamp(installedRev());
if (freshExtract?.archive) core.writeUnpackedAsarStamp(freshExtract.archive);
}
let renamed = false;
if (clean && handoff?.asar && options.scheduleSwap !== false) {
const swapped = core.scheduleSealedDesktopRestart(handoff);
+7 -5
View File
@@ -8,6 +8,7 @@
*/
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { isRedteamSession } from '../identity.js'
import { redteamRoot } from './platform-config.js'
const ROLE_TAG = /^[ \t]*redteamRole:[ \t]*(recon|assess|vuln-scan|exploit|internal)[ \t]*$/im
@@ -33,15 +34,16 @@ function remember(agent, role) {
for (const id of ids) roleBySession.set(String(id), role)
}
function isRedteamChild(session) {
function isRedteamChild(session, agent) {
const header = session?.header
return header?.origin === 'subagent' && header?.agentPreset === 'redteam'
if (header?.origin !== 'subagent' && !((header?.delegationDepth ?? 0) > 0)) return false
return isRedteamSession({ session, agent: agent ? { ...agent, session } : { session } })
}
export function noteClaimedMessage(payload) {
const agent = payload?.agent
const session = agent?.session
if (!isRedteamChild(session)) return
if (!isRedteamChild(session, agent)) return
const role = parseRedteamRole(textOfMessage(payload?.message))
if (!role) return
remember(agent, role)
@@ -99,9 +101,9 @@ function readRoleFile(engagementId, role) {
export function resolveSubagentRoleText(context) {
try {
const session = context?.agent?.session || context?.session
if (!isRedteamChild(session)) return ''
const agent = context?.agent
const session = agent?.session || context?.session
if (!isRedteamChild(session, agent)) return ''
const sessionId = session?.id ?? agent?.id
let role = sessionId !== undefined && sessionId !== null
? roleBySession.get(String(sessionId)) || ''
+10 -6
View File
@@ -2,6 +2,7 @@ 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 { modePromptText } from "./identity.js";
const RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
const MAX_RULE_BYTES = 256 * 1024;
@@ -191,15 +192,18 @@ export function resolveInjectText(dshHome) {
return { text: "", source: "none", ruleId };
}
/** 红队在当前正文之外,再带上另一份没有重复的提示词或规则集。 */
/**
* 官方始终用默认提示词全文,含 CTF,不读规则集。
* 红队开了规则集就只用规则集,不带默认提示词。
* 红队没开规则集时用默认提示词,去掉 CTF。操作说明由组装接在后面。
* 禁区说明不进模型。
*/
export function resolveModeInject(dshHome, redteam) {
const prompt = normalizeOverride(overrideFileText(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) {