fix: 二次 Apply 不再误报 #26/#27,重启等到会话树落地再进页面

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
yangandCursor committed 2026-09-17 13:33:34 +08:00
1 parent 6c88f4d075
commit fd4dfa4e38
11 files changed
+254 -432

No files matched your search

+1
View File
@@ -3,3 +3,4 @@ node_modules/
npm-debug.log*
.DS_Store
_archive/
频道推广手册/
-9
View File
@@ -1,12 +1,4 @@
#!/usr/bin/env node
// dsh-purge CLI(小杨)— 移植自 dsh_purge.py 的静默模式,功能一个不差
// 用法:
// dsh-purge # TUI 等价:默认只显示状态(这里同 --status)
// dsh-purge --status # 显示状态
// dsh-purge --apply # 应用全部清洗
// dsh-purge --revert # 回滚还原
// dsh-purge --edit # 编辑 prompt-inject.md
// dsh-purge --help # 帮助
import * as core from "../lib/core.js";
@@ -116,7 +108,6 @@ async function main() {
}
console.log(" 编辑完成后重启 dsh 生效。");
} else {
// 默认只显示状态(对齐 py 的"默认不清洗")
console.log("默认不清洗,使用 --apply 应用清洗。");
}
}
+15 -9
View File
@@ -1,4 +1,3 @@
// dsh-purge client bundle: settings section follows Harness zh/en.
window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
var module = { exports: {} };
@@ -505,7 +504,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
}
setNotice({ kind: "ok", text: tr("ok.done") });
loadAll();
// Only after apply finished successfully — never restart mid-apply.
if (action === "apply") setAskRestart(true);
} else {
setNotice({ kind: "error", text: tr("err.action", { action: label, error: d.error || "" }) });
@@ -811,22 +809,32 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
);
}
function reopenAfterRestart() {
const url = new URL(window.location.href);
url.searchParams.delete("token");
window.location.replace(url.pathname + url.search + url.hash);
}
function waitForRestart(setNotice, setBusy, t) {
const started = Date.now();
const ping = () => {
fetch("/dsh-purge/status", { cache: "no-store" })
.then((r) => { if (r.ok) window.location.reload(); else retry(); })
fetch("/dsh-purge/status", { cache: "no-store", credentials: "same-origin" })
.then((r) => (r.ok ? r.json() : Promise.reject()))
.then((d) => {
if (d && d.ok && d.ready !== false) reopenAfterRestart();
else retry();
})
.catch(retry);
};
const retry = () => {
if (Date.now() - started > 25000) {
if (Date.now() - started > 90000) {
setNotice({ kind: "error", text: t("restart.timeout") });
setBusy(false);
return;
}
setTimeout(ping, 400);
setTimeout(ping, 500);
};
setTimeout(ping, 700);
setTimeout(ping, 800);
}
function restartDsh(setNotice, setBusy, t) {
@@ -893,7 +901,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
} catch { /* ignore */ }
if (!cancelled) setTheme(detectHostTheme());
};
// Debounce attribute churn so layout style writes don't thrash React state.
const syncSoon = () => {
if (timer) window.clearTimeout(timer);
timer = window.setTimeout(syncFromHost, 50);
@@ -908,7 +915,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
try {
if (document.body) {
obs = new MutationObserver(syncSoon);
// Host dark mode is projected onto body; ignore documentElement style noise.
obs.observe(document.body, { attributes: true, attributeFilter: ["data-ds-dark-theme"] });
}
} catch { /* ignore */ }
-3
View File
@@ -1,6 +1,3 @@
# dsh-purge bundle patch: inserts the plugin into a profile's layer stack.
# Overlay system-prompt so Harness does not open with "You are a coding agent".
# Identity comes from prompt-inject.md only (when present).
- id: system-prompt
config:
includeHarnessIdentity: false
+1 -6
View File
@@ -1,9 +1,4 @@
// ESM facade over the real child_process builtin with windowsHide forced.
// Loaded via registerHooks so `import { spawn } from "node:child_process"`
// receives the wrapped functions (plain cp.spawn = … does NOT affect ESM
// named imports on Node 24).
const cp = process.getBuiltinModule("child_process");
const cp = process.getBuiltinModule("child_process"); // Node 24 ESM 具名导入是副本,必须包 builtin
const MARK = "__dshPurgeHideConsole";
function hide(options) {
+192 -303
View File
File diff suppressed because it is too large. Load diff
+3 -33
View File
@@ -1,13 +1,3 @@
// Force every child_process launch on Windows to use CREATE_NO_WINDOW.
// Must load before other plugins spawn work — import this module for side effects,
// or call installHideConsole() explicitly from apply().
//
// Node 24: ESM `import { spawn } from "node:child_process"` is NOT a live
// binding to module.exports.spawn. Monkey-patching require("child_process")
// alone does nothing for DSH packages. We register an import hook that
// redirects node:child_process → ./child-process-hide.mjs (which wraps the
// builtin via process.getBuiltinModule).
import { createRequire, registerHooks } from "node:module";
import { pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
@@ -70,12 +60,9 @@ function facadeUrl() {
return pathToFileURL(fileURLToPath(new URL("./child-process-hide.mjs", import.meta.url))).href;
}
/** Redirect ESM/CJS resolution of child_process to the windowsHide facade. */
export function installChildProcessImportHook() {
if (process.platform !== "win32") return { ok: true, skipped: "not_win32" };
// DSH Desktop runs on Electron. Electron’s overrideChildProcess patches
// child_process by assigning properties (e.g. exec) onto the module object,
// which throws on a frozen ESM namespace. Skip the redirect on Electron hosts.
// Electron 会给 child_process 赋值;ESM namespace 冻结后会抛错,桌面宿主只做 wrap。
if (typeof process.versions !== "undefined" && process.versions.electron) {
return { ok: true, skipped: "electron_host" };
}
@@ -84,8 +71,6 @@ export function installChildProcessImportHook() {
registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier === "node:child_process" || specifier === "child_process") {
// Do not redirect the facade's own getBuiltinModule path (it never
// resolves via this specifier). Short-circuit every importer.
return { shortCircuit: true, url: target, format: "module" };
}
return nextResolve(specifier, context);
@@ -95,12 +80,11 @@ export function installChildProcessImportHook() {
return { ok: true, hooked: true };
}
/** Patch node:child_process in this process (CJS require path). Idempotent. */
export function installHideConsole() {
if (process.platform !== "win32") return { ok: true, skipped: "not_win32" };
const hook = installChildProcessImportHook();
const require = createRequire(import.meta.url);
// Prefer builtin so we patch the real object the facade also wraps.
// 改 builtin 本体,和 facade 包的是同一对象。
const cp =
typeof process.getBuiltinModule === "function"
? process.getBuiltinModule("child_process")
@@ -119,11 +103,7 @@ export function installHideConsole() {
return { ok: true, patched: true, hook };
}
/** Source written next to DSH `lib/bin.js` so the entry imports it first. */
export function hideConsoleEntrySource() {
// Keep the side file self-contained: registerHooks + wrap builtin.
// The facade lives beside this file as dsh-purge-child-process-hide.mjs
// (copied by installHideConsoleIntoBin).
return `// ${IMPORT_MARK} — auto-installed by dsh-purge; do not edit
import { pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
@@ -132,11 +112,9 @@ 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;
// DSH Desktop (Electron) must NOT redirect child_process to the ESM facade:
// Electron’s overrideChildProcess assigns e.g. exec onto the module object,
// and a frozen ESM namespace throws TypeError. Only the safe wrapping below runs.
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({
@@ -195,9 +173,6 @@ function requirePath() {
return createRequire(import.meta.url)("node:path");
}
/**
* Resolve the @deepseek-ai/dsh package root that actually owns lib/bin.js.
*/
export function resolveDshBinRoot(hint, { fs, path: nodePath } = {}) {
const nodeFs = fs ?? requireFs();
const p = nodePath ?? requirePath();
@@ -229,9 +204,6 @@ export function resolveDshBinRoot(hint, { fs, path: nodePath } = {}) {
const IMPORT_LINE = `import "./${IMPORT_MARK}.js"; // [dsh-purge] hide-console`;
/**
* Drop hide-console next to bin.js and ensure it is the first import.
*/
export function installHideConsoleIntoBin(aiBase, { fs, path: nodePath } = {}) {
if (process.platform !== "win32") return "skipped_not_win32";
const nodeFs = fs ?? requireFs();
@@ -251,7 +223,6 @@ export function installHideConsoleIntoBin(aiBase, { fs, path: nodePath } = {}) {
let text = nodeFs.readFileSync(binJs, "utf8");
if (text.includes(IMPORT_MARK) && text.includes(IMPORT_LINE.split(" //")[0])) {
// Side + facade refreshed above; bin.js import already present.
return "already_injected";
}
text = text.replace(/^import "\.\/dsh-purge-hide-console\.js";.*\r?\n/m, "");
@@ -268,5 +239,4 @@ export function installHideConsoleIntoBin(aiBase, { fs, path: nodePath } = {}) {
return "injected";
}
// Side-effect install when this module is imported on win32
installHideConsole();
+2 -11
View File
@@ -1,7 +1,3 @@
// Official Harness / engineer personas are stripped so prompt-inject.md owns identity.
// Liangshen phase-1 keeps persona (+ prefix on 0.1.5). Fold inject into the prefix
// (or legacy persona) so turn 1 still sees it. No plugin-authored identity card.
export const GLOBAL_PROMPT_ORDER = 5000;
export const IDENTITY_CARD_PREFIX = "WHO YOU ARE (highest priority";
@@ -29,7 +25,6 @@ const OLD_LCS_LOCK =
"When asked 你是谁 / who are you, answer with that name only. " +
"Never say 我是 DeepSeek 的 AI 助手 or that you run on DeepSeek Harness as your identity — that is the host, not you.";
/** @deprecated Identity is prompt-inject.md only. Kept so old callers do not throw. */
export const IDENTITY_LOCK = "";
export function extractOperatorName(injectText) {
@@ -45,7 +40,6 @@ export function extractOperatorName(injectText) {
return "";
}
/** @deprecated No plugin identity card. Inject file is used as-is. */
export function buildIdentityCard(_injectText) {
return "";
}
@@ -122,6 +116,7 @@ function isPersonaFoldTarget(name, preferPrefix) {
return PERSONA_PREFIX_NAMES.has(name) || PERSONA_LEGACY_NAMES.has(name);
}
// 0.1.5 优先写入 persona-prefix;无 prefix 时写入 legacy persona。
function foldInjectIntoPersona(sections, injectText) {
const inject = typeof injectText === "string" ? injectText.trim() : "";
const names = sections.map((s) => String(s?.name || ""));
@@ -143,11 +138,6 @@ function foldInjectIntoPersona(sections, injectText) {
return [{ name: "deployment:persona-prefix", text: inject }, ...out];
}
/**
* @param {object} assembled
* @param {string} [fallbackInject] raw prompt-inject.md when purge sections were
* already filtered out by an outer Liangshen hook (first-turn race).
*/
export function rewritePromptAssembly(assembled, fallbackInject = "") {
if (!assembled || !Array.isArray(assembled.sections)) return assembled;
const rest = [];
@@ -163,6 +153,7 @@ export function rewritePromptAssembly(assembled, fallbackInject = "") {
else rest.push(next);
}
// fallbackInject:section 被滤掉时从 prompt-inject.md 补回。
const injectText = collectInjectText(purge, fallbackInject);
assembled.sections = [...foldInjectIntoPersona(rest, injectText), ...purge];
return assembled;
+36 -41
View File
@@ -1,11 +1,3 @@
// dsh-purge 插件入口(小杨)
// 功能(移植自 dsh_purge.py,一个不差):
// 1. 启动自动重洗(autoApplyOnStart)— 解决 npm 升级覆盖 node_modules 后需手动重跑的痛点
// 2. /purge 命令 — status / apply / revert / edit / help
// 2b. /rules 命令 — list / use / create / delete / reset
// 3. 模型工具 — purge_status / purge_apply / purge_revert
// 4. systemPrompt 注入 — 会话强指令 section(兜底,不依赖改文件)
import fs from "node:fs";
import { promises as fsp } from "node:fs";
import path from "node:path";
@@ -35,12 +27,38 @@ const log = (config, ...args) => {
if (config?.verbose) console.log("[dsh-purge]", ...args);
};
let webTreeReady = false;
function watchWebTreeReady(ctx) {
// 必须挂在 connection 上再 await,与官方打印 URL 同一时刻。
// apply() 里立刻 await 会在后续入口尚未入树时提前结束,session.list 仍是空的。
const mark = () => {
webTreeReady = true;
};
if (typeof ctx?.inject !== "function") {
mark();
return;
}
try {
ctx.inject(["connection"], (host) => {
const settled = host.get?.("loader")?.await?.();
if (!settled || typeof settled.then !== "function") {
mark();
return;
}
settled.then(() => {
if (host.get?.("webServer") !== undefined && host.get?.("connection") !== undefined) mark();
}, mark);
});
} catch {
mark();
}
}
function fsExists(fp) {
return fs.existsSync(fp);
}
// ── 文本渲染(无 rich 依赖)───────────────────────────────────────
function line(title, value, ok = null) {
const mark = ok === null ? "·" : ok ? "✓" : "✗";
return `${mark} ${title}: ${value}`;
@@ -88,7 +106,6 @@ function readInjectFile(injectFile) {
}
export function registerPromptSections(ctx, config, injectFile) {
// prompt-inject.md verbatim. No plugin identity card.
ctx.systemPrompt.section({
name: "dsh-purge",
order: GLOBAL_PROMPT_ORDER,
@@ -123,7 +140,6 @@ export function registerPromptSections(ctx, config, injectFile) {
});
}
/** Cap fallback inject read so a huge/corrupt prompt-inject.md cannot blow memory each assemble. */
const INJECT_FALLBACK_MAX_BYTES = 512 * 1024;
function readInjectFallback() {
@@ -150,16 +166,12 @@ function installIdentityOverride(ctx) {
if (typeof ctx.on !== "function") return;
const hook = async (_assembly, _context, next) => {
const assembled = typeof next === "function" ? await next() : _assembly;
// Fallback file read covers Liangshen phase-1 races where purge sections
// were filtered before this hook ran — first turn must still get inject.
return rewritePromptAssembly(assembled, readInjectFallback());
};
// Inner (no prepend): fold inject into persona BEFORE Liangshen phase-1 filter.
// prepend:false 先于 phase-1 滤镜;prepend:true 在滤镜之后再折一次。
try {
ctx.on("system-prompt/assemble", hook, { global: true, prepend: false });
} catch {}
// Outer (prepend): if filter already ran, re-fold from file. Re-register once
// after plugins settle so we stay outermost without stacking three listeners.
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
const late = () => {
try {
@@ -170,8 +182,6 @@ function installIdentityOverride(ctx) {
setTimeout(late, 1500);
}
// ── 自动重洗 ──────────────────────────────────────────────────────
const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"];
function desktopShimNeedsPatch(dirs) {
@@ -204,7 +214,6 @@ async function autoApply(config) {
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));
@@ -240,8 +249,6 @@ async function autoApply(config) {
}
}
// ── 命令处理 ──────────────────────────────────────────────────────
async function handlePurgeCommand(rawInput, config) {
const args = (rawInput || "").trim().split(/\s+/).filter(Boolean);
const sub = (args[0] || "status").toLowerCase();
@@ -442,15 +449,11 @@ async function handleRulesCommand(rawInput) {
}
}
// ── 插件 apply ────────────────────────────────────────────────────
export function apply(ctx, config) {
const cfg = { ...DEFAULTS, ...(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));
@@ -465,7 +468,6 @@ export function apply(ctx, config) {
console.warn("[dsh-purge] desktop runtime scrub error:", String(e));
}
// 1. 启动自动重洗(异步,不阻塞启动)
setImmediate(() => {
autoApply(cfg).then((r) => log(cfg, "auto-apply:", r));
rules.ensureInitialState(core.findDshHome())
@@ -473,12 +475,10 @@ export function apply(ctx, config) {
.catch((e) => console.warn("[dsh-purge] rules init error:", String(e)));
});
// 2. systemPrompt 注入(操作员提示词放在 persona 之后,避免被 coding agent 盖住)
installIdentityOverride(ctx);
const injectFile = core.findOverrideFile(core.findDshHome());
registerPromptSections(ctx, cfg, injectFile);
// 3. /purge 命令
const commands = ctx.get?.("commands");
if (commands) {
commands.register({
@@ -495,7 +495,6 @@ export function apply(ctx, config) {
});
}
// 4. 模型工具(原始 JSON-Schema ToolDefinition,零 peer 依赖)
if (ctx.tools) {
ctx.tools.register({
name: "purge_status",
@@ -580,7 +579,6 @@ export function apply(ctx, config) {
});
}
// 5. HTTP API(Web UI 设置面板用)
installWebServer(ctx, cfg);
}
@@ -597,15 +595,12 @@ 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.
// 复用当前 argv 的 profile/子命令,入口改走 node + bin.js。
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));
@@ -628,7 +623,6 @@ function restartArgv() {
}
function scheduleWebRestart(request) {
// Final no-flash pin before exit so the replacement process loads hide-console first.
try {
core.silenceCmdFlash();
} catch {}
@@ -650,13 +644,11 @@ function scheduleWebRestart(request) {
},
});
child.unref();
// Exit only after the helper is detached; apply/restart handlers already finished.
setTimeout(() => process.exit(0), 250);
}
// ── Web UI 设置面板后端(HTTP 路由)──────────────────────────────
function installWebServer(ctx, cfg) {
watchWebTreeReady(ctx);
ctx.inject(["webServer"], (host) => {
host.effect(() => {
host.webServer.register({
@@ -669,11 +661,16 @@ function installWebServer(ctx, cfg) {
return;
}
try {
if (!webTreeReady) {
sendJson(response, 503, { ok: false, ready: false });
return;
}
const state = await core.gatherState();
const patch_names = {};
for (const p of core.ALL_PATCHES) patch_names[String(p.id)] = p.name;
sendJson(response, 200, {
ok: true,
ready: true,
ai_base: state.ai_base,
patches_applied: state.patches_applied,
patches_pending: state.patches_pending,
@@ -714,10 +711,8 @@ function installWebServer(ctx, cfg) {
const report = await core.applyPatches(state.ai_base);
const override = await core.ensureOverrideContent(state.dsh_home, false);
const shim = await core.patchAllShims();
// Apply must finish the no-flash pass before offering restart.
const flash = core.silenceCmdFlash(state.ai_base);
const summary = core.summarizeApplyReport(report);
// Restart when required patches are soft-ok AND (on win32) bin pin is ok/soft.
const complete = summary.failed.length === 0 && flash.ok === true;
sendJson(response, 200, {
ok: true,
+2 -5
View File
@@ -1,4 +1,3 @@
// Spawned by /dsh-purge/restart: wait until the old web port is free, then relaunch.
import net from "node:net";
import { spawn } from "node:child_process";
import { envForDetachedSpawn } from "./core.js";
@@ -37,8 +36,7 @@ async function waitFree() {
const ok = await waitFree();
if (!ok) process.exit(1);
// On Windows, detached without a hidden console allocates a visible conhost.
// Always force windowsHide + never shell (dsh.cmd → cmd.exe flash).
// detached + windowsHide;shell:false 避免再走 dsh.cmd / cmd.exe。
const child = spawn(info.execPath, info.argv, {
detached: true,
stdio: "ignore",
@@ -49,7 +47,6 @@ const child = spawn(info.execPath, info.argv, {
});
child.on("error", () => process.exit(1));
child.unref();
// Brief linger so the replacement is not torn down with this helper's process
// group on Windows before it detaches.
// 等子进程脱离 job,避免 helper 退出时带走新进程。
await new Promise((r) => setTimeout(r, 400));
process.exit(0);
+2 -12
View File
@@ -1,6 +1,3 @@
// 规则集:多套 AGENTS.md / CLAUDE.md;激活时写入目标文件,并被 systemPrompt 段实时注入
// 存储: $DSH_HOME/rules/<id>.md + <id>.json ;状态: rules/state.json
import fs from "node:fs";
import { promises as fsp } from "node:fs";
import path from "node:path";
@@ -86,13 +83,12 @@ export async function listRules(dshHome) {
try {
size = (await fsp.stat(path.join(dir, e.name))).size;
} catch {
/* ignore */
}
const meta = await readRuleMeta(dshHome, id);
out.push({ id, name: meta.name, target: meta.target, size });
}
} catch {
/* rules dir missing → empty */
// rules 目录不存在时按空列表返回
}
out.sort((a, b) => a.id.localeCompare(b.id));
return out;
@@ -136,7 +132,6 @@ export async function deleteRule(dshHome, id) {
try {
await fsp.unlink(stateFile(dshHome));
} catch {
/* ignore */
}
}
}
@@ -156,7 +151,6 @@ export async function setActive(dshHome, id) {
await fsp.writeFile(stateFile(dshHome), JSON.stringify({ active: id }, null, 2), "utf8");
}
/** Sync read for systemPrompt.section text(); empty string if none. */
export function activeRuleText(dshHome) {
try {
const parsed = JSON.parse(fs.readFileSync(stateFile(dshHome), "utf8"));
@@ -184,7 +178,6 @@ export async function ensureInitialState(dshHome) {
try {
await fsp.unlink(stateFile(dshHome));
} catch {
/* ignore */
}
active = null;
}
@@ -199,7 +192,7 @@ export async function ensureInitialState(dshHome) {
return { active: "default", imported: target };
}
} catch {
/* file missing, try next target */
// 当前 target 文件不存在,试下一个
}
}
return { active: null };
@@ -222,13 +215,11 @@ export async function resetToOriginal(dshHome) {
skipped.push(fp);
}
} catch {
/* 目标文件不存在 */
}
}
try {
await fsp.unlink(stateFile(dshHome));
} catch {
/* 无状态文件 */
}
return { removed, skipped };
}
@@ -250,7 +241,6 @@ export async function rulesStatus(dshHome) {
const ruleContent = await readRule(dshHome, active);
agents_synced = ruleContent !== null && ruleContent === content;
} catch {
/* target file missing */
}
}
return {