From 7642678a27219cefbabc323f1fe183e255695de1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= Date: Fri, 18 Sep 2026 00:27:33 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.1=EF=BC=8C?= =?UTF-8?q?=E5=9B=9E=E9=80=80=E4=B8=8A=E4=B8=80=E5=8F=A5=E5=B9=B6=E6=B8=85?= =?UTF-8?q?=E6=8E=89=E5=BE=85=E5=8F=91=E9=80=81=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- README.md | 22 ++- README.zh-CN.md | 22 ++- client.js | 407 +++++++++++++++++++++++++++++++++++++++++++- lib/core.js | 36 +++- lib/index.js | 85 ++++++++++ lib/rewind.js | 436 ++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 3 +- 7 files changed, 986 insertions(+), 25 deletions(-) create mode 100644 lib/rewind.js diff --git a/README.md b/README.md index f01ed2a..62aa29e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.0

+

Version 1.1.1

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.0&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.1&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.0', + version: '1.1.1', 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.0` | Semver | +| version | `1.1.1` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | Zip URL | @@ -456,12 +456,15 @@ dsh-purge --edit /purge status | apply | revert | edit | help /rules list | use | create | delete | reset | help +/rewind purge_status purge_apply purge_revert ``` Patched packages load only after a restart. Apply does not restart by itself. +The composer **Undo** button drops the last turn and puts the last user sentence back in the input. On the main agent you can rewind once or the whole last round (including subagents). After rewind, send only what is in the box now. `/rewind` does the same. + --- ## Local checks @@ -469,6 +472,7 @@ Patched packages load only after a restart. Apply does not restart by itself. ```sh node --check lib/index.js node --check lib/core.js +node --check lib/rewind.js node --check client.js ``` @@ -533,6 +537,12 @@ If nothing is found, set `DSH_BASE`. No files are changed. ## Changelog +### 1.1.1 + +- Composer **Undo** / `/rewind`: main agent can rewind once or the last round (drop this round’s subagents); a subagent rewinds once. +- After rewind, the input box keeps the last user sentence, but sending again is a new turn — leftover inbox is cleared so the old prompt is not auto-sent. +- Optional unmatched patches count as skipped, not failed. + ### 1.1.0 - Check update and download share one button: after a check, it becomes **Update** and the pill shows the remote version. diff --git a/README.zh-CN.md b/README.zh-CN.md index a62fd75..91dc867 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.0

+

Version 1.1.1

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.0&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.1&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.0', + version: '1.1.1', 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.0` | 语义化版本号 | +| version | `1.1.1` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | zip 下载直链 | @@ -459,6 +459,7 @@ dsh-purge --edit # 聊天 /purge status | apply | revert | edit | help /rules list | use | create | delete | reset | help +/rewind # 模型工具 purge_status purge_apply purge_revert @@ -466,6 +467,8 @@ purge_status purge_apply purge_revert 设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。 +输入框旁的「回退」会丢掉最近一轮对话,并把上一句填回输入框;聊天里 `/rewind` 同样可用。 + --- ## 本地校验 @@ -473,6 +476,7 @@ purge_status purge_apply purge_revert ```sh node --check lib/index.js node --check lib/core.js +node --check lib/rewind.js node --check client.js ``` @@ -537,6 +541,12 @@ npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑 ## 更新记录 +### 1.1.1 + +- 输入框旁「回退」/ `/rewind`:主代理可选回退一次或上一轮(丢掉本轮子代理);子代理直接回退一次。 +- 回退后输入框仍是上一句用户内容,再次发送是全新一轮:清掉待发送队列,不会把旧提示再自动发出去。 +- 可选补丁对不上时记为跳过,不再算失败。 + ### 1.1.0 - 检测更新与下载分开:先查,有新版本按钮变成「更新」,版本号显示远端。 diff --git a/client.js b/client.js index 4be43f4..de75ff9 100644 --- a/client.js +++ b/client.js @@ -70,6 +70,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "table.status": "状态", "status.applied": "已应用", "status.pending": "待应用", + "status.skipped": "跳过", + "apply.hint": "待应用=原文还在。跳过=没装或官方已改写,再点也不会变。", "skip": "跳过", "unknown": "未知", "delete": "删除", @@ -175,6 +177,15 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "patch.39": "persona text→prefix(0.1.2 预设)", "patch.40": "会话 v0 plugin summary(mnemon)", "patch.41": "complete 预设仍保留注入", + "rewind.label": "回退", + "rewind.aria": "回退", + "rewind.busy": "回退中…", + "rewind.empty": "没有可回退的上一句", + "rewind.fail": "回退失败: {error}", + "rewind.once": "回退一次", + "rewind.once.hint": "只退当前对话上一句", + "rewind.round": "回退上一轮", + "rewind.round.hint": "退回上一轮主对话,本轮子代理一并去掉", }; const en = { @@ -193,6 +204,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "table.status": "Status", "status.applied": "Applied", "status.pending": "Pending", + "status.skipped": "Skipped", + "apply.hint": "Pending = original text still present. Skipped = missing or already rewritten.", "skip": "Skipped", "unknown": "Unknown", "delete": "Delete", @@ -298,6 +311,15 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "patch.39": "persona text→prefix (0.1.2 presets)", "patch.40": "session v0 plugin summary (mnemon)", "patch.41": "Keep inject when a complete prompt is set", + "rewind.label": "Undo", + "rewind.aria": "Undo", + "rewind.busy": "Undoing…", + "rewind.empty": "Nothing to undo", + "rewind.fail": "Undo failed: {error}", + "rewind.once": "Undo once", + "rewind.once.hint": "Drop the last turn of this chat", + "rewind.round": "Undo last round", + "rewind.round.hint": "Back to the previous main turn, including this round's subagents", }; const THEME_KEY = "dshp-theme"; @@ -398,17 +420,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { function statusKind(st) { if (st === "applied" || st === "already") return "ok"; if (st === "pending") return "wait"; - if (st === "missing_file") return "miss"; + if (st === "missing_file" || st === "skipped") return "miss"; return "bad"; } function statusLabel(st, t) { if (st === "applied" || st === "already") return t("status.applied"); if (st === "pending") return t("status.pending"); - if (st === "missing_file" || st === "skipped") return t("skip"); + if (st === "skipped") return t("status.skipped"); + if (st === "missing_file") return t("skip"); return st || t("unknown"); } + function statusSettled(st) { + return st === "applied" || st === "already" || st === "skipped" || st === "missing_file"; + } + function shimKind(v) { if (v === "patched") return "ok"; if (v === "original") return "wait"; @@ -441,7 +468,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const st = state.patch_status[id] || state.patch_status[String(id)] || "missing_file"; return { id, st, label: t("patch." + id) }; }); - const done = rows.filter((r) => r.st === "applied" || r.st === "already").length; + const done = rows.filter((r) => statusSettled(r.st)).length; const expanded = !!open[group.key]; return h("div", { key: group.key, className: "dshp-group" }, h("button", { @@ -628,7 +655,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const s = state; const total = s && s.patches_total ? s.patches_total : 26; const applied = s && typeof s.patches_applied === "number" ? s.patches_applied : 0; - const pct = total ? Math.round((applied / total) * 100) : 0; + const skipped = s && typeof s.patches_skipped === "number" ? s.patches_skipped : 0; + const settled = Math.min(total, applied + skipped); + const pct = total ? Math.round((settled / total) * 100) : 0; const localVer = (s && s.plugin_version) || (updateInfo && updateInfo.localVersion) || ""; const remoteVer = updateInfo && (updateInfo.remoteVersion || updateInfo.remoteSha) || ""; @@ -656,7 +685,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { ), s ? h("div", { className: "dshp-metrics" }, h("div", { className: "dshp-metric" }, - h("b", null, applied + " / " + total), + h("b", null, settled + " / " + total), h("span", null, t("metric.purged")), ), h("div", { className: "dshp-metric" }, @@ -685,6 +714,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { h(Btn, { kind: "danger", disabled: patchBusy, onClick: () => doAction("revert", "action.revert") }, t("btn.revert")), noticeNode(notice), ), + h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("apply.hint")), askRestart ? h("div", { className: "dshp-ask" }, h("span", null, t("restart.confirm")), h(Btn, { tiny: true, onClick: () => setAskRestart(false) }, t("restart.later")), @@ -1063,6 +1093,364 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { ); } + const REWIND_CSS = ` +.dshp-rewind-wrap{position:relative;display:inline-flex} +.dshp-rewind{appearance:none;display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 8px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary,currentColor);font:12px/1 var(--ds-font-sans,system-ui,sans-serif);cursor:pointer} +.dshp-rewind:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary,currentColor)} +.dshp-rewind:disabled{opacity:.4;cursor:default} +.dshp-rewind svg{display:block} +.dshp-rewind-menu{position:absolute;right:0;bottom:calc(100% + 6px);z-index:100;box-sizing:border-box;min-width:196px;padding:4px;border:0;border-radius:12px;background:var(--dsw-specific-menu,#fff);color:var(--dsw-alias-label-primary,#1a1a1a);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent,0 8px 24px rgba(0,0,0,.16))} +body[data-ds-dark-theme] .dshp-rewind-menu{background:var(--dsw-specific-menu,#32312d);color:var(--dsw-alias-label-primary,#e6e2db);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1,#3f3d38);box-shadow:var(--dsw-elevation-prominent,0 10px 28px rgba(0,0,0,.45))} +.dshp-rewind-item{display:flex;flex-direction:column;gap:2px;width:100%;padding:8px 10px;border:0;border-radius:8px;background:transparent;color:inherit;text-align:left;cursor:pointer;font:12px/1.3 var(--ds-font-sans,system-ui,sans-serif)} +.dshp-rewind-item:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))} +.dshp-rewind-item b{font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,inherit)} +.dshp-rewind-item span{color:var(--dsw-alias-label-tertiary,#9a958c);font-size:11px} +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 FILL_DELAYS = [0, 50, 180]; + let rewindSeenAt = 0; + let rewindSessions = null; + let rewindHost = null; + let pendingComposer = { sessionId: "", text: "", at: 0 }; + + function rewindText(t, key, fallback) { + try { + if (typeof t === "function") { + const value = t(key); + if (value && value !== key) return value; + } + } catch { /* ignore */ } + return fallback; + } + + function currentSessionId(sessions) { + try { return sessions?.list?.getSnapshot?.()?.current || ""; } catch { return ""; } + } + + function isPluginDraft(text) { + const value = String(text || "").trim(); + if (!value) return false; + return /^\[MNEMON\]/i.test(value) + || /MNEMON RUNTIME MEMORY SNAPSHOT/i.test(value) + || /^MNEMON VIEW TOOLS/im.test(value); + } + + function writeDraft(sessionId, text) { + if (!sessionId) return; + 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) { + if (!sessionId) return ""; + if (pendingComposer.sessionId === sessionId && pendingComposer.text) return pendingComposer.text; + try { return sessionStorage.getItem(DRAFT_KEY + sessionId) || ""; } catch { return ""; } + } + + function takeDraft(sessionId) { + return peekDraft(sessionId); + } + + function markRestored(sessionId) { + if (!sessionId) return; + try { sessionStorage.setItem(RESTORED_KEY + sessionId, "1"); } catch { /* ignore */ } + } + + function isRestored(sessionId) { + if (!sessionId) return false; + try { return !!sessionStorage.getItem(RESTORED_KEY + sessionId); } catch { return false; } + } + + function conversationInput(sessionId) { + try { + const host = rewindHost; + const conversation = host?.conversation || (typeof host?.get === "function" ? host.get("conversation") : undefined); + const sessions = host?.sessions || rewindSessions; + const actx = typeof sessions?.scope === "function" ? sessions.scope(sessionId) : undefined; + if (conversation?.input?.for && actx) return conversation.input.for(actx); + return conversation?.input || null; + } catch { + return null; + } + } + + function liveDraft(sessionId, inputActions) { + try { + const fromActions = inputActions?.state?.getSnapshot?.()?.draft; + if (typeof fromActions === "string") return fromActions; + } catch { /* ignore */ } + try { + const draft = conversationInput(sessionId)?.state?.getSnapshot?.()?.draft; + if (typeof draft === "string") return draft; + } catch { /* ignore */ } + return ""; + } + + function hostSetDraft(sessionId, text) { + if (!sessionId || !text) return false; + try { + const input = conversationInput(sessionId); + if (input && typeof input.setDraft === "function") { + input.setDraft(text); + return true; + } + } catch { /* ignore */ } + return false; + } + + function fillComposer(inputActions, text) { + if (!text) return; + if (inputActions && typeof inputActions.setDraft === "function") { + 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 = () => { + if (stopped) return; + const current = liveDraft(sessionId, inputActions); + if (filled && current !== text) { + stopped = true; + return; + } + if (current && current !== text) { + stopped = true; + return; + } + fillComposer(inputActions, text); + hostSetDraft(sessionId, text); + filled = true; + }; + for (const ms of FILL_DELAYS) window.setTimeout(tryFill, ms); + } + + async function dropInheritedQueue(sessions, sessionId) { + if (!sessions || !sessionId) return; + const drop = async () => { + try { + const actx = typeof sessions.scope === "function" ? sessions.scope(sessionId) : undefined; + const face = typeof sessions.sessionOf === "function" ? sessions.sessionOf(actx) : undefined; + const queue = face?.getSnapshot?.()?.queue || []; + for (const item of queue) { + const id = item?.id || item?.itemId; + if (!id) continue; + try { await face.updateQueue?.(id, { kind: "remove" }); } catch { /* ignore */ } + } + } catch { /* ignore */ } + }; + await drop(); + window.setTimeout(() => { drop(); }, 80); + } + + async function openRewoundSession(sessions, sessionId) { + if (!sessions || !sessionId) return; + try { await sessions.refresh?.(); } catch { /* ignore */ } + try { sessions.open(sessionId); } catch { /* ignore */ } + await dropInheritedQueue(sessions, sessionId); + window.setTimeout(() => { + try { sessions.open(sessionId); } catch { /* ignore */ } + dropInheritedQueue(sessions, sessionId); + }, 250); + } + + class RewindSafe extends Component { + constructor(p) { super(p); this.state = { failed: false }; } + static getDerivedStateFromError() { return { failed: true }; } + componentDidCatch(error) { try { console.error("[dsh-purge] rewind slot:", error); } catch { /* ignore */ } } + render() { + if (this.state.failed) { + return h("button", { + type: "button", + className: "dshp-rewind", + title: "回退上一句", + onMouseDown: (e) => e.preventDefault(), + onClick: async () => { + const sessionId = currentSessionId(rewindSessions); + if (!sessionId) return; + try { + const data = await apiJson("/dsh-purge/rewind", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ sessionId, mode: "once" }), + }); + if (data && data.ok && data.sessionId) { + const text = isPluginDraft(data.text) ? "" : (data.text || ""); + scheduleComposerFill(data.sessionId, text); + await openRewoundSession(rewindSessions, data.sessionId); + scheduleComposerFill(data.sessionId, text); + } + } catch (e) { + window.alert("回退失败: " + String((e && e.message) || e)); + } + }, + }, h("style", null, REWIND_CSS), "回退"); + } + return h(RewindButton, this.props); + } + } + + function RewindButton(props) { + const t = props.t || translate; + const sessions = rewindSessions; + const inputActions = props.inputActions; + const sessionId = props.sessionId || currentSessionId(sessions); + const wrapRef = useRef(null); + const [busy, setBusy] = useState(false); + const [notice, setNotice] = useState(""); + const [menu, setMenu] = useState(false); + + useEffect(() => { + if (!sessionId) return; + const local = peekDraft(sessionId); + if (!local || isPluginDraft(local) || isRestored(sessionId)) return; + scheduleComposerFill(sessionId, local, inputActions); + markRestored(sessionId); + }, [sessionId, inputActions]); + + useEffect(() => { + if (!menu) return; + const onDoc = (event) => { + if (wrapRef.current && !wrapRef.current.contains(event.target)) setMenu(false); + }; + document.addEventListener("mousedown", onDoc); + return () => document.removeEventListener("mousedown", onDoc); + }, [menu]); + + const runRewind = async (mode) => { + if (!sessionId || busy) return; + setBusy(true); + setMenu(false); + setNotice(""); + try { + const data = await apiJson("/dsh-purge/rewind", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ sessionId, mode }), + }); + 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); + await openRewoundSession(sessions, data.sessionId); + scheduleComposerFill(data.sessionId, text); + } catch (e) { + setNotice(rewindText(t, "rewind.fail", "回退失败: {error}").replace("{error}", String((e && e.message) || e))); + } finally { + setBusy(false); + } + }; + + const onClick = async (event) => { + event?.preventDefault?.(); + event?.stopPropagation?.(); + if (!sessionId || busy) return; + if (menu) { + setMenu(false); + return; + } + setBusy(true); + setNotice(""); + try { + const info = await apiJson("/dsh-purge/rewind/options?sessionId=" + encodeURIComponent(sessionId)); + if (info && info.ok && info.kind === "main") { + setMenu(true); + return; + } + await runRewind("once"); + } catch (e) { + setNotice(rewindText(t, "rewind.fail", "回退失败: {error}").replace("{error}", String((e && e.message) || e))); + } finally { + setBusy(false); + } + }; + + const label = busy ? rewindText(t, "rewind.busy", "回退中…") : rewindText(t, "rewind.label", "回退"); + const title = notice || rewindText(t, "rewind.aria", "回退"); + return h("div", { className: "dshp-rewind-wrap", ref: wrapRef }, + h("style", null, REWIND_CSS), + h("button", { + type: "button", + className: "dshp-rewind", + title, + "aria-label": rewindText(t, "rewind.aria", "回退"), + disabled: busy || !sessionId, + onMouseDown: (e) => e.preventDefault(), + onClick, + }, + h("svg", { viewBox: "0 0 16 16", width: "14", height: "14", "aria-hidden": true }, + h("path", { + fill: "currentColor", + d: "M7.2 3.2 3.4 7l3.8 3.8V8.6c2.8 0 4.7.7 5.9 2.3-.2-2.8-1.9-5.2-5.9-5.6V3.2z", + }), + ), + label, + ), + menu ? h("div", { className: "dshp-rewind-menu", role: "menu" }, + h("button", { + type: "button", + className: "dshp-rewind-item", + onMouseDown: (e) => e.preventDefault(), + onClick: () => runRewind("once"), + }, + h("b", null, rewindText(t, "rewind.once", "回退一次")), + h("span", null, rewindText(t, "rewind.once.hint", "只退当前对话上一句")), + ), + h("button", { + type: "button", + className: "dshp-rewind-item", + onMouseDown: (e) => e.preventDefault(), + onClick: () => runRewind("round"), + }, + h("b", null, rewindText(t, "rewind.round", "回退上一轮")), + h("span", null, rewindText(t, "rewind.round.hint", "退回上一轮主对话,本轮子代理一并去掉")), + ), + ) : null, + ); + } + + function installRewindWatch(ctx) { + const sessions = ctx.sessions; + if (!sessions) return () => {}; + const tick = async () => { + try { + const data = await apiJson("/dsh-purge/rewind"); + if (!data || !data.sessionId || !data.at || data.at <= rewindSeenAt) return; + rewindSeenAt = data.at; + const current = currentSessionId(sessions); + if (current && current !== data.parentId) return; + const text = isPluginDraft(data.text) ? "" : (data.text || ""); + scheduleComposerFill(data.sessionId, text); + await openRewoundSession(sessions, data.sessionId); + scheduleComposerFill(data.sessionId, text); + } catch { /* ignore */ } + }; + const timer = window.setInterval(tick, 1200); + return () => window.clearInterval(timer); + } + + function installRewindUi(ctx) { + rewindHost = ctx; + rewindSessions = ctx.sessions; + ctx.slots.inject("conversation.input.right", () => ctx.slots.register({ + name: "conversation.input.right", + id: "dsh-purge-rewind", + order: 20, + inject: (sessionId) => ({ + sessionId, + t: ctx.locale.bind(NS), + }), + }, RewindSafe)); + ctx.effect(() => installRewindWatch(ctx), "dsh-purge: rewind watch"); + } + function apply(ctx) { ctx.effect(() => ctx.locale.register(NS, { zh, en }), "dsh-purge: dictionaries"); const t = ctx.locale.bind(NS); @@ -1075,6 +1463,15 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { locale: NS, inject: () => ({ t }), }, SettingsRoot)); + try { + if (typeof ctx.inject === "function") { + ctx.inject(["sessions"], (host) => installRewindUi(host)); + } else if (ctx.sessions) { + installRewindUi(ctx); + } + } catch (e) { + try { console.warn("[dsh-purge] rewind ui skipped:", e); } catch { /* ignore */ } + } } exports.name = name; diff --git a/lib/core.js b/lib/core.js index 5edc892..cd855b4 100644 --- a/lib/core.js +++ b/lib/core.js @@ -3266,10 +3266,14 @@ function patchApplied(text, patch) { return false; } -function patchHasRemainingWork(text, patch) { +function patchHasRemainingWork(text, patch, fp = "") { const hay = asLf(text); + const yaml = isYamlPath(fp); for (const { pattern, replace } of patchReplacements(patch)) { - if (pattern && typeof replace === "string" && hay.includes(asLf(pattern))) return true; + if (!pattern || typeof replace !== "string") continue; + // 与 apply 一致:YAML 里无缩进 identity 不能 replaceAll,不算待做。 + if (yaml && isBareIdentityNeedle(pattern)) continue; + if (hay.includes(asLf(pattern))) return true; } return false; } @@ -3286,13 +3290,20 @@ function isLayoutSoftPatch(patch) { return isIdentityLayoutPatch(patch) || isApprovalSentencePatch(patch); } -function filePatchSettled(text, patch) { +function filePatchSettled(text, patch, fp = "") { if (patchApplied(text, patch)) return true; // 官方副本布局不同、或审批句已被 0.1.5 改写时,没有残留 pattern 就算完成。 - if (isLayoutSoftPatch(patch)) return !patchHasRemainingWork(text, patch); + if (isLayoutSoftPatch(patch)) return !patchHasRemainingWork(text, patch, fp); return false; } +function filePatchOutcome(text, patch, fp = "") { + if (filePatchSettled(text, patch, fp)) return "applied"; + if (patchHasRemainingWork(text, patch, fp)) return "pending"; + // 原文对不上、再点应用也变不了:可选/布局软补丁显示跳过,不再假装待应用。 + return "skipped"; +} + function fileKeysOf(p) { return Array.isArray(p.file) ? p.file : [p.file]; } @@ -3444,7 +3455,7 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES) { } continue; } - if (filePatchSettled(text, p)) { + if (filePatchSettled(text, p, fp)) { if (p.id === 21 && webFetchWorkspacePaths(aiBase) && !webFetchWorkspaceLinkReady(aiBase)) { const linked = ensureWebFetchWorkspaceLink(aiBase); lastError = linked.status; @@ -3484,6 +3495,7 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) { const keys = fileKeysOf(p); let applied = 0; let pending = 0; + let skipped = 0; let missing = 0; for (const key of keys) { const fps = pathsOf(files, key); @@ -3502,12 +3514,19 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) { const runtimeReady = p.id !== 21 || !webFetchWorkspacePaths(aiBase) || webFetchWorkspaceLinkReady(aiBase); - if (filePatchSettled(text, p) && runtimeReady) applied += 1; - else pending += 1; + if (!runtimeReady) { + pending += 1; + continue; + } + const outcome = filePatchOutcome(text, p, fp); + if (outcome === "applied") applied += 1; + else if (outcome === "pending") pending += 1; + else skipped += 1; } } if (pending > 0) status[p.id] = "pending"; else if (applied > 0) status[p.id] = "applied"; + else if (skipped > 0) status[p.id] = "skipped"; else status[p.id] = "missing_file"; } return status; @@ -3984,9 +4003,11 @@ export async function gatherState() { const patch_status = aiBase ? await patchStatus(aiBase) : {}; let patches_applied = 0; let patches_pending = 0; + let patches_skipped = 0; for (const s of Object.values(patch_status)) { if (s === "applied") patches_applied += 1; if (s === "pending") patches_pending += 1; + if (s === "skipped" || s === "missing_file") patches_skipped += 1; } let shim_cmd = "missing"; let shim_ps1 = "missing"; @@ -4005,6 +4026,7 @@ export async function gatherState() { patch_status, patches_applied, patches_pending, + patches_skipped, has_backup: aiBase ? await hasBackup(aiBase) : false, shim_cmd, shim_ps1, diff --git a/lib/index.js b/lib/index.js index 5870c51..7a8932a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -10,6 +10,7 @@ import { GLOBAL_PROMPT_ORDER, rewritePromptAssembly, } from "./identity.js"; +import * as rewind from "./rewind.js"; export const name = "dsh-purge"; @@ -500,6 +501,31 @@ export function apply(ctx, config) { input: { hint: "list | use | create [别名] [目标] | delete | reset | help" }, handler: async (invocation) => handleRulesCommand(invocation.rawInput ?? ""), }); + commands.register({ + name: "rewind", + description: "回退:子代理直接回退一次;主代理 /rewind once 或 /rewind round", + input: { hint: "once | round" }, + handler: async (invocation) => { + const sessionId = rewind.invocationSessionId(invocation); + const arg = String(invocation.rawInput || "").trim().split(/\s+/)[0]?.toLowerCase() || ""; + const info = await rewind.analyzeRewind(ctx, sessionId); + if (info.ok && info.kind === "main" && arg !== "once" && arg !== "round") { + return { + kind: "success", + text: "主代理请选择:/rewind once 回退一次,/rewind round 回退上一轮(含本轮子代理)。", + }; + } + const mode = arg === "round" ? "round" : "once"; + const result = await rewind.applyRewind(ctx, sessionId, mode); + if (!result.ok) return { kind: "error", text: result.error }; + return { + kind: "success", + text: mode === "round" + ? "已回退上一轮。正在打开新的主会话,上一句已填回输入框。" + : "已回退一次。正在打开新会话,上一句已填回输入框。", + }; + }, + }); } if (ctx.tools) { @@ -681,6 +707,7 @@ function installWebServer(ctx, cfg) { ai_base: state.ai_base, patches_applied: state.patches_applied, patches_pending: state.patches_pending, + patches_skipped: state.patches_skipped || 0, patches_total: core.ALL_PATCHES.length, patch_status: state.patch_status, patch_names, @@ -699,6 +726,64 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: status"); + host.webServer.register({ + kind: "exact", + path: "/dsh-purge/rewind/options", + 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.analyzeRewind(ctx, sessionId)); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e) }); + } + }, + }, "dsh-purge: rewind options"); + host.webServer.register({ + kind: "exact", + path: "/dsh-purge/rewind", + handler: async (request, response) => { + if (request.method === "GET") { + try { + const url = new URL(request.url, "http://127.0.0.1"); + const sessionId = url.searchParams.get("sessionId"); + if (sessionId) { + const draft = rewind.takeDraft(sessionId); + sendJson(response, 200, { ok: true, ...(draft || {}) }); + return; + } + const pending = rewind.getPending(); + sendJson(response, 200, { ok: true, ...(pending || {}) }); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e) }); + } + return; + } + if (request.method === "POST") { + try { + const body = await readJsonBody(request); + const sessionId = String(body?.sessionId || "").trim(); + if (!sessionId) { + sendJson(response, 400, { ok: false, error: "需要 sessionId" }); + return; + } + const mode = body?.mode === "round" ? "round" : "once"; + const result = await rewind.applyRewind(ctx, sessionId, mode); + sendJson(response, result.ok ? 200 : 409, result); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e) }); + } + return; + } + response.writeHead(405, { allow: "GET, POST" }); + response.end(); + }, + }, "dsh-purge: rewind"); host.webServer.register({ kind: "exact", path: "/dsh-purge/update", diff --git a/lib/rewind.js b/lib/rewind.js new file mode 100644 index 0000000..b656e63 --- /dev/null +++ b/lib/rewind.js @@ -0,0 +1,436 @@ +const DRAFT_TTL_MS = 10 * 60 * 1000; +const pendingDrafts = new Map(); +let lastPending = null; + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function errorText(err) { + if (!err) return "回退失败"; + if (typeof err === "string") return err; + return err.message || err.code || String(err); +} + +function service(ctx, name) { + if (!ctx || typeof ctx.get !== "function") return undefined; + try { + return ctx.get(name); + } catch { + return undefined; + } +} + +function userTextFromEvent(event) { + const data = event?.data; + const content = data?.content ?? data?.message?.content; + if (typeof content === "string") return content.trim(); + if (!Array.isArray(content)) return ""; + const parts = []; + for (const block of content) { + if (!block) continue; + if (typeof block === "string") { + parts.push(block); + continue; + } + if (block.type === "text" || typeof block.text === "string") { + parts.push(String(block.text ?? "")); + } + } + return parts.join("").trim(); +} + +function isPluginDraft(text) { + const value = String(text || "").trim(); + if (!value) return false; + return /^\[MNEMON\]/i.test(value) + || /MNEMON RUNTIME MEMORY SNAPSHOT/i.test(value) + || /^MNEMON VIEW TOOLS/im.test(value); +} + +function isHumanUserEvent(event) { + if (event?.type !== "user/message") return false; + const source = event.data?.source; + if (source?.kind === "plugin") return false; + if (source?.kind && source.kind !== "user") return false; + const text = userTextFromEvent(event); + if (!text || isPluginDraft(text)) return false; + return true; +} + +function lastOpenTurn(events) { + for (let i = events.length - 1; i >= 0; i -= 1) { + const type = events[i]?.type; + if (type === "turn/start") return events[i]; + if (type === "turn/end") return null; + } + return null; +} + +function isSubagentHeader(header) { + if (!header) return false; + return header.origin === "subagent" || (header.delegationDepth ?? 0) > 0; +} + +export function climbToMain(startId, getHeader) { + let currentId = startId; + const seen = new Set(); + while (currentId && !seen.has(currentId)) { + seen.add(currentId); + const header = getHeader(currentId); + if (!isSubagentHeader(header) || !header?.parentSession) { + return currentId; + } + currentId = header.parentSession; + } + return startId; +} + +export function pendingInboxInserts(events) { + const list = Array.isArray(events) ? events : []; + let lastEnd = -1; + let lastStart = -1; + for (const event of list) { + if (event?.type === "turn/end") lastEnd = event.seq; + if (event?.type === "turn/start") lastStart = event.seq; + } + const after = lastEnd >= 0 ? lastEnd : -1; + const ids = []; + const seen = new Set(); + for (const event of list) { + if (!event || event.seq <= after) continue; + if (lastStart > after && event.seq >= lastStart) continue; + if (event.type !== "agent/inbox/spliced") continue; + if (event.data?.target && event.data.target !== "next-turn") continue; + for (const message of event.data?.inserted || []) { + const id = message?.id; + if (!id || seen.has(id)) continue; + seen.add(id); + ids.push(id); + } + } + return ids; +} + +export function lastTurnSubagentIds(events) { + const list = Array.isArray(events) ? events : []; + let lastStart = -1; + for (let i = list.length - 1; i >= 0; i -= 1) { + if (list[i]?.type === "turn/start") { + lastStart = list[i].seq; + break; + } + } + if (lastStart < 0) return []; + const ids = []; + const seen = new Set(); + for (const event of list) { + if (!event || event.seq < lastStart) continue; + if (event.type !== "subagent/catalog" && event.type !== "subagent/descriptor") continue; + const id = event.data?.childId || event.data?.sessionId || event.data?.id; + if (!id || seen.has(id)) continue; + seen.add(id); + ids.push(id); + } + return ids; +} + +export function planRewind(events) { + const list = Array.isArray(events) ? events : []; + const turnEnds = list.filter((event) => event?.type === "turn/end"); + const turnStarts = list.filter((event) => event?.type === "turn/start"); + const lastStart = turnStarts[turnStarts.length - 1]; + const usersInLastTurn = lastStart + ? list.filter((event) => isHumanUserEvent(event) && event.seq >= lastStart.seq) + : []; + const lastUser = usersInLastTurn[0] + || list.filter(isHumanUserEvent).at(-1); + if (!lastUser) { + return { ok: false, error: "没有可回退的上一句" }; + } + const text = userTextFromEvent(lastUser); + if (turnEnds.length >= 2) { + return { + ok: true, + mode: "fork", + atSeq: turnEnds[turnEnds.length - 2].seq, + text, + }; + } + return { ok: true, mode: "blank", text }; +} + +function rememberDraft(sessionId, text, parentId) { + const rec = { + sessionId, + parentId, + text: text || "", + at: Date.now(), + }; + pendingDrafts.set(sessionId, rec); + lastPending = rec; + const now = Date.now(); + for (const [id, row] of pendingDrafts) { + if (now - row.at > DRAFT_TTL_MS) pendingDrafts.delete(id); + } + return rec; +} + +export function getDraft(sessionId) { + if (!sessionId) return null; + const rec = pendingDrafts.get(sessionId); + if (!rec) return null; + if (Date.now() - rec.at > DRAFT_TTL_MS) { + pendingDrafts.delete(sessionId); + return null; + } + return rec; +} + +export function takeDraft(sessionId) { + const rec = getDraft(sessionId); + if (rec) pendingDrafts.delete(sessionId); + return rec; +} + +export function getPending() { + if (!lastPending) return null; + if (Date.now() - lastPending.at > DRAFT_TTL_MS) { + lastPending = null; + return null; + } + return lastPending; +} + +function disposeObservation(observed) { + try { + observed?.[Symbol.dispose]?.(); + } catch { + /* ignore */ + } +} + +async function readSessionLog(ctx, sessionId) { + const store = service(ctx, "sessions"); + const live = store?.get?.(sessionId); + if (live?.snapshotEvents) { + return { + events: live.snapshotEvents(), + header: live.header, + cwd: live.header?.cwd, + }; + } + + const controller = service(ctx, "sessionController"); + if (typeof controller?.inspect === "function") { + const inspected = await controller.inspect(sessionId); + return { + events: inspected.events || [], + header: inspected.meta || inspected.header, + cwd: inspected.meta?.cwd || inspected.header?.cwd, + }; + } + + const query = service(ctx, "sessionQuery"); + if (typeof query?.observeSession === "function") { + const observed = await query.observeSession(sessionId, { projectionMode: "none" }); + try { + return { + events: observed.events || [], + header: observed.header, + cwd: observed.header?.cwd, + }; + } finally { + disposeObservation(observed); + } + } + + throw new Error("找不到当前会话"); +} + +function findWorkspace(ctx, sessionId, cwd) { + const registry = service(ctx, "workspaceRegistry"); + const list = registry?.list?.() || []; + return list.find((workspace) => (workspace?.sessionIds || []).includes(sessionId)) + || (cwd ? list.find((workspace) => workspace?.path === cwd) : undefined); +} + +async function waitTurnClosed(ctx, sessionId, timeoutMs = 8000) { + const started = Date.now(); + let last = await readSessionLog(ctx, sessionId); + while (lastOpenTurn(last.events)) { + if (Date.now() - started >= timeoutMs) { + throw new Error("回合还在进行,请先点停止再回退"); + } + await sleep(80); + last = await readSessionLog(ctx, sessionId); + } + return last; +} + +function getAgent(ctx, sessionId) { + const agents = service(ctx, "agents"); + try { + return agents?.get?.(sessionId) || agents?.agent?.(sessionId) || undefined; + } catch { + return undefined; + } +} + +async function disarmRewoundSession(ctx, sessionId) { + if (!sessionId) return; + const controller = service(ctx, "sessionController"); + const disarmOnce = async () => { + const agent = getAgent(ctx, sessionId); + try { agent?.inbox?.clear?.(); } catch { /* ignore */ } + try { agent?.cancel?.({ kind: "user" }, { keepInbox: false }); } catch { /* ignore */ } + + const ids = []; + try { + const log = await readSessionLog(ctx, sessionId); + ids.push(...pendingInboxInserts(log.events)); + } catch { /* ignore */ } + try { + for (const message of [...(agent?.inbox?.nextTurn || []), ...(agent?.inbox?.nextStep || [])]) { + if (message?.id) ids.push(message.id); + } + } catch { /* ignore */ } + + const seen = new Set(); + for (const id of ids) { + if (!id || seen.has(id)) continue; + seen.add(id); + try { + controller?.updateQueue?.({ + sessionId, + itemId: id, + action: { kind: "remove" }, + }); + } catch { /* ignore */ } + } + + try { agent?.inbox?.clear?.(); } catch { /* ignore */ } + if (agent?.status === "running") { + try { agent.cancel({ kind: "user" }, { keepInbox: false }); } catch { /* ignore */ } + } + }; + + await disarmOnce(); + await sleep(20); + await disarmOnce(); + try { + const idle = getAgent(ctx, sessionId)?.whenIdle?.(); + if (idle && typeof idle.then === "function") { + await Promise.race([idle, sleep(800)]); + } + } catch { /* ignore */ } + await disarmOnce(); +} + +async function createBlank(ctx, controller, sourceId, cwd) { + const workspace = findWorkspace(ctx, sourceId, cwd); + if (workspace?.id) { + return controller.create({ workspaceId: workspace.id }); + } + if (cwd) return controller.create({ cwd }); + return controller.create({}); +} + +export function invocationSessionId(invocation) { + return invocation?.agent?.session?.id + || invocation?.agent?.sessionId + || invocation?.agent?.session?.header?.id; +} + +async function resolveMainSession(ctx, sessionId) { + const headers = new Map(); + let currentId = sessionId; + const seen = new Set(); + while (currentId && !seen.has(currentId)) { + seen.add(currentId); + const log = await readSessionLog(ctx, currentId); + const header = log.header || {}; + headers.set(currentId, header); + if (!isSubagentHeader(header) || !header.parentSession) { + return { sessionId: currentId, log }; + } + currentId = header.parentSession; + } + return { sessionId, log: await readSessionLog(ctx, sessionId) }; +} + +async function rewindOneSession(ctx, controller, sessionId) { + let log = await readSessionLog(ctx, sessionId); + if (lastOpenTurn(log.events)) { + try { controller.cancel?.({ sessionId }); } catch { /* ignore */ } + log = await waitTurnClosed(ctx, sessionId); + } + const plan = planRewind(log.events); + if (!plan.ok) return plan; + + let created; + if (plan.mode === "fork") { + created = await controller.fork({ sessionId, atSeq: plan.atSeq }); + } else { + created = await createBlank(ctx, controller, sessionId, log.cwd); + } + const childId = created?.sessionId || (typeof created === "string" ? created : ""); + if (!childId) return { ok: false, error: "回退会话创建失败" }; + + await disarmRewoundSession(ctx, childId); + + const rec = rememberDraft(childId, plan.text, sessionId); + return { + ok: true, + sessionId: childId, + parentId: sessionId, + text: rec.text, + cut: plan.mode, + at: rec.at, + }; +} + +export async function analyzeRewind(ctx, sessionId) { + if (!sessionId) return { ok: false, error: "没有当前会话" }; + try { + const log = await readSessionLog(ctx, sessionId); + const kind = isSubagentHeader(log.header) ? "subagent" : "main"; + const subagentIds = kind === "main" ? lastTurnSubagentIds(log.events) : []; + return { + ok: true, + kind, + sessionId, + hasSubagents: subagentIds.length > 0, + subagentIds, + }; + } catch (err) { + return { ok: false, error: errorText(err) }; + } +} + +export async function applyRewind(ctx, sessionId, mode) { + if (!sessionId) return { ok: false, error: "没有当前会话" }; + const controller = service(ctx, "sessionController"); + if (!controller || typeof controller.fork !== "function" || typeof controller.create !== "function") { + return { ok: false, error: "当前 dsh 没有会话回退接口" }; + } + + const action = mode === "round" ? "round" : "once"; + try { + if (action === "round") { + const target = await resolveMainSession(ctx, sessionId); + if (sessionId !== target.sessionId) { + try { controller.cancel?.({ sessionId }); } catch { /* ignore */ } + } + const result = await rewindOneSession(ctx, controller, target.sessionId); + if (!result.ok) return result; + return { ...result, sourceId: sessionId, mode: "round" }; + } + + const result = await rewindOneSession(ctx, controller, sessionId); + if (!result.ok) return result; + return { ...result, sourceId: sessionId, mode: "once" }; + } catch (err) { + return { ok: false, error: errorText(err) }; + } +} diff --git a/package.json b/package.json index 759de23..07c7c07 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.0", + "version": "1.1.1", "description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐", "type": "module", "main": "lib/index.js", @@ -56,6 +56,7 @@ "@deepseek-ai/dsh-client-connection", "@deepseek-ai/dsh-client-runtime", "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-slots", "@deepseek-ai/dsh-client-ui-settings" ] }