mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 06:00:22 +08:00
feat(log): 加日志探针覆盖所有 inject 路径,方便现场定位
统一 purgeLog(tag, kv) 单行 ISO + 标签 + k=v 格式。tail -F / grep 友好。 覆盖标签: - boot/home - plugin apply 启动态 + DSH home 发现结果 - host.hungFn - 四级 fallback 命中(refresh/hung/disk/sealed/empty)+ bytes - assemble.entry - cordis handler 入口(hasNext/sections/events) - assemble.event - cordis event 决策(mode/task/last/sub) - assemble.rewriteFn - guard 包装路径决策(同上) - assemble.rewrite - rewriteLiveAssembly 落点(fullBytes/injectBytes/anchorApplied/roleBytes) - assemble.waterfall / rewriteFail - next() / rewrite 抛错 - inject.read - readInjectFallback 来源(refresh/ensure/empty)+ redteam/sub + bytes - guard.wrap - wrapAssemble 调用(caller=init/interval/sessionCreated/presetSelected/preStep/prepareAssemble) 日志仍写 %TEMP%/dsh-purge-desktop.log,2MB 自动 rotate 到 .1, 每 1024 次写检查一次 size,长会话不吃爆 tmp。 现场测: 1. tail -F "$TEMP/dsh-purge-desktop.log" 2. 新对话首发消息 → assemble.event mode=full last=full:user/message assemble.rewrite fullBytes=N injectBytes=N anchorApplied=false 3. 工具调用后 → mode=anchor last=tool-result anchorApplied=true 4. inject 真空(模型自称 Claude)→ 看 host.hungFn tier=empty 或 inject.read source=empty 定位哪一级返空
This commit is contained in:
1 parent
c5726f9525
commit
1975187a9c
1 file changed
+106
-26
+106
-26
@@ -214,20 +214,21 @@ function installHungPromptGlobal() {
|
||||
try { home = core.findDshHome(); } catch { home = ""; }
|
||||
try {
|
||||
const text = refreshHungOperator(home).text;
|
||||
if (text) return text;
|
||||
} catch { /* 下一重 */ }
|
||||
if (text) { purgeLog("host.hungFn", { tier: "refresh", bytes: text.length }); return text; }
|
||||
} catch (e) { purgeLog("host.hungFn", { tier: "refresh", err: String(e?.message || e) }); }
|
||||
try {
|
||||
const hung = core.hungOperatorPrompt();
|
||||
if (hung) return hung;
|
||||
} catch { /* 下一重 */ }
|
||||
if (hung) { purgeLog("host.hungFn", { tier: "hung", bytes: hung.length }); return hung; }
|
||||
} catch (e) { purgeLog("host.hungFn", { tier: "hung", err: String(e?.message || e) }); }
|
||||
try {
|
||||
const disk = core.readPromptInjectFileSync(home);
|
||||
if (disk) return disk;
|
||||
} catch { /* 下一重 */ }
|
||||
if (disk) { purgeLog("host.hungFn", { tier: "disk", bytes: disk.length }); return disk; }
|
||||
} catch (e) { purgeLog("host.hungFn", { tier: "disk", err: String(e?.message || e) }); }
|
||||
try {
|
||||
const sealed = core.defaultOverrideText();
|
||||
if (sealed) return sealed;
|
||||
} catch { /* 彻底空 */ }
|
||||
if (sealed) { purgeLog("host.hungFn", { tier: "sealed", bytes: sealed.length }); return sealed; }
|
||||
} catch (e) { purgeLog("host.hungFn", { tier: "sealed", err: String(e?.message || e) }); }
|
||||
purgeLog("host.hungFn", { tier: "empty", bytes: 0 });
|
||||
return "";
|
||||
};
|
||||
globalThis.__dshPurgeHungPrompt = fn;
|
||||
@@ -393,13 +394,30 @@ function rotatePurgeInternalLog() {
|
||||
}
|
||||
} catch { /* 文件不存在 */ }
|
||||
}
|
||||
function logAssembleDecision(where, decision) {
|
||||
// 单行 ISO 时间戳 + 标签 + k=v... 格式。tail -F 跟 / grep 都好读。
|
||||
// 值里空格会把 kv 切开,统一替换成 _ 保证 grep 稳定。
|
||||
function purgeLog(tag, kv) {
|
||||
try {
|
||||
if ((++_purgeLogWriteCount & 0x3ff) === 0) rotatePurgeInternalLog();
|
||||
const line = `${new Date().toISOString()} [assemble.${where}] mode=${decision.mode} task=${decision.taskKind} last=${decision.lastRole} sub=${decision.isSubagent}\n`;
|
||||
fs.appendFileSync(PURGE_INTERNAL_LOG, line, "utf8");
|
||||
let line = `${new Date().toISOString()} [${tag}]`;
|
||||
if (kv) {
|
||||
for (const k of Object.keys(kv)) {
|
||||
const raw = kv[k];
|
||||
const v = raw === undefined || raw === null ? "" : String(raw).replace(/\s+/g, "_");
|
||||
line += ` ${k}=${v}`;
|
||||
}
|
||||
}
|
||||
fs.appendFileSync(PURGE_INTERNAL_LOG, line + "\n", "utf8");
|
||||
} catch {}
|
||||
}
|
||||
function logAssembleDecision(where, decision) {
|
||||
purgeLog(`assemble.${where}`, {
|
||||
mode: decision.mode,
|
||||
task: decision.taskKind,
|
||||
last: decision.lastRole,
|
||||
sub: decision.isSubagent,
|
||||
});
|
||||
}
|
||||
|
||||
function injectSnapshot(dshHome = core.findDshHome()) {
|
||||
const resolved = rules.resolveInjectText(dshHome);
|
||||
@@ -518,11 +536,31 @@ export function registerPromptSections(ctx, config) {
|
||||
function readInjectFallback(context) {
|
||||
let home = "";
|
||||
try { home = core.findDshHome(); } catch { home = ""; }
|
||||
const raw = refreshHungOperator(home).text || rules.ensureOperatorBody(home);
|
||||
if (!raw) return "";
|
||||
const refreshed = refreshHungOperator(home);
|
||||
let text = refreshed.text || "";
|
||||
let source = text ? "refresh" : "none";
|
||||
if (!text) {
|
||||
const fallback = rules.ensureOperatorBody(home);
|
||||
if (fallback) { text = fallback; source = "ensure"; }
|
||||
}
|
||||
if (!text) {
|
||||
purgeLog("inject.read", { source: "empty", bytes: 0 });
|
||||
return "";
|
||||
}
|
||||
let redteam = false;
|
||||
try { redteam = isRedteamSession(context); } catch { redteam = false; }
|
||||
return modePromptText(raw, redteam);
|
||||
let subagent = false;
|
||||
try { subagent = context?.agent?.session?.header?.origin === "subagent"; } catch {}
|
||||
const out = modePromptText(text, redteam);
|
||||
purgeLog("inject.read", {
|
||||
source,
|
||||
srcTag: refreshed.source || "n/a",
|
||||
redteam,
|
||||
sub: subagent,
|
||||
rawBytes: text.length,
|
||||
outBytes: out.length,
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function installMnemonMessageStrip(ctx, config = {}) {
|
||||
@@ -572,20 +610,35 @@ function rewriteLiveAssembly(config, assembled, context, decision = { mode: "ful
|
||||
const redteam = enabled && isRedteamSession(context);
|
||||
const full = enabled ? readInjectFallback(context) : "";
|
||||
let inject = full;
|
||||
let anchorApplied = false;
|
||||
// [v11] decision.mode=anchor 只在真·工具循环触发(last event tool/result 或 plugin
|
||||
// continuation),塞简化版(头 6000 字 + 任务块)省 token。真实 user 发送永远 full。
|
||||
// anchor 空兜底回 full,避免 clipInjectHead 失败让 inject 真空。
|
||||
if (decision && decision.mode === "anchor" && full) {
|
||||
const simplified = buildAnchorInject(decision.taskKind, full);
|
||||
if (simplified) inject = simplified;
|
||||
if (simplified) { inject = simplified; anchorApplied = true; }
|
||||
}
|
||||
const roleText = redteam ? resolveSubagentRoleText(context) : "";
|
||||
purgeLog("assemble.rewrite", {
|
||||
enabled,
|
||||
redteam,
|
||||
mode: decision?.mode || "full",
|
||||
task: decision?.taskKind || "general",
|
||||
last: decision?.lastRole || "unknown",
|
||||
fullBytes: full.length,
|
||||
injectBytes: inject.length,
|
||||
anchorApplied,
|
||||
roleBytes: roleText.length,
|
||||
cap: config.capabilityProtocol !== false,
|
||||
strip: config.stripMnemon !== false,
|
||||
});
|
||||
return rewritePromptAssembly(assembled, {
|
||||
fallbackInject: inject,
|
||||
dropMnemon: config.stripMnemon !== false,
|
||||
dropPurgeAfterFold: false,
|
||||
capabilityProtocol: config.capabilityProtocol !== false,
|
||||
context,
|
||||
roleText: redteam ? resolveSubagentRoleText(context) : "",
|
||||
roleText,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -705,11 +758,16 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
logAssembleDecision("rewriteFn", decision);
|
||||
return rewriteLiveAssembly(config, assembled, context, decision);
|
||||
};
|
||||
const wrapAssemble = () => {
|
||||
const wrapAssemble = (caller = "unknown") => {
|
||||
try {
|
||||
const prompt = ctx.systemPrompt;
|
||||
return trackDisposer(installAssembleGuard(prompt, rewriteFn), prompt);
|
||||
} catch {
|
||||
const d = installAssembleGuard(prompt, rewriteFn);
|
||||
const mounted = typeof d === "function";
|
||||
const tracked = trackDisposer(d, prompt);
|
||||
purgeLog("guard.wrap", { caller, prompt: !!prompt, mounted });
|
||||
return tracked;
|
||||
} catch (e) {
|
||||
purgeLog("guard.wrap", { caller, err: String(e?.message || e) });
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -723,6 +781,15 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
ctx.on("system-prompt/assemble", async (...args) => {
|
||||
const [assembly, context] = args;
|
||||
const next = args.length >= 3 ? args[args.length - 1] : null;
|
||||
// 入口即记录 — 看请求是否真的到达了我们的 handler;hasNext=false 时说明 cordis
|
||||
// 走的旧签名,下游 waterfall 全靠我们返回的 assembled。
|
||||
let eventsLen = 0;
|
||||
try { eventsLen = readSessionEvents(context?.agent?.session).length; } catch {}
|
||||
purgeLog("assemble.entry", {
|
||||
hasNext: typeof next === "function",
|
||||
sections: Array.isArray(assembly?.sections) ? assembly.sections.length : -1,
|
||||
events: eventsLen,
|
||||
});
|
||||
let assembled = assembly;
|
||||
if (typeof next === "function") {
|
||||
try {
|
||||
@@ -731,6 +798,7 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
// 下游 waterfall 任一环节抛就会把整条 assemble 弄死,UI 卡住发不出去。
|
||||
// 吞掉改用上游装配兜底,inject 保底能挂上。
|
||||
try { console.warn("[dsh-purge] system-prompt/assemble waterfall rejected:", err?.message || err); } catch {}
|
||||
purgeLog("assemble.waterfall", { err: String(err?.message || err) });
|
||||
assembled = assembly;
|
||||
}
|
||||
}
|
||||
@@ -745,6 +813,7 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
return rewriteLiveAssembly(config, assembled, context, decision);
|
||||
} catch (err) {
|
||||
try { console.warn("[dsh-purge] rewriteLiveAssembly failed:", err?.message || err); } catch {}
|
||||
purgeLog("assemble.rewriteFail", { err: String(err?.message || err) });
|
||||
return assembled;
|
||||
}
|
||||
}, { global: true, prepend: true });
|
||||
@@ -762,33 +831,33 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
trackDisposer(installAssembleGuard(prompt, rewriteFn), prompt);
|
||||
} catch { /* 这一层代理包不上时,下面再包插件自己的 */ }
|
||||
}
|
||||
wrapAssemble();
|
||||
wrapAssemble("prepareAssemble");
|
||||
return prompt || null;
|
||||
};
|
||||
globalThis.__dshPurgePrepareAssemble = prepareAssemble;
|
||||
const hungFn = installHungPromptGlobal();
|
||||
// complete:true 会在 waterfall 之后盖掉 sections;包住 assemble 返回值,每轮都补回注入。
|
||||
wrapAssemble();
|
||||
wrapAssemble("init");
|
||||
// guard 需要在每次 cordis 换 systemPrompt 代理时重挂(session 内切预设、subagent fork、
|
||||
// live-mount)。原本 20 秒后 clearInterval,之后换代理就包不上 → 第二轮 inject 走原生
|
||||
// assemble → 宿主按 token 预算裁剪 → 用户看到"只截取了部分"。installAssembleGuard 幂等
|
||||
// (wrappedPrompts WeakSet + 对象 identity 校验),400ms 持续跑到 ctx dispose 的 CPU 代价可忽略。
|
||||
// 400ms 回滚:2000ms 窗口 → 新对话第一次 assemble 可能跑在钩子挂上之前,inject 塌。
|
||||
// CPU 代价(幂等 wrap)相比"新对话失效"的用户感知,根本不值一提。
|
||||
const timer = setInterval(wrapAssemble, 400);
|
||||
const timer = setInterval(() => wrapAssemble("interval"), 400);
|
||||
if (typeof timer.unref === "function") timer.unref();
|
||||
// 下面三个 ctx.on 必须加 flag:installIdentityOverride 若被同一 ctx 二次 apply
|
||||
// (dispose 后重 mount / 热重载),listener 叠加会让 inject 跑 N 遍,也让 wrap 挂 N 层。
|
||||
if (!ctx.__dshPurgeSessionHook) {
|
||||
ctx.__dshPurgeSessionHook = true;
|
||||
try { ctx.on("session/created", wrapAssemble); } catch { /* ignore */ }
|
||||
try { ctx.on("session/created", () => wrapAssemble("sessionCreated")); } catch { /* ignore */ }
|
||||
}
|
||||
if (!ctx.__dshPurgePresetHook) {
|
||||
ctx.__dshPurgePresetHook = true;
|
||||
try {
|
||||
ctx.on("agent-preset/selected", () => {
|
||||
try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ }
|
||||
wrapAssemble();
|
||||
wrapAssemble("presetSelected");
|
||||
}, { global: true });
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
@@ -796,7 +865,7 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
ctx.__dshPurgePreStepHook = true;
|
||||
try {
|
||||
ctx.on("agent/pre-step", (payload, next) => {
|
||||
wrapAssemble();
|
||||
wrapAssemble("preStep");
|
||||
return typeof next === "function" ? next() : payload;
|
||||
}, { global: true, prepend: true });
|
||||
} catch { /* ignore */ }
|
||||
@@ -1401,11 +1470,22 @@ async function handleSkillsCommand(rawInput) {
|
||||
|
||||
export function apply(ctx, config) {
|
||||
const cfg = { ...DEFAULTS, ...(config || {}) };
|
||||
if (!cfg.enabled) return;
|
||||
if (!cfg.enabled) {
|
||||
purgeLog("boot", { enabled: false });
|
||||
return;
|
||||
}
|
||||
purgeLog("boot", {
|
||||
enabled: true,
|
||||
surface: hostctl.currentSurface(),
|
||||
stripMnemon: cfg.stripMnemon !== false,
|
||||
cap: cfg.capabilityProtocol !== false,
|
||||
refusalRecover: cfg.refusalRecover !== false,
|
||||
});
|
||||
core.setHooksDenyConfigValue(cfg.hooksDenyBypass);
|
||||
core.refreshHooksDenySettings();
|
||||
try {
|
||||
const home = core.pinDshHome() || core.findDshHome();
|
||||
purgeLog("home", { home: home || "(none)" });
|
||||
installHungPromptGlobal();
|
||||
// Apply→cleanup→restart 成功后,默认把加密提示词 seed 进 prompt-inject.md。
|
||||
// 用户已经改过的文件不动;只有「没有」或「仍是空文件」时才补写。
|
||||
|
||||
Reference in new issue
Block a user