diff --git a/README.md b/README.md index 03de96a..f634eae 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@
Version 1.1.37
+Version 1.1.38
Local official DeepSeek Harness cybersecurity red-team plugin. Clean host policy, and ship a built-in drill console. Swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐ @@ -784,4 +784,17 @@ What changed, and the zip, are on [Releases](https://github.com/YuJunZhiXue/dsh- --- +## ☕ Sponsor + +If this project helps you, send it over — I'm out here asking~ + +| Asset | Address | +| --- | --- | +| USDT (TRC20) | `TV5ajPkRD8RH623Dx9mqvYZVNN8nPGRKid` | +| Solana | `6x16GhRgLVpKFFXaU1seKNdx2rypspSJTL4dbpt6Xpwk` | +| Ethereum | `0xB68BD60C0e8c519513B7DF9bB147696815423B3E` | +| Bitcoin | `bc1qu70yxkrtwnymt8ryluz9x8y8hqzune5340npht` | + +--- + Thanks to the [LINUX DO](https://linux.do) community diff --git a/README.zh-CN.md b/README.zh-CN.md index 3d15614..a6952d5 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@
Version 1.1.37
+Version 1.1.38
本机官方 DeepSeek Harness 网络安全红队评测插件。清洗宿主策略,并带内嵌演练台。不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐
@@ -775,4 +775,17 @@ flowchart LR
---
+## ☕ Sponsor
+
+If this project helps you, send it over — I'm out here asking~
+
+| Asset | Address |
+| --- | --- |
+| USDT (TRC20) | `TV5ajPkRD8RH623Dx9mqvYZVNN8nPGRKid` |
+| Solana | `6x16GhRgLVpKFFXaU1seKNdx2rypspSJTL4dbpt6Xpwk` |
+| Ethereum | `0xB68BD60C0e8c519513B7DF9bB147696815423B3E` |
+| Bitcoin | `bc1qu70yxkrtwnymt8ryluz9x8y8hqzune5340npht` |
+
+---
+
感谢 [LINUX DO](https://linux.do) 社区
diff --git a/client.js b/client.js
index 7c61deb..1849cc8 100644
--- a/client.js
+++ b/client.js
@@ -4158,7 +4158,7 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert
placeholder: '该角色的系统提示词(Markdown)',
}),
h('div', { style: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', marginTop: 6 } },
- '保存后写入 agents/' + (active || 'role') + '.md,并在该角色会话的每次模型请求前注入。'))))
+ '保存后写入 agents/' + (active || 'role') + '.md。子会话任务第一行写 redteamRole: recon、assess、vuln-scan、exploit 或 internal 后,对应文件进入系统提示词。'))))
}
/* ---------------------------------------------------------- 技能库(DSH 原生) */
diff --git a/lib/child-process-hide.mjs b/lib/child-process-hide.mjs
index ba03246..140e949 100644
--- a/lib/child-process-hide.mjs
+++ b/lib/child-process-hide.mjs
@@ -1,5 +1,16 @@
-const cp = process.getBuiltinModule("child_process"); // Node 24 ESM 具名导入是副本,必须包 builtin
+function builtinChildProcess() {
+ try {
+ if (typeof process.getBuiltinModule !== "function") return null;
+ const mod = process.getBuiltinModule("child_process");
+ if (!mod || typeof mod.spawn !== "function") return null;
+ return mod;
+ } catch {
+ return null;
+ }
+}
+
const MARK = "__dshPurgeHideConsole";
+const electron = typeof process.versions !== "undefined" && Boolean(process.versions.electron);
function hide(options) {
if (options == null) return { windowsHide: true };
@@ -37,7 +48,10 @@ function wrapFork(orig) {
};
}
-if (process.platform === "win32" && !cp[MARK]) {
+function live() {
+ const cp = builtinChildProcess();
+ if (!cp) return null;
+ if (process.platform !== "win32" || electron || cp[MARK]) return cp;
cp.spawn = wrapSpawn(cp.spawn);
cp.spawnSync = wrapSpawn(cp.spawnSync);
cp.exec = wrapExec(cp.exec);
@@ -46,14 +60,28 @@ if (process.platform === "win32" && !cp[MARK]) {
cp.execFileSync = wrapExecFile(cp.execFileSync);
if (typeof cp.fork === "function") cp.fork = wrapFork(cp.fork);
Object.defineProperty(cp, MARK, { value: true, enumerable: false });
+ return cp;
}
+function method(name) {
+ return function bound(...args) {
+ const cp = live();
+ const fn = cp && cp[name];
+ if (typeof fn !== "function") {
+ throw new TypeError(`node:child_process.${name} is unavailable`);
+ }
+ return fn.apply(this, args);
+ };
+}
+
+const cp = live();
+
export default cp;
-export const spawn = cp.spawn;
-export const spawnSync = cp.spawnSync;
-export const exec = cp.exec;
-export const execSync = cp.execSync;
-export const execFile = cp.execFile;
-export const execFileSync = cp.execFileSync;
-export const fork = cp.fork;
-export const ChildProcess = cp.ChildProcess;
+export const spawn = method("spawn");
+export const spawnSync = method("spawnSync");
+export const exec = method("exec");
+export const execSync = method("execSync");
+export const execFile = method("execFile");
+export const execFileSync = method("execFileSync");
+export const fork = method("fork");
+export const ChildProcess = cp ? cp.ChildProcess : undefined;
diff --git a/lib/core.js b/lib/core.js
index bf9e33c..0ebb70f 100644
--- a/lib/core.js
+++ b/lib/core.js
@@ -1581,9 +1581,9 @@ export function missingAiBaseMessage() {
if (adapterFor(detectSurface()) === "desktop") {
const exe = desktop.findDesktopAppExecutable();
if (exe) {
- const asar = path.join(path.dirname(exe), "resources", "app.asar");
+ const asar = desktop.appAsarPath(exe);
if (asarArchiveIsFile(asar) && desktop.isOfficialHarnessExecutable(exe)) {
- return `已找到 ${exe}。官方宿主在 app.asar 里,点「应用」会解开 resources\\app 并自动重启,不用另跑脚本。`;
+ return `已找到 ${exe}。官方宿主在 app.asar 里,点「应用」会解开 ${desktop.appDirForExecutable(exe)} 并自动重启,不用另跑脚本。`;
}
return `已找到桌面应用 ${exe},但其 resources/app(或 app.asar.unpacked)下没有 @deepseek-ai`;
}
@@ -1608,7 +1608,7 @@ export function sealedAsarHandoff(input = {}) {
? path.normalize(hinted)
: desktop.findDesktopAppExecutable(input);
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return null;
- const asar = path.join(path.dirname(exe), "resources", "app.asar");
+ const asar = desktop.appAsarPath(exe);
if (!asarArchiveIsFile(asar)) return null;
return { exe, asar, swapAsar: true };
}
@@ -1617,7 +1617,7 @@ export function sealedAsarHandoff(input = {}) {
export async function openSealedDesktopHost(options = {}) {
const handoff = sealedAsarHandoff();
if (!handoff) return { aiBase: null, swapAsar: false };
- const appDir = path.join(path.dirname(handoff.exe), "resources", "app");
+ const appDir = desktop.appDirForExecutable(handoff.exe);
let aiBase = options.forceExtract ? null : aiBaseUnderAppDir(appDir);
if (!aiBase) {
await extractAsar(handoff.asar, appDir);
@@ -1625,7 +1625,7 @@ export async function openSealedDesktopHost(options = {}) {
}
overlayAsarUnpacked(handoff.asar, appDir);
if (!aiBase) {
- throw new Error(`已解开 ${handoff.asar},但 resources\\app 下没有 @deepseek-ai`);
+ throw new Error(`已解开 ${handoff.asar},但 ${appDir} 下没有 @deepseek-ai`);
}
resetPathMemo();
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar };
@@ -3220,7 +3220,7 @@ function officialShellMain() {
try {
const exe = desktop.findDesktopAppExecutable();
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return "";
- const main = path.join(path.dirname(exe), "resources", "app", "lib", "main.js");
+ const main = path.join(desktop.appDirForExecutable(exe), "lib", "main.js");
return fs.existsSync(main) ? main : "";
} catch {
return "";
diff --git a/lib/desktop.js b/lib/desktop.js
index ee9aac6..3d11aa8 100644
--- a/lib/desktop.js
+++ b/lib/desktop.js
@@ -88,20 +88,68 @@ export function looksLikeDesktopName(p) {
);
}
+const OFFICIAL_HARNESS_BASES = new Set([
+ "deepseek harness.exe",
+ "deepseek-harness.exe",
+ "deepseek harness",
+ "deepseek-harness",
+]);
+
+function sameBase(name, expected) {
+ return String(name || "").toLowerCase() === expected;
+}
+
export function isDesktopExecutable(fp) {
const base = path.basename(String(fp || "")).toLowerCase();
- return (
- base === "dsh desktop.exe" ||
- base === "dsh desktop" ||
- base === "deepseek harness.exe" ||
- base === "deepseek-harness.exe"
- );
+ return base === "dsh desktop.exe" || base === "dsh desktop" || OFFICIAL_HARNESS_BASES.has(base);
}
/** 只有官方 DeepSeek Harness 会把宿主封进 app.asar 并在「应用」时解开。第三方 DSH Desktop 不走这条。 */
export function isOfficialHarnessExecutable(fp) {
- const base = path.basename(String(fp || "")).toLowerCase();
- return base === "deepseek harness.exe" || base === "deepseek-harness.exe";
+ return OFFICIAL_HARNESS_BASES.has(path.basename(String(fp || "")).toLowerCase());
+}
+
+/** 某个安装目录下可能的 resources 文件夹(mac 大小写敏感盘要 Resources 和 resources 都试)。 */
+export function resourceDirCandidates(installDir) {
+ if (!installDir) return [];
+ const name = path.basename(installDir);
+ if (sameBase(name, "macos")) {
+ const contents = path.dirname(installDir);
+ return [path.join(contents, "Resources"), path.join(contents, "resources")];
+ }
+ if (sameBase(name, "contents")) {
+ return [path.join(installDir, "Resources"), path.join(installDir, "resources")];
+ }
+ if (name.toLowerCase().endsWith(".app")) {
+ return [
+ path.join(installDir, "Contents", "Resources"),
+ path.join(installDir, "Contents", "resources"),
+ ];
+ }
+ if (sameBase(name, "resources")) return [installDir];
+ return [path.join(installDir, "resources"), path.join(installDir, "Resources")];
+}
+
+/** 官方宿主的 resources 目录。已存在的 app.asar 优先,否则用该平台的常规目录名。 */
+export function resourcesDirForExecutable(exe) {
+ const exeDir = path.dirname(path.normalize(String(exe || "")));
+ if (!exeDir) return "";
+ const cands = resourceDirCandidates(exeDir);
+ const withAsar = cands.find((dir) => isFile(path.join(dir, "app.asar")));
+ if (withAsar) return withAsar;
+ const existing = cands.find((dir) => isDir(dir));
+ if (existing) return existing;
+ return cands[0] || "";
+}
+
+export function appAsarPath(exe) {
+ const dir = resourcesDirForExecutable(exe);
+ return dir ? path.join(dir, "app.asar") : "";
+}
+
+export function appDirForExecutable(exe) {
+ const dir = resourcesDirForExecutable(exe);
+ return dir ? path.join(dir, "app") : "";
}
function exeCandidatesBeside(dir) {
@@ -109,12 +157,16 @@ function exeCandidatesBeside(dir) {
return [
path.join(dir, "DeepSeek Harness.exe"),
path.join(dir, "deepseek-harness.exe"),
+ path.join(dir, "DeepSeek Harness"),
+ path.join(dir, "deepseek-harness"),
path.join(dir, "DSH Desktop.exe"),
path.join(dir, "DSH Desktop"),
- path.join(dir, "MacOS", "DSH Desktop"),
path.join(dir, "MacOS", "DeepSeek Harness"),
- path.join(dir, "Contents", "MacOS", "DSH Desktop"),
+ path.join(dir, "MacOS", "deepseek-harness"),
+ path.join(dir, "MacOS", "DSH Desktop"),
path.join(dir, "Contents", "MacOS", "DeepSeek Harness"),
+ path.join(dir, "Contents", "MacOS", "deepseek-harness"),
+ path.join(dir, "Contents", "MacOS", "DSH Desktop"),
];
}
@@ -271,6 +323,15 @@ export function commonDesktopInstallDirs(env = process.env) {
"/Applications/DSH Desktop.app",
path.join(home, "Applications", "DeepSeek Harness.app"),
path.join(home, "Applications", "DSH Desktop.app"),
+ "/opt/DeepSeek Harness",
+ "/opt/deepseek-harness",
+ "/usr/lib/DeepSeek Harness",
+ "/usr/lib/deepseek-harness",
+ "/usr/share/deepseek-harness",
+ path.join(home, ".local", "share", "DeepSeek Harness"),
+ path.join(home, ".local", "share", "deepseek-harness"),
+ "/opt/DSH Desktop",
+ "/usr/lib/dsh-desktop",
]);
}
@@ -284,9 +345,14 @@ export function listDesktopInstallRoots(input = {}) {
if (isDesktopExecutable(execPath)) {
const dir = path.dirname(path.normalize(execPath));
roots.push(dir);
- if (path.basename(dir) === "MacOS") {
+ if (sameBase(path.basename(dir), "macos")) {
const contents = path.dirname(dir);
- roots.push(contents, path.join(contents, "Resources"), path.dirname(contents));
+ roots.push(
+ contents,
+ path.join(contents, "Resources"),
+ path.join(contents, "resources"),
+ path.dirname(contents),
+ );
}
}
@@ -351,22 +417,13 @@ export function findDesktopAppExecutable(input = {}) {
function packageRootsFromInstall(installDir) {
if (!installDir) return [];
- const bases = [installDir];
- const name = path.basename(installDir);
- if (name === "MacOS") bases.push(path.join(path.dirname(installDir), "Resources"));
- if (name === "Contents") bases.push(path.join(installDir, "Resources"));
- if (name.toLowerCase().endsWith(".app")) bases.push(path.join(installDir, "Contents", "Resources"));
const out = [];
- for (const base of bases) {
+ for (const resources of resourceDirCandidates(installDir)) {
out.push(
- path.join(base, "resources", "app", "dsh", "node_modules", "@deepseek-ai"),
- path.join(base, "resources", "app", "node_modules", "@deepseek-ai"),
- path.join(base, "resources", "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai"),
- path.join(base, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"),
- path.join(base, "app", "dsh", "node_modules", "@deepseek-ai"),
- path.join(base, "app", "node_modules", "@deepseek-ai"),
- path.join(base, "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai"),
- path.join(base, "app.asar.unpacked", "node_modules", "@deepseek-ai"),
+ path.join(resources, "app", "dsh", "node_modules", "@deepseek-ai"),
+ path.join(resources, "app", "node_modules", "@deepseek-ai"),
+ path.join(resources, "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai"),
+ path.join(resources, "app.asar.unpacked", "node_modules", "@deepseek-ai"),
);
}
return out;
@@ -421,15 +478,11 @@ export function resolveDesktopAiBase(input = {}) {
export function resolveDesktopCliScript(input = {}) {
const exe = findDesktopAppExecutable(input);
if (exe) {
- const install = path.dirname(exe);
- const packed = path.join(install, "resources", "app", "lib", "desktop-cli.js");
+ const resources = resourcesDirForExecutable(exe);
+ const packed = path.join(resources, "app", "lib", "desktop-cli.js");
if (isFile(packed)) return path.normalize(packed);
- const unpacked = path.join(install, "resources", "app.asar.unpacked", "lib", "desktop-cli.js");
+ const unpacked = path.join(resources, "app.asar.unpacked", "lib", "desktop-cli.js");
if (isFile(unpacked)) return path.normalize(unpacked);
- if (path.basename(install) === "MacOS") {
- const macPacked = path.join(path.dirname(install), "Resources", "app", "lib", "desktop-cli.js");
- if (isFile(macPacked)) return path.normalize(macPacked);
- }
}
for (const arg of input.argv ?? process.argv) {
if (typeof arg === "string" && /desktop-cli\.js$/i.test(arg) && isFile(arg)) {
@@ -635,6 +688,46 @@ const ASAR_RENAME_WHEN_IDLE_PS1 = [
"",
].join("\r\n");
+const ASAR_RENAME_WHEN_IDLE_SH = [
+ "#!/bin/sh",
+ "asar=$1",
+ "exe=$2",
+ "lock=$3",
+ "deadline=$(($(date +%s) + 1800))",
+ "relaunch() {",
+ " case \"$(uname -s)\" in",
+ " Darwin)",
+ " case \"$exe\" in",
+ " */Contents/MacOS/*)",
+ " bundle=$(dirname \"$(dirname \"$(dirname \"$exe\")\")\")",
+ " open \"$bundle\"",
+ " return",
+ " ;;",
+ " esac",
+ " ;;",
+ " esac",
+ " unset ELECTRON_RUN_AS_NODE",
+ " nohup \"$exe\" >/dev/null 2>&1 &",
+ "}",
+ "while [ \"$(date +%s)\" -lt \"$deadline\" ]; do",
+ " if [ ! -e \"$asar\" ]; then",
+ " rm -f \"$lock\"",
+ " exit 0",
+ " fi",
+ " bak=\"$asar.bak\"",
+ " rm -f \"$bak\"",
+ " if mv \"$asar\" \"$bak\" 2>/dev/null; then",
+ " rm -f \"$lock\"",
+ " relaunch",
+ " exit 0",
+ " fi",
+ " sleep 1",
+ "done",
+ "rm -f \"$lock\"",
+ "exit 1",
+ "",
+].join("\n");
+
/** 官方壳开着时 app.asar 被占用。不结束进程,等用户退出后再改名并重新打开。 */
export function scheduleAsarRenameWhenIdle({ exe, asar } = {}) {
if (!exe || !asar) return { pending: false };
@@ -646,25 +739,36 @@ export function scheduleAsarRenameWhenIdle({ exe, asar } = {}) {
// 没有待处理标记,下面新建。
}
fs.writeFileSync(lock, `${Date.now()}\n`, "utf8");
- const script = path.join(os.tmpdir(), "dsh-purge-asar-rename-when-idle.ps1");
- fs.writeFileSync(script, ASAR_RENAME_WHEN_IDLE_PS1, "utf8");
- const child = spawn(
- "powershell.exe",
- [
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- script,
- "-AsarPath",
- asar,
- "-ExePath",
- exe,
- "-LockPath",
- lock,
- ],
- { detached: true, stdio: "ignore", windowsHide: true, shell: false },
- );
+ if (process.platform === "win32") {
+ const script = path.join(os.tmpdir(), "dsh-purge-asar-rename-when-idle.ps1");
+ fs.writeFileSync(script, ASAR_RENAME_WHEN_IDLE_PS1, "utf8");
+ const child = spawn(
+ "powershell.exe",
+ [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ script,
+ "-AsarPath",
+ asar,
+ "-ExePath",
+ exe,
+ "-LockPath",
+ lock,
+ ],
+ { detached: true, stdio: "ignore", windowsHide: true, shell: false },
+ );
+ child.unref();
+ return { pending: true };
+ }
+ const script = path.join(os.tmpdir(), "dsh-purge-asar-rename-when-idle.sh");
+ fs.writeFileSync(script, ASAR_RENAME_WHEN_IDLE_SH, { encoding: "utf8", mode: 0o755 });
+ const child = spawn("/bin/sh", [script, asar, exe, lock], {
+ detached: true,
+ stdio: "ignore",
+ shell: false,
+ });
child.unref();
return { pending: true };
}
@@ -672,6 +776,7 @@ export function scheduleAsarRenameWhenIdle({ exe, asar } = {}) {
/** 等当前桌面进程退出后把 app.asar 挪走,再启动 exe。解开后的 resources\\app 才会被加载。 */
export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit = false } = {}) {
if (!exe || !asar) throw new Error("缺少桌面 exe 或 app.asar,无法重启");
+ if (process.platform !== "win32") return scheduleAsarRenameWhenIdle({ exe, asar });
const script = path.join(os.tmpdir(), `dsh-purge-asar-swap-${process.pid}.ps1`);
fs.writeFileSync(script, ASAR_SWAP_PS1, "utf8");
const child = spawn(
@@ -697,6 +802,8 @@ export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit
}
function officialExeFromProcess() {
+ // macOS / Linux 的重启走宿主 requestRestart。这里的 wscript 只服务 Windows 官方包。
+ if (process.platform !== "win32") return "";
if (isOfficialHarnessExecutable(process.execPath)) return path.normalize(process.execPath);
const resources = process.resourcesPath;
if (!resources) return "";
@@ -763,7 +870,7 @@ export function restartOfficialHarness() {
if (!exe) return { restarting: false };
const pending = pendingOfficialUpdate(exe);
if (pending) return launchOfficialDesktopUpdate(exe, pending);
- const asar = path.join(path.dirname(exe), "resources", "app.asar");
+ const asar = appAsarPath(exe);
const script = path.join(os.tmpdir(), "dsh-purge-official-restart.js");
const launcher = path.join(os.tmpdir(), "dsh-purge-official-restart.cmd");
fs.writeFileSync(script, officialRestartScript(exe, asar), "utf8");
diff --git a/lib/hide-console.js b/lib/hide-console.js
index 21d4998..2a3ec27 100644
--- a/lib/hide-console.js
+++ b/lib/hide-console.js
@@ -1,5 +1,4 @@
-import { createRequire, registerHooks } from "node:module";
-import { pathToFileURL } from "node:url";
+import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { isAsarSealedPath } from "./desktop.js";
@@ -7,7 +6,6 @@ import { diskFs, fsFor } from "./extract-asar.js";
const MARK = "__dshPurgeHideConsole";
const IMPORT_MARK = "dsh-purge-hide-console";
-const HOOK_MARK = "__dshPurgeChildProcessHook";
function forceHideOptions(options) {
if (options == null) return { windowsHide: true };
@@ -58,39 +56,53 @@ function wrapFork(orig) {
};
}
-function facadeUrl() {
- return pathToFileURL(fileURLToPath(new URL("./child-process-hide.mjs", import.meta.url))).href;
+export function isElectronHost(versions = process.versions) {
+ return Boolean(versions && versions.electron);
+}
+
+/**
+ * Windows 非 Electron:包 builtin,给子进程加 windowsHide。
+ * Electron(官方桌面 / 第三方 DSH Desktop)整段跳过。
+ * macOS、Linux、Kali 不是 win32,调用方直接跳过。
+ * 不再 registerHooks 短路 node:child_process(#46)。
+ */
+export function hideConsoleDecision(platform = process.platform, versions = process.versions) {
+ if (platform !== "win32") return "not_win32";
+ if (isElectronHost(versions)) return "electron_host";
+ return "wrap_builtin";
}
export function installChildProcessImportHook() {
- if (process.platform !== "win32") return { ok: true, skipped: "not_win32" };
- // Electron 会给 child_process 赋值;ESM namespace 冻结后会抛错,桌面宿主只做 wrap。
- if (typeof process.versions !== "undefined" && process.versions.electron) {
- return { ok: true, skipped: "electron_host" };
+ // #46:Node 24 把 node:child_process 短路到 facade 后,
+ // CJS require 会在 loadBuiltinWithHooks 里读到 undefined.exports。
+ // Windows / macOS / Linux 都不再注册这个 resolve 钩子。
+ return { ok: true, skipped: "no_builtin_short_circuit" };
+}
+
+function builtinChildProcess() {
+ try {
+ if (typeof process.getBuiltinModule === "function") {
+ const cp = process.getBuiltinModule("child_process");
+ if (cp && typeof cp.spawn === "function") return cp;
+ }
+ } catch {
+ /* Electron 沙箱里 getBuiltinModule 可能抛,下面再试 require */
}
- if (globalThis[HOOK_MARK]) return { ok: true, already: true };
- const target = facadeUrl();
- registerHooks({
- resolve(specifier, context, nextResolve) {
- if (specifier === "node:child_process" || specifier === "child_process") {
- return { shortCircuit: true, url: target, format: "module" };
- }
- return nextResolve(specifier, context);
- },
- });
- Object.defineProperty(globalThis, HOOK_MARK, { value: true, enumerable: false });
- return { ok: true, hooked: true };
+ try {
+ const cp = createRequire(import.meta.url)("node:child_process");
+ if (cp && typeof cp.spawn === "function") return cp;
+ } catch {
+ return null;
+ }
+ return null;
}
export function installHideConsole() {
- if (process.platform !== "win32") return { ok: true, skipped: "not_win32" };
+ const decision = hideConsoleDecision();
+ if (decision !== "wrap_builtin") return { ok: true, skipped: decision };
const hook = installChildProcessImportHook();
- const require = createRequire(import.meta.url);
- // 改 builtin 本体,和 facade 包的是同一对象。
- const cp =
- typeof process.getBuiltinModule === "function"
- ? process.getBuiltinModule("child_process")
- : require("node:child_process");
+ const cp = builtinChildProcess();
+ if (!cp) return { ok: true, skipped: "builtin_unavailable", hook };
if (cp[MARK]) return { ok: true, already: true, hook };
cp.spawn = wrapSpawn(cp.spawn);
@@ -107,31 +119,13 @@ export function installHideConsole() {
export function hideConsoleEntrySource() {
return `// ${IMPORT_MARK} — auto-installed by dsh-purge; do not edit
-import { pathToFileURL } from "node:url";
-import { fileURLToPath } from "node:url";
-
-const HOOK_MARK = "__dshPurgeChildProcessHook";
const MARK = ${JSON.stringify(MARK)};
-const facade = pathToFileURL(fileURLToPath(new URL("./dsh-purge-child-process-hide.mjs", import.meta.url))).href;
const isElectron = typeof process.versions !== "undefined" && !!process.versions.electron;
-
-// Electron 宿主不改 resolve;只 wrap builtin。
-if (process.platform === "win32" && !isElectron && !globalThis[HOOK_MARK]) {
- const { registerHooks } = await import("node:module");
- registerHooks({
- resolve(specifier, context, nextResolve) {
- if (specifier === "node:child_process" || specifier === "child_process") {
- return { shortCircuit: true, url: facade, format: "module" };
- }
- return nextResolve(specifier, context);
- },
- });
- Object.defineProperty(globalThis, HOOK_MARK, { value: true, enumerable: false });
-}
-
-const cp = process.getBuiltinModule ? process.getBuiltinModule("child_process") : null;
-if (process.platform === "win32" && cp && !cp[MARK]) {
+const cp = !isElectron && process.platform === "win32" && typeof process.getBuiltinModule === "function"
+ ? process.getBuiltinModule("child_process")
+ : null;
+if (cp && typeof cp.spawn === "function" && !cp[MARK]) {
const hide = (options) => {
if (options == null) return { windowsHide: true };
if (typeof options !== "object") return options;
diff --git a/lib/identity.js b/lib/identity.js
index c8ddde5..39237d1 100644
--- a/lib/identity.js
+++ b/lib/identity.js
@@ -116,23 +116,61 @@ function redteamOpsBody(text) {
return raw.slice(at).trim();
}
+function sessionOfContext(context) {
+ return context?.agent?.session || context?.session || null;
+}
+
+export function isRedteamSubagent(context) {
+ const header = sessionOfContext(context)?.header;
+ return header?.origin === "subagent" && header?.agentPreset === "redteam";
+}
+
/**
* 主模式仍只有清洗提示词。
- * 红队模式把同一份清洗提示词放在最前,后面只接派活和操作说明,不保留红队身份句。
+ * 红队指挥:清洗稿、目标卡、运行环境前提,不保留红队身份句。
+ * 红队子会话:清洗稿、目标卡、角色稿、运行环境前提。roleText 为空时与指挥相同。
*/
-function attachInjectToRedteamPersona(sections, inject) {
+function attachInjectToRedteamPersona(sections, inject, roleText, cardText) {
let attached = false;
+ const role = typeof roleText === "string" ? roleText.trim() : "";
+ const card = typeof cardText === "string" ? cardText.trim() : "";
const next = sections.map((section) => {
const ops = redteamOpsBody(section?.text);
if (ops == null) return section;
attached = true;
- const text = inject ? `${inject}\n\n${ops}` : ops;
- return { ...section, text, order: -10000 };
+ const parts = [];
+ if (inject) parts.push(inject);
+ if (card) parts.push(card);
+ if (role) parts.push(role);
+ parts.push(ops);
+ return { ...section, text: parts.join("\n\n"), order: -10000 };
});
if (!attached) return sections;
return next.filter((section) => section?.name !== "dsh-purge");
}
+function insertCardSection(sections, cardText) {
+ const card = typeof cardText === "string" ? cardText.trim() : "";
+ if (!card) return sections;
+ if (sections.some((section) => String(section?.text || "").includes(card))) return sections;
+ const section = { name: "dsh-purge:objective", text: card, order: -9995 };
+ const purgeAt = sections.findIndex((item) => item?.name === "dsh-purge");
+ const next = sections.slice();
+ next.splice(purgeAt >= 0 ? purgeAt + 1 : 0, 0, section);
+ return next;
+}
+
+function insertRoleSection(sections, roleText) {
+ const role = typeof roleText === "string" ? roleText.trim() : "";
+ if (!role) return sections;
+ if (sections.some((section) => String(section?.text || "").includes(role))) return sections;
+ const section = { name: "dsh-purge:redteam-role", text: role, order: -9990 };
+ const purgeAt = sections.findIndex((item) => item?.name === "dsh-purge");
+ const next = sections.slice();
+ next.splice(purgeAt >= 0 ? purgeAt + 1 : 0, 0, section);
+ return next;
+}
+
function stripIdentityPrefix(text) {
let rest = String(text || "").trim();
if (rest.startsWith(IDENTITY_CARD_PREFIX)) {
@@ -241,6 +279,8 @@ function normalizeRewriteOptions(fallbackInject, options) {
dropMnemon: fallbackInject.dropMnemon !== false,
dropPurgeAfterFold: fallbackInject.dropPurgeAfterFold !== false,
context: fallbackInject.context,
+ roleText: typeof fallbackInject.roleText === "string" ? fallbackInject.roleText : "",
+ cardText: typeof fallbackInject.cardText === "string" ? fallbackInject.cardText : "",
};
}
return {
@@ -248,6 +288,8 @@ function normalizeRewriteOptions(fallbackInject, options) {
dropMnemon: options?.dropMnemon !== false,
dropPurgeAfterFold: options?.dropPurgeAfterFold !== false,
context: options?.context,
+ roleText: typeof options?.roleText === "string" ? options.roleText : "",
+ cardText: typeof options?.cardText === "string" ? options.cardText : "",
};
}
@@ -294,6 +336,9 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
}
const injectText = collectInjectText(purge, opts.fallbackInject);
+ const redteamChild = isRedteamSubagent(opts.context);
+ const roleText = redteamChild ? opts.roleText : "";
+ const cardText = opts.cardText.trim();
// #29: 不要把上一条 system/message 全文钉回 sections。
// 默认留下 dsh-purge 段。0.1.5 在 waterfall 之后若 complete:true,只认这段把注入抄进最终提示词;
// 提前折进 persona 再删掉本段,重启加载该逻辑后注入会丢。
@@ -301,9 +346,8 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
const extras = opts.dropPurgeAfterFold
? purge.filter((section) => section.name !== "dsh-purge")
: purge;
- assembled.sections = ensureFullInject(
- attachInjectToRedteamPersona([...folded, ...extras], injectText),
- injectText,
- );
+ const withPersona = attachInjectToRedteamPersona([...folded, ...extras], injectText, roleText, cardText);
+ const withRole = insertRoleSection(ensureFullInject(withPersona, injectText), roleText);
+ assembled.sections = redteamChild ? insertCardSection(withRole, cardText) : withRole;
return assembled;
}
diff --git a/lib/index.js b/lib/index.js
index 605cd28..750bf45 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -11,6 +11,11 @@ import {
isMnemonPluginMessage,
rewritePromptAssembly,
} from "./identity.js";
+import {
+ installSubagentRoleCapture,
+ resolveSubagentRoleText,
+} from "./redteam/role-section.js";
+import { readObjectiveCard } from "./redteam/objective-card.js";
import * as rewind from "./rewind.js";
import * as continueRetry from "./continue-retry.js";
import * as uninstaller from "./uninstall.js";
@@ -231,16 +236,25 @@ function installMnemonMessageStrip(ctx, config = {}) {
function rewriteLiveAssembly(config, assembled, context) {
const enabled = config.enabled !== false;
const inject = enabled ? readInjectFallback() : "";
+ let roleText = "";
+ let cardText = "";
+ if (enabled) {
+ try { roleText = resolveSubagentRoleText(context); } catch { roleText = ""; }
+ try { cardText = readObjectiveCard(); } catch { cardText = ""; }
+ }
return rewritePromptAssembly(assembled, {
fallbackInject: inject,
dropMnemon: config.stripMnemon !== false,
dropPurgeAfterFold: false,
context,
+ roleText,
+ cardText,
});
}
function installIdentityOverride(ctx, config = {}) {
if (typeof ctx.on !== "function") return;
+ installSubagentRoleCapture(ctx);
if (ctx.__dshPurgeAssembleHook) return;
ctx.__dshPurgeAssembleHook = true;
const hook = async (_assembly, context, next) => {
diff --git a/lib/redteam/client.js b/lib/redteam/client.js
index 8ec000a..63d620d 100644
--- a/lib/redteam/client.js
+++ b/lib/redteam/client.js
@@ -1214,7 +1214,7 @@ window.__ModuleLoader__.load({
placeholder: '该角色的系统提示词(Markdown)',
}),
h('div', { style: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', marginTop: 6 } },
- '保存后写入 agents/' + (active || 'role') + '.md,并在该角色会话的每次模型请求前注入。'))))
+ '保存后写入 agents/' + (active || 'role') + '.md。子会话任务第一行写 redteamRole: recon、assess、vuln-scan、exploit 或 internal 后,对应文件进入系统提示词。'))))
}
/* ---------------------------------------------------------- 技能库(DSH 原生) */
diff --git a/lib/redteam/index.js b/lib/redteam/index.js
index 97f8548..134a2a3 100644
--- a/lib/redteam/index.js
+++ b/lib/redteam/index.js
@@ -3,7 +3,7 @@
*
* 资产库、工具、预设、技能都在本插件目录内。本文件负责:
* 1. 首次把 `presets/redteam` 落到 `$DSH_HOME/.agent-presets/redteam/`
- * 2. 把技能目录写成 `skills/redteam` 的真实绝对路径
+ * 2. 随包技能落到 `$DSH_HOME/redteam/skills`,预设用 `dshHomePath` 指向它
* 3. 已有用户预设时只修失效路径 / 旧包名,不整份覆盖
*/
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
@@ -100,26 +100,26 @@ function isSkillsDirLine(line) {
|| /[/\\]skills[/\\]redteam\/?$/.test(text)
}
+/** 预设里随包技能那一行。加载时按当前 DSH_HOME 解析,不写本机绝对路径。 */
+const BUNDLED_SKILLS_EXPR = "!!js dshHomePath('redteam/skills')"
+
/**
- * 把预设正文里的技能目录占位符 / 失效的绝对路径渲染成**当前**包内 skills/ 路径。
+ * 把占位符或写死的本机路径改成 `dshHomePath('redteam/skills')`。
*
- * 为什么不能只替换占位符:
- * · 占位符没被替换时,YAML 会把它解析成对象 → `skill-filesystem` 配置校验失败
- * → **整个预设挂载失败** → 该会话建不了、发不出消息(v0.9.0 真出过这个事故:
- * 部署时把打包模板直接 cp 进了用户预设目录);
- * · 包换过位置(npx 缓存换了 hash、profile 重装、从源码包切到市场包)时,上次写下的
- * 绝对路径会指向不存在的目录 —— 技能"静默变少",比直接报错更难发现。
- * 两种都在这里就地修正;只有真的改动了才写盘。
+ * 占位符留在 YAML 里会被解析成对象,整个预设挂不上。写死
+ * `profiles/desktop/node_modules/...` 又只在这一台桌面安装上成立,
+ * Web、另一台机器、换过安装位置都会指空。技能文件由 installBundledSkills
+ * 放到 `$DSH_HOME/redteam/skills`。
*/
-function renderSkillsDir(text, skillsDir) {
+function renderSkillsDir(text) {
if (text.includes(SKILLS_PLACEHOLDER)) {
- return { text: text.split(SKILLS_PLACEHOLDER).join(skillsDir), changed: true, reason: 'placeholder' }
+ return { text: text.split(SKILLS_PLACEHOLDER).join(BUNDLED_SKILLS_EXPR), changed: true, reason: 'placeholder' }
}
let changed = false
const out = text.split('\n').map((line) => {
if (!isSkillsDirLine(line)) return line
const indent = /^(\s*)/.exec(line)[1]
- const wanted = indent + '- ' + skillsDir
+ const wanted = indent + '- ' + BUNDLED_SKILLS_EXPR
if (line === wanted) return line
changed = true
return wanted
@@ -127,6 +127,29 @@ function renderSkillsDir(text, skillsDir) {
return { text: out, changed, reason: changed ? 'stale-path' : 'none' }
}
+/**
+ * 把包内 `skills/redteam/*.md` 同步到 `$DSH_HOME/redteam/skills`。
+ * 同名文件按包内内容覆盖。用户自己的副本在 `$DSH_HOME/skills`,不在这里改。
+ */
+export function installBundledSkills() {
+ const paths = packagePaths()
+ const target = join(redteamDataDir(), 'skills')
+ if (!existsSync(paths.skills)) return { action: 'missing', path: target, copied: 0 }
+ mkdirSync(target, { recursive: true })
+ let copied = 0
+ for (const file of readdirSync(paths.skills)) {
+ if (!file.endsWith('.md')) continue
+ const wanted = readFileSync(join(paths.skills, file))
+ const dest = join(target, file)
+ let same = false
+ try { same = readFileSync(dest).equals(wanted) } catch { same = false }
+ if (same) continue
+ writeFileSync(dest, wanted)
+ copied += 1
+ }
+ return { action: copied > 0 ? 'updated' : 'kept', path: target, copied }
+}
+
/** 旧组合会把整份预设标 broken(worker-thread 未装 / tools 硬依赖 redteam)。 */
function needsCompositionRepair(presetFile) {
if (!existsSync(presetFile)) return true
@@ -154,14 +177,57 @@ function renderToolsPackage(text) {
}
}
+/** 包内锚点门相对预设模板的标记,用来给已有用户预设补一行,不整份覆盖。 */
+const ANCHOR_ROW_MARK = '- id: anchor-gate'
+
+/**
+ * 锚点门脚本每次用包内副本覆盖(没有用户可改状态)。
+ * 用户预设里还没有这一行时,插到 redteam-tools 前面。
+ * @returns {'inserted'|'updated'|'kept'|'missing'}
+ */
+function syncAnchorGate(targetDir) {
+ const src = join(packagePaths().presetDir, 'anchor-gate.mjs')
+ const dest = join(targetDir, 'anchor-gate.mjs')
+ if (!existsSync(src)) return 'missing'
+ mkdirSync(targetDir, { recursive: true })
+ const wanted = readFileSync(src, 'utf8')
+ let current = ''
+ try { current = readFileSync(dest, 'utf8') } catch { current = '' }
+ let script = 'kept'
+ if (current !== wanted) {
+ writeFileSync(dest, wanted, 'utf8')
+ script = 'updated'
+ }
+ const presetFile = join(targetDir, 'agent.cordis.yml')
+ if (!existsSync(presetFile)) return script
+ let text
+ try { text = readFileSync(presetFile, 'utf8') } catch { return script }
+ if (text.includes(ANCHOR_ROW_MARK)) return script
+ let template = ''
+ try { template = readFileSync(join(packagePaths().presetDir, 'agent.cordis.yml'), 'utf8') } catch { return script }
+ const start = template.indexOf('# 锚点门')
+ const end = template.indexOf('- id: redteam-tools')
+ if (start === -1 || end === -1 || start > end) return script
+ const block = template.slice(start, end).trim()
+ const nl = text.includes('\r\n') ? '\r\n' : '\n'
+ const rendered = block.replace(/\r\n/g, '\n').replace(/\n/g, nl)
+ const marker = '- id: redteam-tools'
+ const at = text.indexOf(marker)
+ const next = at === -1
+ ? text.replace(/\s*$/, '') + nl + nl + rendered + nl
+ : text.slice(0, at) + rendered + nl + nl + text.slice(at)
+ writeFileSync(presetFile, next, 'utf8')
+ return 'inserted'
+}
+
/**
* 把包内预设落地到用户 preset 根。
*
* 语义(v0.9.0 起):
* · 目标不存在 → 完整安装(占位符替换成真实路径);
* · 目标已存在 → **默认不覆盖用户内容,但会自愈**:只要里面还留着
- * `{{REDTEAM_SKILLS_DIR}}` 或指向不存在的旧包路径,就就地修正(这是唯一必需字段,
- * 不改就会整个预设挂载失败)。其余内容一律保留 —— 用户可以就地改预设。
+ * `{{REDTEAM_SKILLS_DIR}}` 或写死的本机技能路径,就改成 `dshHomePath('redteam/skills')`。
+ * 锚点门脚本会更新,缺了那一行会补上。其余内容保留。
* · `force: true` 才用包内模板整体覆盖。
*
* @param options - `{ force?: boolean, log?: (msg: string) => void }`
@@ -169,6 +235,7 @@ function renderToolsPackage(text) {
*/
export function installPreset(options = {}) {
const paths = packagePaths()
+ const bundled = installBundledSkills()
const target = join(userPresetRoot(), 'redteam')
const log = options.log ?? (() => {})
const skillCount = existsSync(paths.skills)
@@ -183,9 +250,9 @@ export function installPreset(options = {}) {
text = readFileSync(presetFile, 'utf8')
} catch (error) {
log(`读取 ${presetFile} 失败:${error && error.message ? error.message : String(error)}`)
- return { action: 'kept', dir: target, skillsDir: paths.skills, skills: skillCount }
+ return { action: 'kept', dir: target, skillsDir: bundled.path, skills: skillCount }
}
- const rendered = renderSkillsDir(text, paths.skills)
+ const rendered = renderSkillsDir(text)
const tools = renderToolsPackage(rendered.text)
const next = tools.text
if (rendered.changed || tools.changed) {
@@ -194,30 +261,42 @@ export function installPreset(options = {}) {
(rendered.changed
? (rendered.reason === 'placeholder'
? '预设里还留着 ' + SKILLS_PLACEHOLDER + '(会导致整个预设挂载失败)'
- : '预设里的技能目录指向已失效的旧包路径')
- + `,已就地修正为 ${paths.skills}`
+ : '预设里的技能目录写成了本机绝对路径')
+ + ',已改为 dshHomePath(\'redteam/skills\')'
: '')
+ (tools.changed ? (rendered.changed ? ';' : '') + '工具包名已改为 dsh-purge/redteam/tools' : ''),
)
+ }
+ const anchor = syncAnchorGate(target)
+ if (anchor === 'inserted') log('已把锚点门补进现有预设(其余内容保留)')
+ else if (anchor === 'updated') log('已更新锚点门脚本')
+ const repaired = [
+ rendered.changed ? rendered.reason : null,
+ tools.changed ? 'tools-package' : null,
+ anchor === 'inserted' ? 'anchor-gate' : null,
+ anchor === 'updated' ? 'anchor-script' : null,
+ ].filter(Boolean)
+ if (repaired.length > 0) {
return {
- action: 'repaired', dir: target, skillsDir: paths.skills, skills: skillCount,
- repaired: [rendered.changed ? rendered.reason : null, tools.changed ? 'tools-package' : null].filter(Boolean).join('+'),
+ action: 'repaired', dir: target, skillsDir: bundled.path, skills: skillCount,
+ repaired: repaired.join('+'),
}
}
log(`已存在用户自己的预设 ${target},保留不动(要覆盖:REDTEAM_PRESET_REFRESH=1 启动一次)`)
- return { action: 'kept', dir: target, skillsDir: paths.skills, skills: skillCount }
+ return { action: 'kept', dir: target, skillsDir: bundled.path, skills: skillCount }
}
mkdirSync(target, { recursive: true })
for (const file of readdirSync(paths.presetDir)) {
const text = readFileSync(join(paths.presetDir, file), 'utf8')
- const rendered = renderToolsPackage(renderSkillsDir(text, paths.skills).text).text
+ const rendered = renderToolsPackage(renderSkillsDir(text).text).text
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
writeFileSync(join(target, file), rendered, 'utf8')
}
- log(`预设已安装到 ${target}(打包技能 ${skillCount} 个:${paths.skills})`)
- return { action: 'installed', dir: target, skillsDir: paths.skills, skills: skillCount }
+ syncAnchorGate(target)
+ log(`预设已安装到 ${target}(随包技能 ${skillCount} 个,目录 ${bundled.path})`)
+ return { action: 'installed', dir: target, skillsDir: bundled.path, skills: skillCount }
}
/**
@@ -234,7 +313,7 @@ export function apply(ctx) {
})
} catch (error) {
ctx.logger?.error?.('redteam-mode: 预设安装失败:%s', error && error.message ? error.message : String(error))
- result = { action: 'failed', dir: join(userPresetRoot(), 'redteam'), skillsDir: paths.skills, skills: 0 }
+ result = { action: 'failed', dir: join(userPresetRoot(), 'redteam'), skillsDir: join(redteamDataDir(), 'skills'), skills: 0 }
}
let setupResult
try {
@@ -259,7 +338,7 @@ export function apply(ctx) {
writeFileSync(statusFile, JSON.stringify({ ...prev, ...patch, at: new Date().toISOString() }, null, 2), 'utf8')
} catch { /* ignore */ }
}
- writeStatus({ ok: false, phase: 'apply-start', skillsDir: paths.skills, presetDir: result.dir })
+ writeStatus({ ok: false, phase: 'apply-start', skillsDir: result.skillsDir, presetDir: result.dir })
let releaseDeclared
let closed = false
@@ -347,14 +426,16 @@ export function apply(ctx) {
return true
}
let timer
+ let stop
if (!tick()) {
timer = setInterval(() => {
if (tick()) {
clearInterval(timer)
timer = undefined
+ if (stop) clearTimeout(stop)
}
}, 400)
- const stop = setTimeout(() => {
+ stop = setTimeout(() => {
if (timer) {
clearInterval(timer)
timer = undefined
@@ -366,6 +447,7 @@ export function apply(ctx) {
return () => {
closed = true
if (timer) clearInterval(timer)
+ if (stop) clearTimeout(stop)
void undeclare()
}
}, 'dsh-purge-redteam: declare agent preset')
diff --git a/lib/redteam/objective-card.js b/lib/redteam/objective-card.js
new file mode 100644
index 0000000..d9849e5
--- /dev/null
+++ b/lib/redteam/objective-card.js
@@ -0,0 +1,51 @@
+/**
+ * 当前靶标的目标卡。指挥和子会话拼系统提示词时放在清洗稿后面。
+ * 只读 redteam/current 和 engagement.yaml,不打开工具模块,也不开 sqlite。
+ */
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { redteamRoot } from "./platform-config.js";
+
+function safeEngagementId(id) {
+ const text = String(id || "").trim();
+ if (!text || text.length > 200) return "";
+ if (text.includes("..") || text.includes("/") || text.includes("\\") || text.includes("\0")) return "";
+ return text;
+}
+
+function readMeta(path) {
+ if (!existsSync(path)) return null;
+ const out = {};
+ for (const line of readFileSync(path, "utf8").split("\n")) {
+ const matched = /^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/.exec(line);
+ if (!matched) continue;
+ const value = matched[2].trim();
+ if (value.startsWith("[") && value.endsWith("]")) {
+ out[matched[1]] = value.slice(1, -1).split(",").map((item) => item.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
+ } else {
+ out[matched[1]] = value.replace(/^["']|["']$/g, "");
+ }
+ }
+ return out;
+}
+
+/** 没有当前靶标时返回空串,不编一个目标。 */
+export function readObjectiveCard(root = redteamRoot()) {
+ try {
+ const id = safeEngagementId(readFileSync(join(root, "current"), "utf8"));
+ if (!id) return "";
+ const meta = readMeta(join(root, "engagements", id, "engagement.yaml"));
+ const name = String(meta?.target_name || "").trim();
+ if (!name) return "";
+ const scope = Array.isArray(meta.scope_cidrs) ? meta.scope_cidrs.map((item) => String(item).trim()).filter(Boolean) : [];
+ const scopeLine = scope.length > 0 ? scope.join("、") : "只打这个单位名下的资产";
+ return [
+ "## 本次目标",
+ `只打:${name}`,
+ `范围:${scopeLine}`,
+ "不打:回报里带出来的其它单位。只有用户明确说出新的单位名称,才改打新目标。",
+ ].join("\n");
+ } catch {
+ return "";
+ }
+}
diff --git a/lib/redteam/platform-config.js b/lib/redteam/platform-config.js
index fff914a..2fc5591 100644
--- a/lib/redteam/platform-config.js
+++ b/lib/redteam/platform-config.js
@@ -9,7 +9,7 @@
*
* 借鉴 Z3r0:系统配置集中、可在 UI 里改(FOFA / 路径类),而不是只靠 shell 引导。
*/
-import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, statSync } from 'node:fs'
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from 'node:fs'
import { homedir, platform as osPlatform } from 'node:os'
import { delimiter, isAbsolute, join, resolve, sep } from 'node:path'
@@ -43,11 +43,12 @@ export const TOOL_CATALOG = [
{ id: 'frps', label: 'frp 服务端', names: ['frps.exe', 'frps'] },
{ id: 'chisel', label: 'chisel', names: ['chisel.exe', 'chisel'] },
{ id: 'ffuf', label: 'ffuf', names: ['ffuf.exe', 'ffuf'] },
- { id: 'httpx', label: 'httpx', names: ['httpx.exe', 'httpx'] },
+ /* names 是候选文件名,不是某台机器的绝对路径。adapt 是发行版常见别名,目录里碰见才用。 */
+ { id: 'httpx', label: 'httpx', names: ['httpx-toolkit', 'pd-httpx', 'httpx.exe', 'httpx'], rejectPython: true, adapt: [/^httpx-toolkit$/, /^pd-httpx$/, /^httpx$/] },
{ id: 'dnsx', label: 'dnsx', names: ['dnsx.exe', 'dnsx'] },
{ id: 'subfinder', label: 'subfinder', names: ['subfinder.exe', 'subfinder'] },
{ id: 'ksubdomain', label: 'ksubdomain', names: ['ksubdomain.exe', 'ksubdomain'] },
- { id: 'impacket', label: 'impacket(目录或入口)', names: ['impacket-secretsdump.exe', 'secretsdump.py', 'impacket'] },
+ { id: 'impacket', label: 'impacket(目录或入口)', names: ['impacket-secretsdump', 'impacket-secretsdump.exe', 'secretsdump.py', 'impacket'], adapt: [/^impacket-secretsdump$/, /^secretsdump\.py$/] },
]
const EMPTY = () => ({
@@ -165,7 +166,24 @@ export function nucleiTemplatesDirOf(cfg, root) {
/**
* 在目录里找可执行名(浅扫一层 + 常见子目录 bin/)。
*/
-function findInDir(dir, names) {
+function looksLikePythonCli(file) {
+ let fd
+ try {
+ const buf = Buffer.alloc(96)
+ fd = openSync(file, 'r')
+ const n = readSync(fd, buf, 0, buf.length, 0)
+ const head = buf.subarray(0, n).toString('utf8')
+ return head.startsWith('#!') && /python/i.test(head)
+ } catch {
+ return false
+ } finally {
+ if (fd !== undefined) {
+ try { closeSync(fd) } catch { /* ignore */ }
+ }
+ }
+}
+
+function findInDir(dir, names, options = {}) {
if (!dir || !existsSync(dir)) return null
const tryOne = (base) => {
for (const name of names) {
@@ -173,32 +191,68 @@ function findInDir(dir, names) {
if (existsSync(p)) {
try {
const st = statSync(p)
- if (st.isFile()) return p
+ if (!st.isFile()) continue
+ if (options.rejectPython && looksLikePythonCli(p)) continue
+ return p
} catch { /* continue */ }
}
}
return null
}
- const hit = tryOne(dir)
+ const hit = tryOne(dir) || adaptInDir(dir, options)
if (hit) return hit
for (const sub of ['bin', 'Bins', 'tools', 'Tools']) {
- const nested = tryOne(join(dir, sub))
+ const nested = tryOne(join(dir, sub)) || adaptInDir(join(dir, sub), options)
if (nested) return nested
}
return null
}
+/** 精确文件名没有时,用发行版别名在这一层目录里对。对上才算找到。 */
+function adaptInDir(dir, options) {
+ const patterns = options.adapt
+ if (!dir || !Array.isArray(patterns) || patterns.length === 0 || !existsSync(dir)) return null
+ let names
+ try { names = readdirSync(dir) } catch { return null }
+ for (const pattern of patterns) {
+ for (const name of names) {
+ if (!pattern.test(String(name).toLowerCase())) continue
+ const file = join(dir, name)
+ try {
+ if (!statSync(file).isFile()) continue
+ if (options.rejectPython && looksLikePythonCli(file)) continue
+ return file
+ } catch { /* continue */ }
+ }
+ }
+ return null
+}
+
/** PATH 上的 which(仅同步、不 spawn shell)。 */
-function findOnPath(names, env = process.env) {
+function findOnPath(names, env = process.env, options = {}) {
const pathVar = env.PATH || env.Path || ''
const parts = pathVar.split(delimiter).filter(Boolean)
for (const part of parts) {
- const hit = findInDir(part, names)
+ const hit = findInDir(part, names, options)
if (hit) return hit
}
return null
}
+/** dsh 的 PATH 经常比登录 shell 短。Linux 再补发行版和用户目录。 */
+function linuxFallbackDirs(env = process.env) {
+ const home = env.HOME || homedir()
+ const dirs = ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/bin', '/snap/bin']
+ if (home) {
+ dirs.push(
+ join(home, 'go', 'bin'),
+ join(home, '.local', 'bin'),
+ join(home, '.pdtm', 'go', 'bin'),
+ )
+ }
+ return dirs
+}
+
/**
* 解析单个工具:用户指定路径 → toolkit → binDirs → PATH。
* @returns `{ id, label, path, source: 'config'|'toolkit'|'binDir'|'path'|'missing', names }`
@@ -219,18 +273,26 @@ export function resolveTool(id, options = {}) {
}
return { id, label: def.label, path: null, source: 'missing', names: def.names, configured: abs, note: 'config 路径不存在:' + abs }
}
+ const findOpts = { rejectPython: !!def.rejectPython, adapt: def.adapt }
const toolkit = toolkitDirOf(cfg, root)
- const fromToolkit = findInDir(toolkit, def.names)
+ const fromToolkit = findInDir(toolkit, def.names, findOpts)
if (fromToolkit) return { id, label: def.label, path: fromToolkit, source: 'toolkit', names: def.names }
for (const dir of cfg.binDirs || []) {
- const hit = findInDir(dir, def.names)
+ const hit = findInDir(dir, def.names, findOpts)
if (hit) return { id, label: def.label, path: hit, source: 'binDir', names: def.names, binDir: dir }
}
- const fromPath = findOnPath(def.names, env)
+ const fromPath = findOnPath(def.names, env, findOpts)
if (fromPath) return { id, label: def.label, path: fromPath, source: 'path', names: def.names }
+ if (!isWinLike(cfg)) {
+ for (const dir of linuxFallbackDirs(env)) {
+ const hit = findInDir(dir, def.names, findOpts)
+ if (hit) return { id, label: def.label, path: hit, source: 'path', names: def.names }
+ }
+ }
+
return { id, label: def.label, path: null, source: 'missing', names: def.names }
}
@@ -286,7 +348,7 @@ export function platformSummary(root) {
},
adapt,
hint: adapt.kali
- ? '已检测到 Kali(或同系演练机):工具走 PATH/默认查找,可直接开红队会话。'
+ ? '已检测到 Kali。系统包按发行版文件名认:impacket-secretsdump、httpx-toolkit(不把 Python 的 /usr/bin/httpx 当成扫描器)。fscan、gogo、suo5、frp、chisel、dnsx、subfinder、ksubdomain 不是 Kali 自带命令,没放进 /usr/bin 或 ~/go/bin 就会显示未找到。'
: (win
? '当前按 Windows 适配:建议在 Kali 虚拟机里跑,或在本页填工具路径/整包文件夹自动分配。出网代理看下方「出网状态」。'
: '当前按 Linux 适配:可用 setup.sh 装工具箱,也可在本页手填或整包文件夹自动分配。出网代理看下方「出网状态」。'),
@@ -355,6 +417,7 @@ export function scanFolderForTools(dir, options = {}) {
}
let scanned = 0
+ const ranks = {}
const walk = (base, depth) => {
if (scanned >= maxFiles || depth > maxDepth) return
let entries
@@ -387,7 +450,12 @@ export function scanFolderForTools(dir, options = {}) {
const ids = NAME_TO_IDS.get(key)
if (!ids) continue
for (const id of ids) {
- if (assigned[id]) continue
+ const def = TOOL_CATALOG.find((t) => t.id === id)
+ if (def && def.rejectPython && looksLikePythonCli(full)) continue
+ const rank = def ? def.names.findIndex((n) => n.toLowerCase() === key) : 99
+ const prevRank = ranks[id] === undefined ? 99 : ranks[id]
+ if (assigned[id] && rank >= prevRank) continue
+ ranks[id] = rank < 0 ? 99 : rank
assigned[id] = full
hits.push({ id, path: full, name })
}
diff --git a/lib/redteam/role-section.js b/lib/redteam/role-section.js
new file mode 100644
index 0000000..678e173
--- /dev/null
+++ b/lib/redteam/role-section.js
@@ -0,0 +1,133 @@
+/**
+ * 红队子会话的角色稿。
+ *
+ * 指挥派活时在任务第一行写 `redteamRole: `。
+ * 子会话领到这条用户消息时记下角色,组装系统提示词时把
+ * `engagements/<靶标>/agents/.md` 原样放进清洗稿和运行环境前提之间。
+ * 没有这一行就不猜角色。
+ */
+import { existsSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { redteamRoot } from './platform-config.js'
+
+const ROLE_TAG = /^[ \t]*redteamRole:[ \t]*(recon|assess|vuln-scan|exploit|internal)[ \t]*$/im
+
+const roleBySession = new Map()
+
+export function parseRedteamRole(text) {
+ const matched = String(text || '').match(ROLE_TAG)
+ return matched ? matched[1].toLowerCase() : ''
+}
+
+export function textOfMessage(message) {
+ if (!message) return ''
+ if (typeof message === 'string') return message
+ const content = message.content ?? message.text
+ if (typeof content === 'string') return content
+ if (!Array.isArray(content)) return ''
+ return content.map((block) => (typeof block?.text === 'string' ? block.text : '')).join('\n')
+}
+
+function remember(agent, role) {
+ const ids = [agent?.session?.id, agent?.id].filter((id) => id !== undefined && id !== null)
+ for (const id of ids) roleBySession.set(String(id), role)
+}
+
+function isRedteamChild(session) {
+ const header = session?.header
+ return header?.origin === 'subagent' && header?.agentPreset === 'redteam'
+}
+
+export function noteClaimedMessage(payload) {
+ const agent = payload?.agent
+ const session = agent?.session
+ if (!isRedteamChild(session)) return
+ const role = parseRedteamRole(textOfMessage(payload?.message))
+ if (!role) return
+ remember(agent, role)
+}
+
+function roleFromSessionEvents(session) {
+ const events = []
+ try {
+ if (typeof session?.snapshotEvents === 'function') {
+ const got = session.snapshotEvents()
+ if (Array.isArray(got)) events.push(...got)
+ }
+ } catch { /* 读不到历史就只用已记下的角色 */ }
+ if (Array.isArray(session?.events)) events.push(...session.events)
+ let found = ''
+ for (const event of events) {
+ if (!event || event.type !== 'user/message') continue
+ const data = event.data
+ const role = parseRedteamRole(textOfMessage(data?.message || data))
+ if (role) found = role
+ }
+ return found
+}
+
+function safeEngagementId(id) {
+ const text = String(id || '').trim()
+ if (!text || text.length > 200) return ''
+ if (text.includes('..') || text.includes('/') || text.includes('\\') || text.includes('\0')) return ''
+ return text
+}
+
+function currentEngagementId() {
+ try {
+ const root = redteamRoot()
+ const id = safeEngagementId(readFileSync(join(root, 'current'), 'utf8'))
+ if (!id) return ''
+ if (!existsSync(join(root, 'engagements', id, 'agents'))) return ''
+ return id
+ } catch {
+ return ''
+ }
+}
+
+function readRoleFile(engagementId, role) {
+ const id = safeEngagementId(engagementId)
+ if (!id || !parseRedteamRole('redteamRole: ' + role)) return ''
+ try {
+ const path = join(redteamRoot(), 'engagements', id, 'agents', role + '.md')
+ if (!existsSync(path)) return ''
+ return readFileSync(path, 'utf8').trim()
+ } catch {
+ return ''
+ }
+}
+
+export function resolveSubagentRoleText(context) {
+ try {
+ const session = context?.agent?.session || context?.session
+ if (!isRedteamChild(session)) return ''
+ const agent = context?.agent
+ const sessionId = session?.id ?? agent?.id
+ let role = sessionId !== undefined && sessionId !== null
+ ? roleBySession.get(String(sessionId)) || ''
+ : ''
+ if (!role) {
+ role = roleFromSessionEvents(session)
+ if (role) remember(agent || { session }, role)
+ }
+ if (!role) return ''
+ return readRoleFile(currentEngagementId(), role)
+ } catch {
+ return ''
+ }
+}
+
+export function installSubagentRoleCapture(ctx) {
+ if (!ctx || typeof ctx.on !== 'function') return
+ if (ctx.__dshPurgeRoleCapture) return
+ ctx.__dshPurgeRoleCapture = true
+ const hook = (payload) => {
+ try { noteClaimedMessage(payload) } catch { /* 记角色失败不阻断领消息 */ }
+ }
+ const install = () => {
+ try { ctx.on('agent/inbox/claimed', hook, { global: true, prepend: true }) } catch { /* ignore */ }
+ }
+ install()
+ queueMicrotask(install)
+ setTimeout(install, 800)
+}
diff --git a/lib/redteam/store-core.js b/lib/redteam/store-core.js
index 666f347..af49a36 100644
--- a/lib/redteam/store-core.js
+++ b/lib/redteam/store-core.js
@@ -483,8 +483,8 @@ export const DEFAULT_PROMPTS = {
5. **用户问进度 / 要报告**:用 \`redteam_score_list\`、\`redteam_attack_chain\`、\`redteam_asset_stats\`、\`redteam_sessions\` 读实际数据回答,并告诉他下一步你打算派谁。
## 派活方式
-- 用原生 \`subagent\` 工具派活,**任务描述必须是自包含的**(子智能体看不到你的上下文):把目标、已知资产与入口(贴真实值:隧道监听地址、WebShell URL、凭据)、已测过的清单、期望产出、以及"不要再往下委派"写进去。
-- 子任务里带上该角色的职责边界(见下面各角色提示词要点),别让信息收集去测漏洞、别让漏洞发现去打内网。
+- 用原生 \`subagent\` 工具派活。\`prompt\` 的**第一行**必须是 \`redteamRole: \`,code 只能是 \`recon\` / \`assess\` / \`vuln-scan\` / \`exploit\` / \`internal\`。这一行让 \`agents/.md\` 进入子会话系统提示词。**不要**把 \`redteam_role_prompt\` 的全文抄进任务。
+- 第一行之后只写自包含任务:目标、已知资产与入口(贴真实值:隧道监听地址、WebShell URL、凭据)、已测过的清单、期望产出,以及"不要再往下委派"。单位名称必须和系统提示词里的「本次目标」一致。别让信息收集去测漏洞、别让漏洞发现去打内网。
- **子智能体落库后,你负责核对**:读 \`redteam_asset_stats\` / \`redteam_vuln_query\` / \`redteam_sessions\` 看它说的成果是不是真的落了库、有没有证据(原始请求、命令、回显)。**没落库的成果不算成果**,让它补。
- 子智能体是叶子节点,不会再有下级;它们结束后你可以继续派新的,**不要在同一时刻超过 3 个**。
diff --git a/lib/redteam/tools.js b/lib/redteam/tools.js
index 5273289..6dc4f1f 100644
--- a/lib/redteam/tools.js
+++ b/lib/redteam/tools.js
@@ -14,8 +14,9 @@
* 卡住"同一靶标最多 3 个执行智能体",超了直接拒绝,不靠提示词自觉。
*/
import { createRequire } from 'node:module'
-import { existsSync } from 'node:fs'
-import { join } from 'node:path'
+import { existsSync, realpathSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { dirname, join } from 'node:path'
import { ROLE_TITLES, PLANNER_ROLE, ROLE_ORDER } from './store-core.js'
/* 技能可用性判定只有一份实现:面板的「技能库」页签与这里共用(见该文件头注释) */
import { checkSkill, summarizeSkills, expandSkillPath } from './skill-availability.js'
@@ -31,26 +32,40 @@ import {
* 会解析失败 → 预设行 fiber 为 undefined(never started)→ 整份「红队模式」被下拉过滤。
* 这里从运行中的 dsh / profile 路径 createRequire。
*/
+function addCandidate(list, pkg) {
+ if (!pkg) return
+ const norm = String(pkg).replace(/\\/g, '/')
+ if (!list.includes(norm)) list.push(norm)
+}
+
+function considerBin(list, bin) {
+ if (!bin) return
+ let text = String(bin).replace(/\\/g, '/')
+ try { text = realpathSync(bin).replace(/\\/g, '/') } catch { /* 解析不了就用原路径 */ }
+ const needle = '/node_modules/@deepseek-ai/dsh/'
+ const at = text.lastIndexOf(needle)
+ if (at >= 0) addCandidate(list, text.slice(0, at + needle.length - 1) + '/package.json')
+ const nm = text.lastIndexOf('/node_modules/')
+ if (nm >= 0) addCandidate(list, join(text.slice(0, nm), 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
+ const dir = dirname(text)
+ /* npm 全局的 argv 常常是 …/bin/dsh,真正的包在旁边的 lib/node_modules。 */
+ addCandidate(list, join(dir, '..', 'lib', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
+ addCandidate(list, join(dir, '..', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
+}
+
function loadDefineTool() {
const candidates = []
- try {
- const bin = String(process.argv[1] || '').replace(/\\/g, '/')
- const needle = '/node_modules/@deepseek-ai/dsh/'
- const at = bin.lastIndexOf(needle)
- if (at >= 0) {
- candidates.push(join(bin.slice(0, at + '/node_modules/@deepseek-ai/dsh'.length), 'package.json'))
+ try { considerBin(candidates, process.argv[1]) } catch { /* ignore */ }
+ const homes = [process.env.DSH_HOME, join(homedir(), '.dsh')].filter(Boolean)
+ for (const home of homes) {
+ addCandidate(candidates, join(home, 'package.json'))
+ for (const profile of ['web', 'desktop', 'default']) {
+ addCandidate(candidates, join(home, 'profiles', profile, 'package.json'))
+ addCandidate(candidates, join(home, 'profiles', profile, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
}
- const nm = bin.lastIndexOf('/node_modules/')
- if (nm >= 0) {
- candidates.push(join(bin.slice(0, nm), 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
- }
- } catch { /* ignore */ }
- if (process.env.DSH_HOME) {
- candidates.push(join(process.env.DSH_HOME, 'profiles', 'web', 'package.json'))
- candidates.push(join(process.env.DSH_HOME, 'package.json'))
}
- candidates.push(join(process.cwd(), 'package.json'))
- candidates.push(join('D:', 'DeepSeek Harness', 'npm-global', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
+ addCandidate(candidates, join(process.cwd(), 'package.json'))
+ addCandidate(candidates, join('D:', 'DeepSeek Harness', 'npm-global', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
for (const pkg of candidates) {
try {
if (!pkg || !existsSync(pkg)) continue
@@ -238,7 +253,23 @@ const text = (value) => [{ type: 'text', text: typeof value === 'string' ? value
/** 角色 code 的合法值说明(写进工具 description,模型不用猜)。 */
const ROLE_HINT = '角色 code:' + ROLE_ORDER.map((r) => '`' + r + '`(' + ROLE_TITLES[r] + ')').join('、')
-/** 当前会话的绑定键(根会话 + 本会话 + 父链),用于把绑定写全。 */
+/** 子会话组装角色稿时用:沿父链找到本进程里已绑定的靶标。没有就返回 undefined。 */
+export function engagementIdForSession(session) {
+ if (!session) return undefined
+ try {
+ const info = sessionInfoOf({ agent: { session } })
+ if (info.id === undefined) return undefined
+ const resolved = resolveRootSession(session)
+ const rootId = resolved.rootId === undefined ? info.id : resolved.rootId
+ const keys = Array.from(new Set([rootId, info.id, ...resolved.chain].filter(Boolean)))
+ for (const key of keys) {
+ const bound = bindings.get(key)
+ if (typeof bound === 'string' && bound.length > 0) return bound
+ }
+ } catch { /* 解析失败就交给 current 指针 */ }
+ return undefined
+}
+
function bindKeysOf(exec) {
const { rootId, sessionId, chain } = bindingKeyOf(exec)
return Array.from(new Set([rootId, sessionId, ...chain].filter(Boolean)))
@@ -907,7 +938,7 @@ export function apply(ctx) {
ctx.tools.register(withStructuredErrors(defineTool({
name: 'redteam_role_prompt',
- description: '取出某个红队角色(信息收集/漏洞检测/漏洞利用/内网渗透)当前生效的系统提示词。委派子智能体时,把该提示词作为角色约束放进任务描述。',
+ description: '取出某个红队角色当前生效的系统提示词,只供查看。派活时不要把全文抄进任务;在 subagent 的 prompt 第一行写 redteamRole: ,角色稿会进入子会话系统提示词。',
parameters: {
engagement: { type: 'string' },
role: { type: 'string', required: true, /* 角色白名单**从 ROLE_ORDER 派生**:写死 4 个值曾漏掉 assess,
diff --git a/lib/surface.js b/lib/surface.js
index becd574..583087b 100644
--- a/lib/surface.js
+++ b/lib/surface.js
@@ -47,7 +47,9 @@ export function isDesktopSurface(input = {}) {
name === "dsh desktop.exe" ||
name === "dsh desktop" ||
name === "deepseek harness.exe" ||
- name === "deepseek-harness.exe"
+ name === "deepseek-harness.exe" ||
+ name === "deepseek harness" ||
+ name === "deepseek-harness"
) return true;
if (pathLooksDesktop(execPath)) return true;
diff --git a/package.json b/package.json
index 60e8cbe..a99af2f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "dsh-purge",
- "version": "1.1.37",
+ "version": "1.1.38",
"description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,内嵌演练台;不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐",
"type": "module",
"main": "lib/index.js",
@@ -35,17 +35,7 @@
],
"scripts": {
"embed-prompt": "node scripts/embed-default-prompt.mjs",
- "build:client": "node scripts/build-client.mjs",
- "test:identity": "node scripts/test-identity-assembly.mjs",
- "test:yaml": "node scripts/test-yaml-comment.mjs",
- "test:update": "node scripts/test-update-guards.mjs",
- "test:zip": "node scripts/test-zip-extract.mjs",
- "test:templates": "node scripts/test-template-page.mjs",
- "test:skills": "node scripts/test-skill-availability.mjs",
- "test:rewind": "node scripts/test-rewind-plan.mjs",
- "test:idempotence": "node scripts/test-patch-idempotence.mjs",
- "test:surface": "node scripts/test-surface-desktop.mjs",
- "test:profile-patch": "node scripts/test-user-profile-patch.mjs"
+ "build:client": "node scripts/build-client.mjs"
},
"license": "MIT",
"keywords": [
diff --git a/presets/redteam/agent.cordis.yml b/presets/redteam/agent.cordis.yml
index 00af576..8064b7c 100644
--- a/presets/redteam/agent.cordis.yml
+++ b/presets/redteam/agent.cordis.yml
@@ -60,9 +60,10 @@
## 并发硬约束(最多 3 个,默认顺序派)
- **同一靶标同时最多 3 个执行智能体**。派活前先 `redteam_agent_slot`(action=status)看名额;要派就 action=acquire 占位;被拒就是满了,**不要重试硬塞**,等现有智能体回报。
- **默认一个一个派、按顺序推进**;只有确实互不依赖的活才并行,且总数 ≤ 3。
- - 每个子任务描述必须**自包含**:目标范围、已知信息、**已经测过什么(避免重复打)**、可用入口(贴真实值:隧道监听地址 / WebShell URL / 凭据)、期望产出(落什么库)、以及"你是叶子节点,不要再往下委派"。
+ - \`subagent\` 的 \`prompt\` **第一行**必须是 \`redteamRole: \`,code 只能是 \`recon\`、\`assess\`、\`vuln-scan\`、\`exploit\`、\`internal\`。这一行把 \`agents/.md\` 放进子会话系统提示词。**不要**把 \`redteam_role_prompt\` 的全文抄进任务。
+ - 第一行之后必须**自包含**:目标范围、已知信息、**已经测过什么(避免重复打)**、可用入口(贴真实值:隧道监听地址 / WebShell URL / 凭据)、期望产出(落什么库)、以及"你是叶子节点,不要再往下委派"。单位名称必须和系统提示词里的「本次目标」一致。
- ## 六个角色(用 redteam_role_prompt 取完整职责,写进子任务描述)
+ ## 六个角色(职责在子会话系统提示词里,这里只作派谁的索引)
- `recon` **信息收集**:只收集资产、把靶标单位的资产**收集完整**(被动 FOFA/crt.sh + 主动探测,重点边缘资产与未备案资产),**不碰漏洞检测**。
- `assess` **资产梳理**:把收集到的资产**一条一条过**,评估易打性(priority/potential/reason)并**全部落库**,产出"先打谁"的排序。
- `vuln-scan` **漏洞发现**:逐条过资产,**先查库避免重复劳动** → 优先 Nday/1day → 再提取前端接口探未授权 → 每条漏洞落库 + 原始请求。
@@ -114,6 +115,17 @@
- **自己的 VPS / 自建服务器上开的代理不算隧道**:隧道必须说清目标侧那一端(`entry_kind`)。
- 报告只收录拿到分的成果,且每条要能复现(目标 → 拿到什么 → 怎么拿到的(命令)→ 原始请求)。
+# 锚点门:第一段思考含 we 且不含 let me 才放开 1024 输出上限;锚不住最多 4 步。
+# 不裁工具、不换人设。压缩后再关一次。放开后工作区长说明改成点名文件。
+- id: anchor-gate
+ name: ./anchor-gate.mjs
+ config:
+ anchorGate: true
+ maxBootstrapSteps: 4
+ promoteAfterFirstResponse: true
+ bootstrapMaxTokens: 1024
+ instructionHint: true
+
- id: redteam-tools
name: dsh-purge/redteam/tools
@@ -177,10 +189,9 @@
# 迁入 $DSH_HOME/skills,技能库页面只做浏览。
- id: skill-filesystem
name: '@deepseek-ai/dsh-skill-filesystem'
- # 红队技能随包分发:__REDTEAM_SKILLS_DIR__ 由插件首次启动时替换成包内 skills/ 的绝对路径。
- # 技能根**顺序即优先级**(同名技能取先出现的那份):$DSH_HOME/skills 必须排在包内目录前面,
- # 否则用户在自己那份里配好的 VPS 地址 / 密钥会被随包模板(里面是 `<你的VPS_IP>` 这类占位符)盖住,
- # 连技能可用性判定都会误报成"技能坏了"。
+ # 随包技能在 $DSH_HOME/redteam/skills,由插件启动时从包内同步。
+ # 技能根顺序即优先级(同名取先出现的那份):$DSH_HOME/skills 必须排在前面,
+ # 否则用户在自己那份里配好的 VPS 地址 / 密钥会被随包模板(里面是 `<你的VPS_IP>` 这类占位符)盖住。
config:
# 只扫描"$DSH_HOME/skills + 本插件自带的"两个根:
# 关掉 includeDefaultRoots,避免把 .agents/skills、项目级的大技能包(动辄数百个)
@@ -188,7 +199,7 @@
includeDefaultRoots: false
customSkillDirs:
- !!js dshHomePath('skills')
- - {{REDTEAM_SKILLS_DIR}}
+ - !!js dshHomePath('redteam/skills')
- id: tool-skill
name: '@deepseek-ai/dsh-tool-skill'
diff --git a/presets/redteam/anchor-gate.mjs b/presets/redteam/anchor-gate.mjs
new file mode 100644
index 0000000..fef958c
--- /dev/null
+++ b/presets/redteam/anchor-gate.mjs
@@ -0,0 +1,216 @@
+/**
+ * 红队锚点门。
+ *
+ * 只接梁神两阶段里这一段,不接两工具裁剪,也不切 PTC:
+ * 第一段思考要像官方 Minimal(含 we、不含 let me)才放开输出上限;
+ * 锚不住则最多 4 步。上限 1024 token,放开后拆掉,避免焊死在后面的请求上。
+ * 上下文压缩把模型可见的表面整段重写,压缩后再关上,直到新的锚点或再走满 4 步。
+ *
+ * 红队指挥和执行角色一直看见原来的工具和人设。放开之后,整篇工作区说明
+ * 改成点名文件路径,需要时再读。
+ */
+export const name = 'dsh-purge-redteam-anchor'
+
+const INSTRUCTION_FROM_RE = /(?:^|\n) *(?:Additional |Updated )?Instructions from: ([^\n]+)/g
+
+export function countWord(text, regex) {
+ return [...String(text ?? '').matchAll(regex)].length
+}
+
+/** 第一段思考:有 we、没有 let me,才算锚住。 */
+export function classifyReasoning(text) {
+ const trimmed = String(text ?? '').trim()
+ const we = countWord(trimmed, /\bwe\b/gi)
+ const letMe = countWord(trimmed, /\blet me\b/gi)
+ if (we > 0 && letMe === 0) return { label: 'minimal-like', we, letMe }
+ if (letMe > 0) return { label: 'standard-like', we, letMe }
+ return { label: 'ambiguous', we, letMe }
+}
+
+export function hasAnchoredReasoning(content) {
+ if (!Array.isArray(content)) return false
+ const first = content.find(block => block?.type === 'reasoning')
+ return first !== undefined && classifyReasoning(first.text).label === 'minimal-like'
+}
+
+/**
+ * a) 用过工具且锚住,或已经走满 maxBootstrapSteps → 放开;
+ * b) 用过工具,这一轮结束,且 promoteAfterFirstResponse → 放开;
+ * c) 没有工具调用但已经回答,且 promoteAfterFirstResponse → 放开。
+ */
+export function decidePromotion(state, config) {
+ if (state.toolCalled && config.anchorGate !== true) return true
+ if (state.toolCalled && config.anchorGate === true && (state.anchored || state.steps >= config.maxBootstrapSteps)) return true
+ if (state.toolCalled && config.anchorGate === true && config.promoteAfterFirstResponse === true && state.turnEnded) return true
+ if (!state.toolCalled && state.responded && config.promoteAfterFirstResponse === true) return true
+ return false
+}
+
+function integerAtLeast(value, fallback, minimum) {
+ const number = typeof value === 'number'
+ ? value
+ : typeof value === 'string' && /^-?\d+$/.test(value.trim())
+ ? Number(value)
+ : Number.NaN
+ if (!Number.isInteger(number) || number < minimum) return fallback
+ return number
+}
+
+function extractInstructionPaths(message) {
+ const paths = []
+ const blocks = Array.isArray(message?.content) ? message.content : []
+ for (const block of blocks) {
+ if (block?.type !== 'text' || typeof block.text !== 'string') continue
+ for (const match of block.text.matchAll(INSTRUCTION_FROM_RE)) {
+ const path = match[1].trim()
+ if (path !== '' && !paths.includes(path)) paths.push(path)
+ }
+ }
+ return paths
+}
+
+function buildInstructionHint(original, paths) {
+ return {
+ id: typeof original?.id === 'string' && original.id !== ''
+ ? original.id
+ : globalThis.crypto.randomUUID(),
+ role: 'user',
+ content: [{
+ type: 'text',
+ text: '