feat: 发布 1.1.1,回退上一句并清掉待发送队列

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-09-18 00:27:33 +08:00
1 parent 25e415ca7c
commit 3f5c0c8281
7 files changed
+986 -25

No files matched your search

+29 -7
View File
@@ -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,
+85
View File
@@ -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 <id> | create <id> [别名] [目标] | delete <id> | 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",
+436
View File
@@ -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) };
}
}