diff --git a/lib/identity.js b/lib/identity.js index e7521ef..6de0fc7 100644 --- a/lib/identity.js +++ b/lib/identity.js @@ -629,11 +629,14 @@ export function installAssembleGuard(prompt, rewriteFn) { desc = undefined; } const bindSlot = (slot) => { - const prev = slot.rewrite; slot.rewrite = rewriteFn; - return function dispose() { - if (slot.rewrite === rewriteFn) slot.rewrite = prev || null; - }; + // dispose 必须 noop:ctx.effect cleanup 在 cordis 正常生命周期中也会触发 + // (child ctx scope 结束 / session 边界 / 预设切换),一旦执行链式 dispose, + // slot.rewrite 会被回滚到 null → assemble 走原生 → inject 失效 → 用户看到 + // "任务到一半就苏醒""保存都救不了"的拒答。 + // 不清 slot.rewrite 是安全的:下次 install 直接覆盖,prompt 对象被 GC 时 + // 整个 slot 一起回收。 + return function dispose() { /* noop */ }; }; if (desc && typeof desc.get === "function" && desc.get[ASSEMBLE_GUARD]) { return bindSlot(desc.get[ASSEMBLE_GUARD]); @@ -673,7 +676,8 @@ export function installAssembleGuard(prompt, rewriteFn) { return wrapped; }; const dispose = function dispose() { - if (slot.rewrite === rewriteFn) slot.rewrite = null; + // 同 bindSlot:不清 slot.rewrite,避免 ctx.effect cleanup 时 inject 失效。 + // 下次 install 会直接覆盖 slot.rewrite,prompt 对象被 GC 时 slot 一起回收。 }; try { let current = wrap(original); @@ -718,9 +722,12 @@ export function installAssembleGuard(prompt, rewriteFn) { export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) { if (!assembled || !Array.isArray(assembled.sections)) return assembled; const opts = normalizeRewriteOptions(fallbackInject, options); + // 不原地改写:宿主若复用同一个 assembled 对象,下一轮进来已被我们污染过(多轮 head + // dsh-purge / CAPABILITY_SECTION 残留)。返回新对象,传入对象保持原状。 + const originalSections = assembled.sections; const rest = []; const purge = []; - for (const section of assembled.sections) { + for (const section of originalSections) { if (!section || section.name === "harness:identity") continue; if (section.name === "dsh-purge:identity") continue; if (opts.dropMnemon && isMnemonSection(section.name)) continue; @@ -767,25 +774,28 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options = ? insertRoleSection(insertCardSection(sections, opts.cardText), opts.roleText) : withOps; } - assembled.sections = sanitizeAssemblySections(leadWithInject(sections, injectText, protocol)); + let outSections = sanitizeAssemblySections(leadWithInject(sections, injectText, protocol)); if (injectText) { const needle = injectText.slice(0, 80); - const has = assembled.sections.some((section) => ( + const has = outSections.some((section) => ( typeof section?.text === "string" && needle && section.text.includes(needle) )); if (!has) { - assembled.sections = [ + outSections = [ { name: "dsh-purge", text: injectText, interpolate: false, order: GLOBAL_PROMPT_ORDER + 1, }, - ...assembled.sections.filter((section) => section && section.name !== "dsh-purge"), + ...outSections.filter((section) => section && section.name !== "dsh-purge"), ]; } } - if (!Array.isArray(assembled.contexts)) assembled.contexts = []; - if (!Array.isArray(assembled.tools)) assembled.tools = []; - return assembled; + return { + ...assembled, + sections: outSections, + contexts: Array.isArray(assembled.contexts) ? assembled.contexts : [], + tools: Array.isArray(assembled.tools) ? assembled.tools : [], + }; } diff --git a/lib/index.js b/lib/index.js index ce6894b..2f6ccf7 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,3 +1,4 @@ +import fs from "node:fs"; import { fsFor } from "./extract-asar.js"; import * as core from "./core.js"; import * as hostctl from "./host.js"; @@ -157,17 +158,43 @@ function injectAllowedNow(config) { } /** 提示词框自改 > prompt-inject.md > 加密默认(见 rules.resolveInjectText)。 */ +// mtime 节流:400ms setInterval + 每 pre-step + 每 preset-selected + 每 readInjectFallback +// 的高频触发下,disk sync + 3 次 hashOverride + 2 次模块级赋值一轮能点 20 次。 +// 短窗复用上次结果:home 没换 + 文件 mtime 没变 + 距上次 < 200ms,直接返回缓存。 +let hungCache = { home: "", mtime: 0, at: 0, resolved: null }; +const HUNG_CACHE_MS = 200; +function statInjectMtimeMs(home) { + if (!home) return 0; + try { + return Math.floor(fs.statSync(core.findOverrideFile(home)).mtimeMs); + } catch { return 0; } +} function refreshHungOperator(dshHome = core.findDshHome()) { const home = core.pinDshHome() || dshHome || core.findDshHome(); + const now = Date.now(); + const mtimeBefore = statInjectMtimeMs(home); + if ( + hungCache.resolved + && hungCache.home === home + && hungCache.mtime === mtimeBefore + && now - hungCache.at < HUNG_CACHE_MS + ) { + return hungCache.resolved; + } try { core.syncPromptInjectOnDiskSync(home); } catch { /* 同步失败仍按 resolve 走 */ } const resolved = rules.resolveInjectText(home); - const text = resolved.text || core.normalizeOverride(core.defaultOverrideText()) || ""; + // 兜底顺序:resolved.text > 加密默认 > 永不空串(避免二轮 fallbackInject 为空走 purge[] 残留)。 + const fallback = core.normalizeOverride(core.defaultOverrideText()) || ""; + const text = resolved.text || fallback; if (text) { core.hangOperatorPrompt(text); // 与点「保存」同一钉钉:不点保存,组装也要读到这一份全文。 core.rememberCommittedOverride(home, text); } - return { ...resolved, text: text || resolved.text }; + const out = { ...resolved, text: text || resolved.text }; + // 用 sync 之后的 mtime 存 cache,下次高频轮询(文件没被外部动)直接命中。 + hungCache = { home, mtime: statInjectMtimeMs(home), at: now, resolved: out }; + return out; } function installHungPromptGlobal() { @@ -445,18 +472,25 @@ function installRewindDeriveFilter(ctx) { function installIdentityOverride(ctx, config = {}) { if (typeof ctx.on !== "function") return; installSubagentRoleCapture(ctx); - // installAssembleGuard 新契约:成功返回 dispose(), 失败/幂等返回 false。统一回收,避免 - // 预设切换 + session/created 事件连环叠层,每轮注入翻倍。 + // installAssembleGuard 幂等:slot.rewrite 已挂的 prompt 对象只刷新 rewriteFn, + // 不再 return 新 dispose。原实现每 400ms + 每 pre-step push 一个 noop closure 入 Set, + // 2 小时 session 累积上万条。改为:只 track 首次真正挂上的 disposer。 const wrapDisposers = new Set(); - const trackDisposer = (d) => { - if (typeof d === "function") wrapDisposers.add(d); + const wrappedPrompts = new WeakSet(); + const trackDisposer = (d, prompt) => { + if (typeof d !== "function") return d; + if (prompt) { + if (wrappedPrompts.has(prompt)) return d; + wrappedPrompts.add(prompt); + } + wrapDisposers.add(d); return d; }; + const rewriteFn = (assembled, context) => rewriteLiveAssembly(config, assembled, context); const wrapAssemble = () => { try { - return trackDisposer(installAssembleGuard(ctx.systemPrompt, (assembled, context) => ( - rewriteLiveAssembly(config, assembled, context) - ))); + const prompt = ctx.systemPrompt; + return trackDisposer(installAssembleGuard(prompt, rewriteFn), prompt); } catch { return false; } @@ -481,9 +515,7 @@ function installIdentityOverride(ctx, config = {}) { try { prompt = loopCtx && loopCtx.systemPrompt; } catch { prompt = null; } if (prompt) { try { - trackDisposer(installAssembleGuard(prompt, (assembled, context) => ( - rewriteLiveAssembly(config, assembled, context) - ))); + trackDisposer(installAssembleGuard(prompt, rewriteFn), prompt); } catch { /* 这一层代理包不上时,下面再包插件自己的 */ } } wrapAssemble(); @@ -496,22 +528,33 @@ function installIdentityOverride(ctx, config = {}) { // guard 需要在每次 cordis 换 systemPrompt 代理时重挂(session 内切预设、subagent fork、 // live-mount)。原本 20 秒后 clearInterval,之后换代理就包不上 → 第二轮 inject 走原生 // assemble → 宿主按 token 预算裁剪 → 用户看到"只截取了部分"。installAssembleGuard 幂等 - // (只做对象 identity 校验 + Map get),400ms 持续跑到 ctx dispose 的 CPU 代价可忽略。 + // (wrappedPrompts WeakSet + 对象 identity 校验),400ms 持续跑到 ctx dispose 的 CPU 代价可忽略。 const timer = setInterval(wrapAssemble, 400); if (typeof timer.unref === "function") timer.unref(); - try { ctx.on("session/created", wrapAssemble); } catch { /* ignore */ } - try { - ctx.on("agent-preset/selected", () => { - try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ } - wrapAssemble(); - }, { global: true }); - } catch { /* ignore */ } - try { - ctx.on("agent/pre-step", (payload, next) => { - wrapAssemble(); - return typeof next === "function" ? next() : payload; - }, { global: true, prepend: true }); - } catch { /* ignore */ } + // 下面三个 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 */ } + } + if (!ctx.__dshPurgePresetHook) { + ctx.__dshPurgePresetHook = true; + try { + ctx.on("agent-preset/selected", () => { + try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ } + wrapAssemble(); + }, { global: true }); + } catch { /* ignore */ } + } + if (!ctx.__dshPurgePreStepHook) { + ctx.__dshPurgePreStepHook = true; + try { + ctx.on("agent/pre-step", (payload, next) => { + wrapAssemble(); + return typeof next === "function" ? next() : payload; + }, { global: true, prepend: true }); + } catch { /* ignore */ } + } // 热重载/卸载时统一回收:轮询 timer、guard 代理层、暴露给 agent loop 的全局钩子, // 都在同一个 effect 里扫掉;避免下次 apply 再绑一层造成多次写入。 try { @@ -521,6 +564,10 @@ function installIdentityOverride(ctx, config = {}) { try { d(); } catch { /* ignore */ } } wrapDisposers.clear(); + // 清 flag,下次 apply 允许重新挂 listener;不然 ctx 复用时沉默无响应。 + delete ctx.__dshPurgeSessionHook; + delete ctx.__dshPurgePresetHook; + delete ctx.__dshPurgePreStepHook; if (globalThis.__dshPurgePrepareAssemble === prepareAssemble) { delete globalThis.__dshPurgePrepareAssemble; }