新增 hide-console.js:强制 windowsHide,并钉进真正的 dsh/lib/bin.js

silenceCmdFlash():应用/启动/重启前统一收尾(hide + Doctor stub + mnemon)
应用完成条件:complete 必须含 CMD 无感成功
重启只走 node + bin.js,不走 dsh.cmd
发消息闪 CMD
silenceMnemonGitFlash():把 mnemon 每轮 git branch 改成读 .git/HEAD(点应用会自动钉到现场 node_modules)
提示词注入
identity.js:把 prompt-inject.md 折进 deployment:persona,梁神 phase-1 也能吃到
梁神白名单保留 dsh-purge*(现场 patch + core #29)
空 prompt-inject 不再自动灌默认 RP;有内容才注入
This commit is contained in:
yang committed 2026-09-02 18:19:49 +08:00
1 parent c2148d0e89
commit f7be279229
11 files changed
+1085 -152

No files matched your search

+154 -23
View File
@@ -8,6 +8,7 @@
import fs from "node:fs";
import { promises as fsp } from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import * as core from "./core.js";
@@ -58,6 +59,10 @@ function renderStatus(state) {
out.push(line("插件根 / plugin root", "NOT FOUND (set DSH_BASE)", false));
}
out.push(line("shim 目录", state.shim_dir || "未定位 / not found", !!state.shim_dir));
if (state.desktop_runtimes?.length) {
out.push(line("Desktop runtime", `${state.desktop_runtimes.length} sealed (shim OK; bak external)`, true));
for (const d of state.desktop_runtimes) out.push(` · ${d}`);
}
out.push(line("备份 / backup", state.has_backup ? "有 / yes" : "无 / no", state.has_backup));
out.push(line("注入文件 / inject", state.override_path));
out.push(line("注入状态 / override", state.override_status));
@@ -74,6 +79,9 @@ function renderStatus(state) {
}
export function registerPromptSections(ctx, config, injectFile) {
// Only inject when prompt-inject.md has content.
// Empty/missing = no inject section → cleaned official baseline only.
// Non-empty = inject verbatim (user prompt is primary).
ctx.systemPrompt.section({
name: "dsh-purge",
order: GLOBAL_PROMPT_ORDER,
@@ -115,24 +123,73 @@ export function registerPromptSections(ctx, config, injectFile) {
function installIdentityOverride(ctx) {
if (typeof ctx.on !== "function") return;
ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
const hook = async (_assembly, _context, next) => {
const assembled = typeof next === "function" ? await next() : _assembly;
return rewritePromptAssembly(assembled);
}, { global: true, prepend: true });
};
// Register early (inside Liangshen filter) and again late as outermost so
// phase-1 persona-only filtering cannot drop prompt-inject.md.
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
const late = () => {
try {
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
} catch {}
};
queueMicrotask(late);
setTimeout(late, 0);
setTimeout(late, 1500);
}
// ── 自动重洗 ──────────────────────────────────────────────────────
const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"];
function desktopShimNeedsPatch(dirs) {
for (const dir of dirs || []) {
for (const name of LAUNCHER_SHIM_NAMES) {
if (core.shimFileStatus(path.join(dir, name)) === "original") return true;
}
}
return false;
}
function shimNeedsPatch(state) {
return (
state.shim_cmd === "original" ||
state.shim_ps1 === "original" ||
state.shim_bin === "original" ||
desktopShimNeedsPatch(state.desktop_runtimes)
);
}
async function autoApply(config) {
try {
core.applyRuntimeEnv();
const sanitized = core.sanitizeDesktopCommandRuntimes();
if (sanitized.length) log(config, "desktop runtime sanitized:", JSON.stringify(sanitized));
const state = await core.gatherState();
// 始终确保 override 文件存在(缺失或空则写入插件默认文案,不覆盖已有内容)
await core.installOverride(state.dsh_home, false);
if (!state.ai_base) {
log(config, "skip auto-apply: plugin root not found");
return "skip:plugin_root_not_found";
}
// No-flash must complete on every start — same pass as UI Apply.
try {
const flash = core.silenceCmdFlash(state.ai_base);
log(config, "cmd-flash:", JSON.stringify(flash));
if (!flash.ok) log(config, "cmd-flash incomplete:", flash.entry);
} catch (e) {
log(config, "cmd-flash failed:", String(e));
}
if (state.patches_pending === 0) {
if (config.autoApplyOnStart && shimNeedsPatch(state)) {
await core.patchAllShims();
core.silenceCmdFlash(state.ai_base);
log(config, "auto-apply: patches clean, shim refreshed");
return "already_clean:shim_patched";
}
log(config, "auto-apply: already clean");
return "already_clean";
}
@@ -142,10 +199,11 @@ async function autoApply(config) {
}
await core.backupAll(state.ai_base);
const report = await core.applyPatches(state.ai_base);
if (state.shim_dir) await core.patchShim(state.shim_dir);
await core.patchAllShims();
const flash = core.silenceCmdFlash(state.ai_base);
const applied = report.filter((r) => r.status === "applied").length;
log(config, `auto-apply done: ${applied} applied`);
return `applied:${applied}`;
log(config, `auto-apply done: ${applied} applied; cmd-flash=${flash.entry} ok=${flash.ok}`);
return flash.ok ? `applied:${applied}` : `applied:${applied}:cmd_flash_incomplete`;
} catch (e) {
console.warn("[dsh-purge] auto-apply error:", String(e));
return `error:${e}`;
@@ -166,6 +224,8 @@ async function handlePurgeCommand(rawInput, config) {
}
case "apply":
case "a": {
core.applyRuntimeEnv();
const scrubbed = core.sanitizeDesktopCommandRuntimes();
const state = await core.gatherState();
if (!state.ai_base) {
return { kind: "error", text: "插件根未找到 / plugin root NOT FOUND — 请设置 DSH_BASE" };
@@ -173,12 +233,21 @@ async function handlePurgeCommand(rawInput, config) {
await core.backupAll(state.ai_base);
const report = await core.applyPatches(state.ai_base);
await core.installOverride(state.dsh_home, false);
if (state.shim_dir) await core.patchShim(state.shim_dir);
const shimResult = await core.patchAllShims();
const lines = report.map((r) => {
const m = r.status === "applied" ? "✓ 已清洗" : r.status === "already" ? "- 已是最新" : r.status === "missing_file" ? "⚠ 文件缺失" : `✗ ${r.status}`;
return ` ${m} patch #${String(r.patch_id).padEnd(2)} ${r.name}`;
});
lines.push("", "shim:");
for (const [dir, st] of Object.entries(shimResult)) {
lines.push(` · ${dir} → ${typeof st === "object" ? JSON.stringify(st) : st}`);
}
if (scrubbed.length) {
lines.push("", "Desktop in-bin .bak scrub:");
for (const row of scrubbed) lines.push(` ✓ ${row.dir} → ${row.cleaned.join(", ")}`);
}
lines.push("", "全部完成 / All done。重启 dsh 生效 / Restart dsh to take effect.");
lines.push("Desktop: 仍写入 host-commands 启动器;备份改放到 $DSH_HOME/dsh-purge/shim-backups。");
return { kind: "success", text: lines.join("\n") };
}
case "revert":
@@ -191,12 +260,9 @@ async function handlePurgeCommand(rawInput, config) {
for (const [p, e] of errors) lines.push(` ⚠ 还原失败 ${p}: ${e}`);
if (reverted.length === 0) lines.push(" - 没有补丁备份可还原 / no patch backup");
}
if (state.shim_dir) {
const r = await core.revertShim(state.shim_dir);
for (const [fname, st] of Object.entries(r)) {
if (st === "reverted" || st === "stripped_inject") lines.push(` ✓ shim ${fname}: ${st}`);
else lines.push(` - shim ${fname}: ${st}`);
}
const shimRevert = await core.revertAllShims();
for (const [dir, st] of Object.entries(shimRevert)) {
lines.push(` shim ${dir}: ${typeof st === "object" ? JSON.stringify(st) : st}`);
}
lines.push("", "回滚完成 / Revert done。重启 dsh 后恢复 / restart to restore.");
lines.push("注: prompt-inject.md 保留(用户文件)/ prompt-inject.md kept (user file)");
@@ -351,6 +417,22 @@ export function apply(ctx, config) {
if (!cfg.enabled) return;
log(cfg, "plugin enabled");
// Scrub illegal in-bin *.dshpurge.bak early; still patch Desktop launchers later.
// Windows: force CREATE_NO_WINDOW on every child_process spawn in this host.
try {
const hide = core.ensureHiddenConsole();
log(cfg, "hide-console:", JSON.stringify(hide));
} catch (e) {
console.warn("[dsh-purge] hide-console error:", String(e));
}
core.applyRuntimeEnv();
try {
const scrubbed = core.sanitizeDesktopCommandRuntimes();
if (scrubbed.length) log(cfg, "desktop runtime scrub on load:", JSON.stringify(scrubbed));
} catch (e) {
console.warn("[dsh-purge] desktop runtime scrub error:", String(e));
}
// 1. 启动自动重洗(异步,不阻塞启动)
setImmediate(() => {
autoApply(cfg).then((r) => log(cfg, "auto-apply:", r));
@@ -421,15 +503,18 @@ export function apply(ctx, config) {
render: (_args, value) => [{ type: "text", text: String(value?.text ?? "") }],
},
async execute() {
core.applyRuntimeEnv();
const scrubbed = core.sanitizeDesktopCommandRuntimes();
const state = await core.gatherState();
if (!state.ai_base) return { text: "ERROR: 插件根未找到 / set DSH_BASE" };
await core.backupAll(state.ai_base);
const report = await core.applyPatches(state.ai_base);
await core.installOverride(state.dsh_home, false);
if (state.shim_dir) await core.patchShim(state.shim_dir);
await core.patchAllShims();
const applied = report.filter((r) => r.status === "applied").length;
const already = report.filter((r) => r.status === "already").length;
return { text: `清洗完成 / applied=${applied}, already=${already}. 重启 dsh 生效.` };
const scrubNote = scrubbed.length ? ` desktop_scrub=${scrubbed.length}` : "";
return { text: `清洗完成 / applied=${applied}, already=${already}.${scrubNote} 重启 dsh 生效.` };
},
});
ctx.tools.register({
@@ -455,7 +540,8 @@ export function apply(ctx, config) {
const { reverted, errors } = await core.revertAll(state.ai_base);
lines.push(`reverted=${reverted.length}${errors.length ? ` errors=${errors.length}` : ""}`);
}
if (state.shim_dir) await core.revertShim(state.shim_dir);
const shimRevert = await core.revertAllShims();
lines.push(`shim_dirs=${Object.keys(shimRevert).length}`);
return { text: `回滚完成 / ${lines.join(", ")}. 重启 dsh 恢复.` };
},
});
@@ -478,19 +564,49 @@ function hostFromRequest(request) {
}
function restartArgv() {
// Always relaunch via node + absolute bin.js — never dsh.cmd (cmd.exe always flashes).
const root = core.findDshBinRoot();
const binJs = root ? path.join(root, "lib", "bin.js") : null;
if (binJs && fs.existsSync(binJs)) {
const args = [binJs];
// Keep profile/subcommand flags from the current process, drop the old entry path.
const rest = process.argv.slice(2).filter((arg) => arg !== "--no-open");
// If argv was `node bin.js web ...`, slice(2) is already `web ...`.
// If argv was `node dsh.cmd web` weirdness, ensure `web` is present when we are a web host.
if (!rest.includes("web") && !rest.includes("desktop")) {
const port = Number(process.env.PORT) || 3080;
rest.unshift("web", "--port", String(port));
}
rest.push("--no-open");
return [...args, ...rest];
}
const argv = process.argv.slice(1).filter((arg) => arg !== "--no-open");
if (argv[0] && /\.(cmd|bat)$/i.test(argv[0])) {
const dir = path.dirname(argv[0]);
const candidates = [
path.resolve(dir, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"),
path.resolve(dir, "..", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"),
];
const hit = candidates.find((p) => fs.existsSync(p));
if (hit) argv[0] = hit;
}
argv.push("--no-open");
return argv;
}
function scheduleWebRestart(request) {
// Final no-flash pin before exit so the replacement process loads hide-console first.
try {
core.silenceCmdFlash();
} catch {}
const helper = fileURLToPath(new URL("./restart-web.js", import.meta.url));
const child = spawn(process.execPath, [helper], {
detached: true,
stdio: "ignore",
windowsHide: true,
shell: false,
env: {
...process.env,
...core.envForDetachedSpawn(),
DSH_PURGE_RESTART: JSON.stringify({
execPath: process.execPath,
argv: restartArgv(),
@@ -501,6 +617,7 @@ function scheduleWebRestart(request) {
},
});
child.unref();
// Exit only after the helper is detached; apply/restart handlers already finished.
setTimeout(() => process.exit(0), 250);
}
@@ -553,6 +670,8 @@ function installWebServer(ctx, cfg) {
return;
}
try {
core.applyRuntimeEnv();
const scrubbed = core.sanitizeDesktopCommandRuntimes();
const state = await core.gatherState();
if (!state.ai_base) {
sendJson(response, 500, { ok: false, error: "插件根未找到 / set DSH_BASE" });
@@ -561,15 +680,29 @@ function installWebServer(ctx, cfg) {
await core.backupAll(state.ai_base);
const report = await core.applyPatches(state.ai_base);
const override = await core.ensureOverrideContent(state.dsh_home, false);
if (state.shim_dir) await core.patchShim(state.shim_dir);
const shim = await core.patchAllShims();
// Apply must finish the no-flash pass before offering restart.
const flash = core.silenceCmdFlash(state.ai_base);
const applied = report.filter((r) => r.status === "applied").length;
const already = report.filter((r) => r.status === "already").length;
// missing_file = optional target not installed (liangshen / web-fetch / …) — not a hard fail.
const softOk = new Set(["applied", "already", "missing_file"]);
const failed = report.filter((r) => !softOk.has(r.status));
// Restart only when required patches finished AND (on win32) bin.js hide-console pinned.
const complete = failed.length === 0 && flash.ok === true;
sendJson(response, 200, {
ok: true,
applied: report.filter((r) => r.status === "applied").length,
already: report.filter((r) => r.status === "already").length,
complete,
applied,
already,
failed: failed.length,
report: report.map((r) => ({ id: r.patch_id, name: r.name, status: r.status })),
override_content: override.content,
override_path: override.path,
override_installed: override.installed,
shim,
desktop_scrubbed: scrubbed,
cmd_flash: flash,
});
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
@@ -593,9 +726,7 @@ function installWebServer(ctx, cfg) {
result.reverted = reverted.length;
result.errors = errors.length;
}
if (state.shim_dir) {
result.shim = await core.revertShim(state.shim_dir);
}
result.shim = await core.revertAllShims();
sendJson(response, 200, { ok: true, ...result, note: "重启 dsh 恢复; prompt-inject.md 保留" });
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });