diff --git a/README.md b/README.md index e2c8712..4cdc5b7 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@
Version 1.1.2
+Version 1.1.3
DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐ @@ -167,13 +167,13 @@ If the official DeepSeek Harness desktop client (EXE) is installed, the button b
🌐 Open Hub page · - 🚀 Install in desktop client + 🚀 Install in desktop client
🔗 **Raw protocol URL:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.2&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.3&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip ``` **Web trigger example:** @@ -186,7 +186,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.2', + version: '1.1.3', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', @@ -205,7 +205,7 @@ export function installDshPurgeToDesktop() { **HTML link:** ```html - + 🚀 Install in desktop client ``` @@ -216,7 +216,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | Plugin id | | name | `dsh-purge` | Display name | -| version | `1.1.2` | Semver | +| version | `1.1.3` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | Zip URL | @@ -537,6 +537,13 @@ If nothing is found, set `DSH_BASE`. No files are changed. ## Changelog +### 1.1.3 + +- Prompt inject once on the first turn; later turns pin the committed system prompt instead of appending a second copy. +- Strip bundled `dsh-mnemon` context rows by default. +- Switching back from a subagent no longer puts the last sent message into the composer. +- Export a Cordis `{ apply }` default so the plugin tree can load. + ### 1.1.2 - Custom OpenAI-compatible APIs no longer 400 on `developer` role: `#42` remaps it back to `system`. diff --git a/README.zh-CN.md b/README.zh-CN.md index 135b5e1..071ef35 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@Version 1.1.2
+Version 1.1.3
DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐ @@ -164,13 +164,13 @@ dsh plugin --profile default remove dsh-purge
🌐 打开插件市场页 · - 🚀 唤起客户端一键安装 + 🚀 唤起客户端一键安装
🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.2&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.3&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.zip ``` **网页端(前端)触发代码示例:** @@ -183,7 +183,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.2', + version: '1.1.3', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', @@ -202,7 +202,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -213,7 +213,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.2` | 语义化版本号 | +| version | `1.1.3` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | zip 下载直链 | @@ -541,6 +541,13 @@ npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑 ## 更新记录 +### 1.1.3 + +- 系统提示词只在每个会话第一轮注入一份;后续轮次钉住已提交的系统提示词,不再追加第二份。 +- 默认剥掉套件自带的 `dsh-mnemon` 上下文注入。 +- 从子代理点回主代理时,不再把上一句已发送的内容填回输入框。 +- 补上 Cordis 需要的 `{ apply }` 默认导出,避免插件树加载失败导致后端退出。 + ### 1.1.2 - 自定义 OpenAI 兼容接口不再因 `developer` 角色 400:`#42` 改回 `system`。 diff --git a/client.js b/client.js index 7187d89..6136525 100644 --- a/client.js +++ b/client.js @@ -1115,12 +1115,14 @@ body[data-ds-dark-theme] .dshp-rewind-menu{background:var(--dsw-specific-menu,#3 body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tertiary,#a8a39a)} `; const DRAFT_KEY = "dshp-rewind-draft:"; - const RESTORED_KEY = "dshp-rewind-done:"; + const ARM_KEY = "dshp-rewind-arm:"; const FILL_DELAYS = [0, 50, 180]; + const ARM_TTL_MS = 45 * 1000; let rewindSeenAt = 0; let rewindSessions = null; let rewindHost = null; let pendingComposer = { sessionId: "", text: "", at: 0 }; + let armedFill = { sessionId: "", text: "", at: 0 }; function rewindText(t, key, fallback) { try { @@ -1149,7 +1151,6 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert const value = isPluginDraft(text) ? "" : (text || ""); pendingComposer = { sessionId, text: value, at: Date.now() }; try { sessionStorage.setItem(DRAFT_KEY + sessionId, value); } catch { /* ignore */ } - try { sessionStorage.removeItem(RESTORED_KEY + sessionId); } catch { /* ignore */ } } function peekDraft(sessionId) { @@ -1158,18 +1159,39 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert try { return sessionStorage.getItem(DRAFT_KEY + sessionId) || ""; } catch { return ""; } } - function takeDraft(sessionId) { - return peekDraft(sessionId); - } - - function markRestored(sessionId) { + function clearStoredDraft(sessionId) { if (!sessionId) return; - try { sessionStorage.setItem(RESTORED_KEY + sessionId, "1"); } catch { /* ignore */ } + if (pendingComposer.sessionId === sessionId) pendingComposer = { sessionId: "", text: "", at: 0 }; + try { sessionStorage.removeItem(DRAFT_KEY + sessionId); } catch { /* ignore */ } + try { sessionStorage.removeItem(ARM_KEY + sessionId); } catch { /* ignore */ } } - function isRestored(sessionId) { - if (!sessionId) return false; - try { return !!sessionStorage.getItem(RESTORED_KEY + sessionId); } catch { return false; } + function armComposerFill(sessionId, text) { + if (!sessionId || !text || isPluginDraft(text)) return; + const at = Date.now(); + armedFill = { sessionId, text, at }; + writeDraft(sessionId, text); + try { sessionStorage.setItem(ARM_KEY + sessionId, String(at)); } catch { /* ignore */ } + } + + function takeArmedFill(sessionId) { + if (!sessionId) return ""; + let text = ""; + let at = 0; + if (armedFill.sessionId === sessionId && armedFill.text) { + text = armedFill.text; + at = armedFill.at; + } else { + text = peekDraft(sessionId); + try { at = Number(sessionStorage.getItem(ARM_KEY + sessionId) || 0); } catch { at = 0; } + } + if (!text || !at || Date.now() - at > ARM_TTL_MS) { + if (text && (!at || Date.now() - at > ARM_TTL_MS)) clearStoredDraft(sessionId); + return ""; + } + clearStoredDraft(sessionId); + armedFill = { sessionId: "", text: "", at: 0 }; + return text; } function conversationInput(sessionId) { @@ -1198,11 +1220,11 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert } function hostSetDraft(sessionId, text) { - if (!sessionId || !text) return false; + if (!sessionId) return false; try { const input = conversationInput(sessionId); if (input && typeof input.setDraft === "function") { - input.setDraft(text); + input.setDraft(text || ""); return true; } } catch { /* ignore */ } @@ -1210,15 +1232,13 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert } function fillComposer(inputActions, text) { - if (!text) return; if (inputActions && typeof inputActions.setDraft === "function") { - try { inputActions.setDraft(text); } catch { /* ignore */ } + try { inputActions.setDraft(text || ""); } catch { /* ignore */ } } } function scheduleComposerFill(sessionId, text, inputActions) { if (!sessionId || !text || isPluginDraft(text)) return; - writeDraft(sessionId, text); let stopped = false; let filled = false; const tryFill = () => { @@ -1239,6 +1259,31 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert for (const ms of FILL_DELAYS) window.setTimeout(tryFill, ms); } + function scheduleEchoClear(sessionId, inputActions) { + if (!sessionId) return; + let last = ""; + let stopped = false; + const tryClear = () => { + if (stopped || !last) return; + const current = String(liveDraft(sessionId, inputActions) || "").trim(); + if (!current) { + stopped = true; + return; + } + if (current !== last) return; + fillComposer(inputActions, ""); + hostSetDraft(sessionId, ""); + clearStoredDraft(sessionId); + stopped = true; + }; + apiJson("/dsh-purge/last-user?sessionId=" + encodeURIComponent(sessionId)).then((data) => { + last = String(data?.text || "").trim(); + if (!last || isPluginDraft(last)) return; + tryClear(); + for (const ms of [0, 50, 180, 400]) window.setTimeout(tryClear, ms); + }).catch(() => {}); + } + async function dropInheritedQueue(sessions, sessionId) { if (!sessions || !sessionId) return; const drop = async () => { @@ -1290,6 +1335,7 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert }); if (data && data.ok && data.sessionId) { const text = isPluginDraft(data.text) ? "" : (data.text || ""); + armComposerFill(data.sessionId, text); scheduleComposerFill(data.sessionId, text); await openRewoundSession(rewindSessions, data.sessionId); scheduleComposerFill(data.sessionId, text); @@ -1316,10 +1362,12 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert useEffect(() => { if (!sessionId) return; - const local = peekDraft(sessionId); - if (!local || isPluginDraft(local) || isRestored(sessionId)) return; - scheduleComposerFill(sessionId, local, inputActions); - markRestored(sessionId); + const armed = takeArmedFill(sessionId); + if (armed) { + scheduleComposerFill(sessionId, armed, inputActions); + return; + } + scheduleEchoClear(sessionId, inputActions); }, [sessionId, inputActions]); useEffect(() => { @@ -1345,7 +1393,7 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert if (!data || !data.ok || !data.sessionId) throw new Error((data && data.error) || "rewind"); if (data.at) rewindSeenAt = data.at; const text = isPluginDraft(data.text) ? "" : (data.text || ""); - writeDraft(data.sessionId, text); + armComposerFill(data.sessionId, text); await openRewoundSession(sessions, data.sessionId); scheduleComposerFill(data.sessionId, text); } catch (e) { @@ -1434,6 +1482,7 @@ body[data-ds-dark-theme] .dshp-rewind-item span{color:var(--dsw-alias-label-tert const current = currentSessionId(sessions); if (current && current !== data.parentId) return; const text = isPluginDraft(data.text) ? "" : (data.text || ""); + armComposerFill(data.sessionId, text); scheduleComposerFill(data.sessionId, text); await openRewoundSession(sessions, data.sessionId); scheduleComposerFill(data.sessionId, text); diff --git a/cordis.patch.yml b/cordis.patch.yml index 79ef8d5..26d1004 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -11,6 +11,8 @@ autoApplyOnStart: true autoUpdateOnStart: true autoRevertOnMissing: false + injectOnce: true + stripMnemon: true verbose: false postPrompt: "" postPromptOrder: 5100 diff --git a/lib/identity.js b/lib/identity.js index 1413fe2..ba189d8 100644 --- a/lib/identity.js +++ b/lib/identity.js @@ -90,12 +90,9 @@ function stripHarnessPersona(text) { } function collectInjectText(purgeSections, fallbackText) { - const fromSections = purgeSections - .map((s) => String(s.text || "").trim()) - .filter(Boolean) - .join("\n\n") - .trim(); - if (fromSections) return fromSections; + const main = purgeSections.find((section) => section.name === "dsh-purge"); + const fromMain = String(main?.text || "").trim(); + if (fromMain) return fromMain; return typeof fallbackText === "string" ? fallbackText.trim() : ""; } @@ -116,6 +113,92 @@ function isPersonaFoldTarget(name, preferPrefix) { return PERSONA_PREFIX_NAMES.has(name) || PERSONA_LEGACY_NAMES.has(name); } +function eventList(session) { + if (!session) return []; + if (typeof session.snapshotEvents === "function") { + try { + const events = session.snapshotEvents(); + if (Array.isArray(events)) return events; + } catch {} + } + if (Array.isArray(session.events)) return session.events; + return []; +} + +function messageText(message) { + if (typeof message === "string") return message; + const content = message?.content; + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content.map((block) => (typeof block?.text === "string" ? block.text : "")).join("\n"); +} + +export function existingSystemPrompt(context) { + const events = eventList(context?.agent?.session || context?.session); + let latest = ""; + for (const event of events) { + if (event?.type !== "system/message") continue; + const text = messageText(event.data?.message || event.data).trim(); + if (text) latest = text; + } + return latest; +} + +export function isFirstConversationTurn(context) { + if (!context || typeof context !== "object") return true; + const explicit = context.turn ?? context.turnIndex ?? context.userTurn ?? context.messageIndex; + if (explicit != null && Number.isFinite(Number(explicit))) return Number(explicit) <= 1; + const events = eventList(context.agent?.session || context.session); + if (events.length > 0) return !events.some((event) => event?.type === "turn/end"); + const msgs = context.messages || context.history || []; + if (!Array.isArray(msgs) || msgs.length === 0) return true; + const users = msgs.filter((m) => { + const role = String(m?.role || m?.type || m?.kind || "").toLowerCase(); + return role === "user" || role === "human"; + }); + return users.length <= 1; +} + +export function promptAlreadyInjected(existing, injectText) { + const inject = String(injectText || "").trim(); + if (!inject) return false; + return String(existing || "").includes(inject.slice(0, Math.min(80, inject.length))); +} + +export function shouldInjectPrompt(context, injectOnce = true, injectText = "") { + if (injectOnce === false) return true; + if (isFirstConversationTurn(context)) return true; + return !promptAlreadyInjected(existingSystemPrompt(context), injectText); +} + +export function isMnemonPluginMessage(message) { + const source = message?.source; + if (!source || typeof source !== "object") return false; + const plugin = String(source.plugin || "").toLowerCase(); + return source.kind === "plugin" && plugin.includes("mnemon"); +} + +function isMnemonSection(name) { + return String(name || "").toLowerCase().includes("mnemon"); +} + +function normalizeRewriteOptions(fallbackInject, options) { + if (fallbackInject && typeof fallbackInject === "object" && !Array.isArray(fallbackInject)) { + return { + fallbackInject: typeof fallbackInject.fallbackInject === "string" ? fallbackInject.fallbackInject : "", + dropMnemon: fallbackInject.dropMnemon !== false, + dropPurgeAfterFold: fallbackInject.dropPurgeAfterFold !== false, + pinPersonaText: typeof fallbackInject.pinPersonaText === "string" ? fallbackInject.pinPersonaText : "", + }; + } + return { + fallbackInject: typeof fallbackInject === "string" ? fallbackInject : "", + dropMnemon: options?.dropMnemon !== false, + dropPurgeAfterFold: options?.dropPurgeAfterFold !== false, + pinPersonaText: typeof options?.pinPersonaText === "string" ? options.pinPersonaText : "", + }; +} + // 0.1.5 优先写入 persona-prefix;无 prefix 时写入 legacy persona。 function foldInjectIntoPersona(sections, injectText) { const inject = typeof injectText === "string" ? injectText.trim() : ""; @@ -138,23 +221,36 @@ function foldInjectIntoPersona(sections, injectText) { return [{ name: "deployment:persona-prefix", text: inject }, ...out]; } -export function rewritePromptAssembly(assembled, fallbackInject = "") { +export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) { if (!assembled || !Array.isArray(assembled.sections)) return assembled; + const opts = normalizeRewriteOptions(fallbackInject, options); + if (opts.pinPersonaText) { + assembled.sections = [{ name: "deployment:persona-prefix", text: opts.pinPersonaText }]; + return assembled; + } const rest = []; const purge = []; for (const section of assembled.sections) { if (!section || section.name === "harness:identity") continue; if (section.name === "dsh-purge:identity") continue; + if (opts.dropMnemon && isMnemonSection(section.name)) continue; const next = { ...section }; if (typeof next.text === "string" && !String(next.name).startsWith("dsh-purge")) { next.text = stripHarnessPersona(next.text); } - if (String(next.name).startsWith("dsh-purge")) purge.push(next); - else rest.push(next); + if (String(next.name).startsWith("dsh-purge")) { + if (!opts.fallbackInject) continue; + purge.push(next); + } else { + rest.push(next); + } } - // fallbackInject:section 被滤掉时从 prompt-inject.md 补回。 - const injectText = collectInjectText(purge, fallbackInject); - assembled.sections = [...foldInjectIntoPersona(rest, injectText), ...purge]; + const injectText = opts.fallbackInject ? collectInjectText(purge, opts.fallbackInject) : ""; + const folded = foldInjectIntoPersona(rest, injectText); + const extras = opts.dropPurgeAfterFold + ? purge.filter((section) => section.name !== "dsh-purge") + : purge; + assembled.sections = [...folded, ...extras]; return assembled; } diff --git a/lib/index.js b/lib/index.js index 6d7d79a..7277124 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2,13 +2,17 @@ import fs from "node:fs"; import { promises as fsp } from "node:fs"; import path from "node:path"; import { spawn } from "node:child_process"; +import { AsyncLocalStorage } from "node:async_hooks"; import { fileURLToPath } from "node:url"; import * as core from "./core.js"; import * as rules from "./rules.js"; import * as updater from "./update.js"; import { GLOBAL_PROMPT_ORDER, + existingSystemPrompt, + isMnemonPluginMessage, rewritePromptAssembly, + shouldInjectPrompt, } from "./identity.js"; import * as rewind from "./rewind.js"; @@ -21,6 +25,8 @@ const DEFAULTS = { autoApplyOnStart: true, autoUpdateOnStart: true, autoRevertOnMissing: false, + injectOnce: true, + stripMnemon: true, postPrompt: "", postPromptOrder: 5100, verbose: false, @@ -108,12 +114,20 @@ function readInjectFile(injectFile) { } } +const assembleState = new AsyncLocalStorage(); + +function injectAllowedNow(config) { + if (config.enabled === false) return false; + const state = assembleState.getStore(); + return !state || state.allow !== false; +} + export function registerPromptSections(ctx, config, injectFile) { ctx.systemPrompt.section({ name: "dsh-purge", order: GLOBAL_PROMPT_ORDER, text: () => { - if (!config.enabled) return ""; + if (!injectAllowedNow(config)) return ""; return readInjectFile(injectFile); }, }); @@ -122,7 +136,7 @@ export function registerPromptSections(ctx, config, injectFile) { name: "dsh-purge:rules", order: GLOBAL_PROMPT_ORDER + 1, text: () => { - if (!config.enabled) return ""; + if (!injectAllowedNow(config)) return ""; try { return rules.activeRuleText(core.findDshHome()); } catch { @@ -139,7 +153,7 @@ export function registerPromptSections(ctx, config, injectFile) { ctx.systemPrompt.section({ name: "dsh-purge:post", order: config.postPromptOrder, - text: postPrompt, + text: () => (injectAllowedNow(config) ? postPrompt : ""), }); } @@ -165,26 +179,50 @@ function readInjectFallback() { } } -function installIdentityOverride(ctx) { +function installMnemonMessageStrip(ctx, config = {}) { + if (config.stripMnemon === false) return; if (typeof ctx.on !== "function") return; - const hook = async (_assembly, _context, next) => { - const assembled = typeof next === "function" ? await next() : _assembly; - return rewritePromptAssembly(assembled, readInjectFallback()); + if (ctx.__dshPurgeMnemonStrip) return; + ctx.__dshPurgeMnemonStrip = true; + const wrap = async (_payload, next) => { + const decision = await next(); + if (!decision || !Array.isArray(decision.messages)) return decision; + const messages = decision.messages.filter((message) => !isMnemonPluginMessage(message)); + if (messages.length === decision.messages.length) return decision; + return { ...decision, messages }; }; - // prepend:false 先于 phase-1 滤镜;prepend:true 在滤镜之后再折一次。 - try { - ctx.on("system-prompt/assemble", hook, { global: true, prepend: false }); - } catch {} - ctx.on("system-prompt/assemble", hook, { global: true, prepend: true }); const late = () => { try { - ctx.on("system-prompt/assemble", hook, { global: true, prepend: true }); + ctx.on("agent/pre-step", wrap, { global: true, prepend: true }); } catch {} }; + late(); queueMicrotask(late); setTimeout(late, 1500); } +function installIdentityOverride(ctx, config = {}) { + if (typeof ctx.on !== "function") return; + if (ctx.__dshPurgeAssembleHook) return; + ctx.__dshPurgeAssembleHook = true; + const hook = async (_assembly, context, next) => { + const inject = config.enabled === false ? "" : readInjectFallback(); + const allow = config.enabled !== false && shouldInjectPrompt(context, config.injectOnce !== false, inject); + const pin = !allow && existingSystemPrompt(context); + return assembleState.run({ allow }, async () => { + const assembled = typeof next === "function" ? await next() : _assembly; + return rewritePromptAssembly(assembled, { + fallbackInject: allow ? inject : "", + dropMnemon: config.stripMnemon !== false, + dropPurgeAfterFold: true, + pinPersonaText: pin, + }); + }); + }; + // 只挂一次:挂多次会让同一轮 assemble 折两遍,UI 也会显示两次注入。 + ctx.on("system-prompt/assemble", hook, { global: true, prepend: true }); +} + const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"]; function desktopShimNeedsPatch(dirs) { @@ -483,7 +521,8 @@ export function apply(ctx, config) { } }); - installIdentityOverride(ctx); + installIdentityOverride(ctx, cfg); + installMnemonMessageStrip(ctx, cfg); const injectFile = core.findOverrideFile(core.findDshHome()); registerPromptSections(ctx, cfg, injectFile); @@ -726,6 +765,24 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: status"); + host.webServer.register({ + kind: "exact", + path: "/dsh-purge/last-user", + handler: async (request, response) => { + if (request.method !== "GET") { + response.writeHead(405, { allow: "GET" }); + response.end(); + return; + } + try { + const url = new URL(request.url, "http://127.0.0.1"); + const sessionId = String(url.searchParams.get("sessionId") || "").trim(); + sendJson(response, 200, await rewind.readLastUserText(ctx, sessionId)); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e) }); + } + }, + }, "dsh-purge: last user"); host.webServer.register({ kind: "exact", path: "/dsh-purge/rewind/options", @@ -1088,3 +1145,11 @@ async function readJsonBody(request) { if (!raw) return {}; return JSON.parse(raw); } + +const plugin = { + name, + inject, + apply, +}; + +export default plugin; diff --git a/lib/rewind.js b/lib/rewind.js index b656e63..4bbc2a6 100644 --- a/lib/rewind.js +++ b/lib/rewind.js @@ -202,6 +202,24 @@ export function getPending() { return lastPending; } +export function lastHumanUserText(events) { + const list = Array.isArray(events) ? events : []; + for (let i = list.length - 1; i >= 0; i -= 1) { + if (isHumanUserEvent(list[i])) return userTextFromEvent(list[i]); + } + return ""; +} + +export async function readLastUserText(ctx, sessionId) { + if (!sessionId) return { ok: false, text: "", error: "没有当前会话" }; + try { + const log = await readSessionLog(ctx, sessionId); + return { ok: true, text: lastHumanUserText(log.events) }; + } catch (err) { + return { ok: false, text: "", error: errorText(err) }; + } +} + function disposeObservation(observed) { try { observed?.[Symbol.dispose]?.(); diff --git a/package.json b/package.json index 1e24051..aaff5ba 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,13 @@ { "name": "dsh-purge", - "version": "1.1.2", + "version": "1.1.3", "description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐", "type": "module", "main": "lib/index.js", "exports": { - ".": "./lib/index.js", + ".": { + "default": "./lib/index.js" + }, "./client": "./client.js", "./package.json": "./package.json" }, diff --git a/tests/identity-inject-once.test.js b/tests/identity-inject-once.test.js new file mode 100644 index 0000000..3735d10 --- /dev/null +++ b/tests/identity-inject-once.test.js @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import { + existingSystemPrompt, + isFirstConversationTurn, + isMnemonPluginMessage, + promptAlreadyInjected, + rewritePromptAssembly, + shouldInjectPrompt, +} from "../lib/identity.js"; + +const inject = "You are Little Code Sauce. This is the operator prompt."; + +assert.equal(isFirstConversationTurn({ messages: [{ role: "user", text: "hi" }] }), true); +assert.equal( + isFirstConversationTurn({ + messages: [ + { role: "user", text: "hi" }, + { role: "assistant", text: "ok" }, + { role: "user", text: "again" }, + ], + }), + false, +); +assert.equal(isFirstConversationTurn({ agent: { session: { events: [] } } }), true); +assert.equal( + isFirstConversationTurn({ + agent: { session: { events: [{ type: "turn/end", data: { turn: 1 } }] } }, + }), + false, +); +assert.equal(shouldInjectPrompt({ turn: 1 }, true, inject), true); +assert.equal( + shouldInjectPrompt( + { + agent: { + session: { + events: [ + { type: "system/message", data: { message: { content: [{ type: "text", text: inject }] } } }, + { type: "turn/end", data: { turn: 1 } }, + ], + }, + }, + }, + true, + inject, + ), + false, +); +assert.equal(shouldInjectPrompt({ turn: 2 }, false, inject), true); +assert.equal(promptAlreadyInjected(inject + "\nWorking directory: x", inject), true); + +const session = { + events: [ + { type: "system/message", data: { message: { content: [{ type: "text", text: "old" }] } } }, + { type: "system/message", data: { message: { content: [{ type: "text", text: inject }] } } }, + ], +}; +assert.equal(existingSystemPrompt({ agent: { session } }), inject); +assert.equal( + isMnemonPluginMessage({ source: { kind: "plugin", plugin: "dsh-mnemon" } }), + true, +); +assert.equal( + isMnemonPluginMessage({ source: { kind: "plugin", plugin: "@deepseek-ai/dsh-system-prompt" } }), + false, +); + +const first = rewritePromptAssembly( + { + sections: [ + { name: "deployment:persona-prefix", text: "Working directory: {{cwd}}." }, + { name: "dsh-purge", text: inject }, + { name: "dsh-purge:rules", text: "extra rule" }, + { name: "dsh-mnemon", text: "old memory dump" }, + { name: "mnemon:routing", text: "use memory tools" }, + ], + }, + { fallbackInject: inject, dropMnemon: true, dropPurgeAfterFold: true }, +); +const names = first.sections.map((s) => s.name); +assert.equal(names.includes("dsh-purge"), false); +assert.equal(names.some((n) => String(n).includes("mnemon")), false); +assert.equal(first.sections.filter((s) => String(s.text || "").includes("Little Code Sauce")).length, 1); +assert.equal(first.sections.some((s) => s.name === "dsh-purge:rules"), true); + +const later = rewritePromptAssembly( + { + sections: [ + { name: "deployment:persona-prefix", text: "Working directory: {{cwd}}." }, + { name: "dsh-purge", text: inject }, + { name: "dsh-mnemon", text: "old memory dump" }, + ], + }, + { fallbackInject: "", dropMnemon: true, dropPurgeAfterFold: true, pinPersonaText: inject }, +); +assert.deepEqual(later.sections, [{ name: "deployment:persona-prefix", text: inject }]); + +console.log("identity-inject-once ok"); diff --git a/tests/rewind-last-user.test.js b/tests/rewind-last-user.test.js new file mode 100644 index 0000000..772e673 --- /dev/null +++ b/tests/rewind-last-user.test.js @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import { lastHumanUserText } from "../lib/rewind.js"; + +const events = [ + { type: "turn/start", seq: 1 }, + { + type: "user/message", + seq: 2, + data: { content: [{ type: "text", text: "first" }], source: { kind: "user" } }, + }, + { type: "turn/end", seq: 3 }, + { type: "turn/start", seq: 4 }, + { + type: "user/message", + seq: 5, + data: { content: [{ type: "text", text: "second" }], source: { kind: "user" } }, + }, + { + type: "user/message", + seq: 6, + data: { content: [{ type: "text", text: "[MNEMON] skip" }], source: { kind: "plugin", plugin: "dsh-mnemon" } }, + }, +]; + +assert.equal(lastHumanUserText(events), "second"); +assert.equal(lastHumanUserText([]), ""); +assert.equal(lastHumanUserText(null), ""); + +console.log("rewind-last-user ok");