mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 10:50:22 +08:00
feat: 发布 1.1.8,默认提示词内置进插件,源 md 不进仓库
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
30bdb49958
commit
6432288056
11 files changed
+994
-58
No files matched your search
@@ -0,0 +1,386 @@
|
||||
import { promises as fsp } from "node:fs";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export const DEFAULT_CONTINUE_RETRY = Object.freeze({
|
||||
autoRetry: true,
|
||||
retryMax: 3,
|
||||
autoContinue: true,
|
||||
continueMax: 3,
|
||||
continueText: "继续",
|
||||
});
|
||||
|
||||
const PERMANENT_CODES = new Set([
|
||||
"AUTH",
|
||||
"UNAUTHORIZED",
|
||||
"FORBIDDEN",
|
||||
"INVALID",
|
||||
"INVALID_REQUEST",
|
||||
"QUOTA",
|
||||
"BILLING",
|
||||
"MODEL_NOT_FOUND",
|
||||
"CONTEXT_OVERFLOW",
|
||||
"CONTEXT_LENGTH",
|
||||
]);
|
||||
|
||||
const ABNORMAL_KINDS = new Set(["error", "aborted", "interrupted", "max-tokens"]);
|
||||
|
||||
export function clampCount(value, fallback = 3) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.max(0, Math.min(20, Math.trunc(n)));
|
||||
}
|
||||
|
||||
export function normalizeConfig(raw = {}) {
|
||||
const src = raw && typeof raw === "object" ? raw : {};
|
||||
const retryMax = clampCount(src.retryMax, DEFAULT_CONTINUE_RETRY.retryMax);
|
||||
const continueMax = clampCount(src.continueMax, DEFAULT_CONTINUE_RETRY.continueMax);
|
||||
const text = typeof src.continueText === "string" ? src.continueText.trim() : "";
|
||||
return {
|
||||
autoRetry: src.autoRetry !== false && retryMax > 0,
|
||||
retryMax,
|
||||
autoContinue: src.autoContinue !== false && continueMax > 0,
|
||||
continueMax,
|
||||
continueText: text || DEFAULT_CONTINUE_RETRY.continueText,
|
||||
};
|
||||
}
|
||||
|
||||
export function settingsPath(dshHome) {
|
||||
return path.join(dshHome, "dsh-purge", "continue-retry.json");
|
||||
}
|
||||
|
||||
export function loadSettings(dshHome) {
|
||||
const fp = settingsPath(dshHome);
|
||||
try {
|
||||
if (!fs.existsSync(fp)) return {};
|
||||
const parsed = JSON.parse(fs.readFileSync(fp, "utf8"));
|
||||
return parsed && typeof parsed === "object" ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveSettings(dshHome, raw) {
|
||||
const next = normalizeConfig(raw);
|
||||
const dir = path.dirname(settingsPath(dshHome));
|
||||
await fsp.mkdir(dir, { recursive: true });
|
||||
await fsp.writeFile(settingsPath(dshHome), `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
||||
return next;
|
||||
}
|
||||
|
||||
export function mergeConfig(pluginCfg, saved) {
|
||||
return normalizeConfig({ ...DEFAULT_CONTINUE_RETRY, ...pluginCfg, ...saved });
|
||||
}
|
||||
|
||||
export function lastTurnEnd(events) {
|
||||
const list = Array.isArray(events) ? events : [];
|
||||
for (let i = list.length - 1; i >= 0; i -= 1) {
|
||||
const event = list[i];
|
||||
if (event?.type === "turn/end") return event;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isUserAbort(reason) {
|
||||
if (!reason || reason.kind !== "aborted") return false;
|
||||
const cause = reason.reason;
|
||||
if (cause === "user" || cause === "cancel") return true;
|
||||
if (cause && typeof cause === "object") {
|
||||
return cause.kind === "user" || cause.kind === "cancel";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isAbnormalReason(reason) {
|
||||
return Boolean(reason && ABNORMAL_KINDS.has(reason.kind));
|
||||
}
|
||||
|
||||
export function shouldAutoContinue(reason) {
|
||||
return isAbnormalReason(reason) && !isUserAbort(reason);
|
||||
}
|
||||
|
||||
export function isPermanentFailure(code) {
|
||||
return PERMANENT_CODES.has(String(code || "").toUpperCase());
|
||||
}
|
||||
|
||||
export function shouldAutoRetry(failure, signal) {
|
||||
if (signal?.aborted) return false;
|
||||
return !isPermanentFailure(failure?.code);
|
||||
}
|
||||
|
||||
export function makeContinueMessage(text) {
|
||||
const body = String(text || DEFAULT_CONTINUE_RETRY.continueText).trim() || DEFAULT_CONTINUE_RETRY.continueText;
|
||||
return {
|
||||
id: `dsh-purge-continue-${randomUUID()}`,
|
||||
role: "user",
|
||||
content: [{ type: "text", text: body }],
|
||||
source: {
|
||||
kind: "plugin",
|
||||
plugin: "dsh-purge",
|
||||
form: "notice",
|
||||
summary: "continue",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createTracker() {
|
||||
const bySession = new Map();
|
||||
|
||||
function slot(sessionId) {
|
||||
const id = String(sessionId || "");
|
||||
if (!id) return null;
|
||||
let cur = bySession.get(id);
|
||||
if (!cur) {
|
||||
cur = { retry: 0, continue: 0, lastContinueSeq: 0, lastRetryKey: "" };
|
||||
bySession.set(id, cur);
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
return {
|
||||
retryUsed(sessionId) {
|
||||
return slot(sessionId)?.retry || 0;
|
||||
},
|
||||
continueUsed(sessionId) {
|
||||
return slot(sessionId)?.continue || 0;
|
||||
},
|
||||
lastContinueSeq(sessionId) {
|
||||
return slot(sessionId)?.lastContinueSeq || 0;
|
||||
},
|
||||
takeRetry(sessionId, key, max) {
|
||||
const cur = slot(sessionId);
|
||||
if (!cur || max <= 0) return false;
|
||||
if (key && cur.lastRetryKey === key) return false;
|
||||
if (cur.retry >= max) return false;
|
||||
cur.retry += 1;
|
||||
cur.lastRetryKey = key || "";
|
||||
return true;
|
||||
},
|
||||
takeContinue(sessionId, seq, max) {
|
||||
const cur = slot(sessionId);
|
||||
if (!cur || max <= 0) return false;
|
||||
if (seq && cur.lastContinueSeq === seq) return false;
|
||||
if (cur.continue >= max) return false;
|
||||
cur.continue += 1;
|
||||
cur.lastContinueSeq = seq || 0;
|
||||
return true;
|
||||
},
|
||||
refundContinue(sessionId) {
|
||||
const cur = slot(sessionId);
|
||||
if (!cur || cur.continue <= 0) return;
|
||||
cur.continue -= 1;
|
||||
cur.lastContinueSeq = 0;
|
||||
},
|
||||
reset(sessionId) {
|
||||
const id = String(sessionId || "");
|
||||
if (id) bySession.delete(id);
|
||||
},
|
||||
resetIfCompleted(sessionId, reason) {
|
||||
if (reason?.kind === "completed" || reason?.kind === "blocked") this.reset(sessionId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function service(ctx, name) {
|
||||
if (!ctx || typeof ctx.get !== "function") return undefined;
|
||||
try {
|
||||
return ctx.get(name);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function sessionEventsOf(agent) {
|
||||
const session = agent?.session;
|
||||
if (!session) return [];
|
||||
try {
|
||||
if (typeof session.snapshotEvents === "function") return session.snapshotEvents() || [];
|
||||
} catch { /* ignore */ }
|
||||
try {
|
||||
if (Array.isArray(session.events)) return session.events;
|
||||
} catch { /* ignore */ }
|
||||
return [];
|
||||
}
|
||||
|
||||
export function inspectTurn(events) {
|
||||
const end = lastTurnEnd(events);
|
||||
const reason = end?.data?.reason || null;
|
||||
return {
|
||||
seq: end?.seq || 0,
|
||||
turn: end?.data?.turn || 0,
|
||||
reason,
|
||||
abnormal: isAbnormalReason(reason),
|
||||
userAbort: isUserAbort(reason),
|
||||
auto: shouldAutoContinue(reason),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAgent(ctx, sessionId) {
|
||||
const agents = service(ctx, "agents");
|
||||
if (!agents || typeof agents.get !== "function") return null;
|
||||
try {
|
||||
return agents.get(sessionId) || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function hasFreshHumanTurn(events) {
|
||||
const list = Array.isArray(events) ? events : [];
|
||||
const end = lastTurnEnd(list);
|
||||
const after = end ? list.filter((event) => (event?.seq || 0) > end.seq) : list;
|
||||
return after.some((event) => {
|
||||
if (event?.type !== "user/message") return false;
|
||||
return event.data?.source?.kind !== "plugin";
|
||||
});
|
||||
}
|
||||
|
||||
export function inboxBusy(agent) {
|
||||
try {
|
||||
const inbox = agent?.inbox;
|
||||
if (!inbox) return false;
|
||||
if (typeof inbox.hasPending === "function" && inbox.hasPending()) return true;
|
||||
if (typeof inbox.size === "number" && inbox.size > 0) return true;
|
||||
if (typeof inbox.length === "number" && inbox.length > 0) return true;
|
||||
} catch { /* ignore */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
export function sendContinue(agent, text) {
|
||||
if (!agent || typeof agent.followup !== "function") {
|
||||
return { ok: false, error: "当前会话没有可续跑的 agent" };
|
||||
}
|
||||
try {
|
||||
agent.followup(makeContinueMessage(text));
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e) };
|
||||
}
|
||||
}
|
||||
|
||||
export function installContinueRetry(ctx, options = {}) {
|
||||
const getConfig = typeof options.getConfig === "function" ? options.getConfig : () => normalizeConfig(options.config);
|
||||
const tracker = options.tracker || createTracker();
|
||||
const timers = new Set();
|
||||
|
||||
function sessionIdOf(agent) {
|
||||
return agent?.id || agent?.session?.id || "";
|
||||
}
|
||||
|
||||
function schedule(fn, ms) {
|
||||
const timer = setTimeout(() => {
|
||||
timers.delete(timer);
|
||||
fn();
|
||||
}, ms);
|
||||
timers.add(timer);
|
||||
return timer;
|
||||
}
|
||||
|
||||
function listen(event, handler) {
|
||||
if (typeof ctx?.on !== "function") return null;
|
||||
try {
|
||||
return ctx.on(event, handler, { global: true });
|
||||
} catch {
|
||||
try {
|
||||
return ctx.on(event, handler);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function maybeAutoContinue(agent) {
|
||||
const cfg = getConfig();
|
||||
if (!cfg.autoContinue) return;
|
||||
const id = sessionIdOf(agent);
|
||||
if (!id) return;
|
||||
if (agent.status === "running" || inboxBusy(agent)) return;
|
||||
const events = sessionEventsOf(agent);
|
||||
if (hasFreshHumanTurn(events)) return;
|
||||
const info = inspectTurn(events);
|
||||
if (!info.auto) return;
|
||||
if (!tracker.takeContinue(id, info.seq, cfg.continueMax)) return;
|
||||
const sent = sendContinue(agent, cfg.continueText);
|
||||
if (!sent.ok) tracker.refundContinue(id);
|
||||
}
|
||||
|
||||
const offError = listen("agent/request-error", async (payload, next) => {
|
||||
const downstream = typeof next === "function" ? await next() : undefined;
|
||||
if (downstream?.kind === "retry") return downstream;
|
||||
const cfg = getConfig();
|
||||
if (!cfg.autoRetry) return downstream;
|
||||
if (!shouldAutoRetry(payload?.failure, payload?.signal)) return downstream;
|
||||
const id = sessionIdOf(payload?.agent);
|
||||
const key = `${payload?.turn || 0}:${payload?.step || 0}:${payload?.failure?.code || ""}`;
|
||||
if (!tracker.takeRetry(id, key, cfg.retryMax)) return downstream;
|
||||
return { kind: "retry" };
|
||||
});
|
||||
|
||||
const offStatus = listen("agent/status", (payload) => {
|
||||
const agent = payload?.agent;
|
||||
if (!agent) return;
|
||||
const id = sessionIdOf(agent);
|
||||
const events = sessionEventsOf(agent);
|
||||
if (payload.status === "running" && hasFreshHumanTurn(events)) tracker.reset(id);
|
||||
if (payload.status !== "idle") return;
|
||||
tracker.resetIfCompleted(id, inspectTurn(events).reason);
|
||||
schedule(() => maybeAutoContinue(agent), 280);
|
||||
});
|
||||
|
||||
return {
|
||||
tracker,
|
||||
inspect(agentOrEvents) {
|
||||
const events = Array.isArray(agentOrEvents) ? agentOrEvents : sessionEventsOf(agentOrEvents);
|
||||
return inspectTurn(events);
|
||||
},
|
||||
continueNow(agent, opts = {}) {
|
||||
const cfg = getConfig();
|
||||
const id = sessionIdOf(agent);
|
||||
const info = inspectTurn(sessionEventsOf(agent));
|
||||
if (!info.abnormal && !opts.force) return { ok: false, error: "当前不是中断或失败状态" };
|
||||
const max = opts.ignoreBudget ? Number.MAX_SAFE_INTEGER : cfg.continueMax;
|
||||
if (info.seq && tracker.lastContinueSeq(id) === info.seq) {
|
||||
return { ok: false, error: "这一轮已经在继续" };
|
||||
}
|
||||
if (!tracker.takeContinue(id, info.seq, max)) {
|
||||
return { ok: false, error: `继续次数已用完(${cfg.continueMax})` };
|
||||
}
|
||||
const sent = sendContinue(agent, opts.text || cfg.continueText);
|
||||
if (!sent.ok) {
|
||||
tracker.refundContinue(id);
|
||||
return sent;
|
||||
}
|
||||
return { ok: true, used: tracker.continueUsed(id), max: cfg.continueMax, reason: info.reason?.kind || "" };
|
||||
},
|
||||
status(agent) {
|
||||
const cfg = getConfig();
|
||||
const id = sessionIdOf(agent);
|
||||
const info = inspectTurn(sessionEventsOf(agent));
|
||||
return {
|
||||
ok: true,
|
||||
sessionId: id,
|
||||
canContinue: Boolean(
|
||||
info.abnormal
|
||||
&& tracker.continueUsed(id) < cfg.continueMax
|
||||
&& tracker.lastContinueSeq(id) !== info.seq
|
||||
),
|
||||
reason: info.reason?.kind || "",
|
||||
userAbort: info.userAbort,
|
||||
retryUsed: tracker.retryUsed(id),
|
||||
continueUsed: tracker.continueUsed(id),
|
||||
retryMax: cfg.retryMax,
|
||||
continueMax: cfg.continueMax,
|
||||
autoRetry: cfg.autoRetry,
|
||||
autoContinue: cfg.autoContinue,
|
||||
continueText: cfg.continueText,
|
||||
};
|
||||
},
|
||||
dispose() {
|
||||
for (const timer of timers) clearTimeout(timer);
|
||||
timers.clear();
|
||||
try { offError?.(); } catch { /* ignore */ }
|
||||
try { offStatus?.(); } catch { /* ignore */ }
|
||||
},
|
||||
};
|
||||
}
|
||||
+115
-12
@@ -13,6 +13,7 @@ import {
|
||||
revertHideConsoleFromBin,
|
||||
} from "./hide-console.js";
|
||||
import * as desktop from "./desktop.js";
|
||||
import { defaultPromptInjectText } from "./default-prompt-data.js";
|
||||
import { adapterFor, detectSurface } from "./surface.js";
|
||||
|
||||
const isWindows = process.platform === "win32";
|
||||
@@ -4217,41 +4218,143 @@ const DEFAULT_OVERRIDE_FILE = path.join(
|
||||
"default-prompt-inject.md",
|
||||
);
|
||||
|
||||
export function normalizeOverride(text) {
|
||||
return String(text ?? "").replace(/\r\n/g, "\n").trim();
|
||||
}
|
||||
|
||||
export function hashOverride(text) {
|
||||
return createHash("sha256").update(normalizeOverride(text), "utf8").digest("hex");
|
||||
}
|
||||
|
||||
export function defaultOverrideText() {
|
||||
return fs.readFileSync(DEFAULT_OVERRIDE_FILE, "utf8");
|
||||
try {
|
||||
if (fs.existsSync(DEFAULT_OVERRIDE_FILE)) {
|
||||
return fs.readFileSync(DEFAULT_OVERRIDE_FILE, "utf8");
|
||||
}
|
||||
} catch {
|
||||
/* use embedded seed */
|
||||
}
|
||||
return defaultPromptInjectText();
|
||||
}
|
||||
|
||||
export function defaultOverrideHash() {
|
||||
return hashOverride(defaultOverrideText());
|
||||
}
|
||||
|
||||
export const OVERRIDE_TEXT = defaultOverrideText();
|
||||
|
||||
export function overrideStatePath(dshHome) {
|
||||
return path.join(dshHome, "dsh-purge", "override-state.json");
|
||||
}
|
||||
|
||||
export async function readOverrideState(dshHome) {
|
||||
const fp = overrideStatePath(dshHome);
|
||||
try {
|
||||
const raw = JSON.parse(await fsp.readFile(fp, "utf8"));
|
||||
return raw && typeof raw === "object" ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeOverrideState(dshHome, state) {
|
||||
const fp = overrideStatePath(dshHome);
|
||||
await fsp.mkdir(path.dirname(fp), { recursive: true });
|
||||
await fsp.writeFile(fp, `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
export async function markOverrideCustomized(dshHome, customized, text) {
|
||||
await writeOverrideState(dshHome, {
|
||||
customized: Boolean(customized),
|
||||
hash: hashOverride(text ?? defaultOverrideText()),
|
||||
seedHash: defaultOverrideHash(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function isUserCustomizedOverride(dshHome) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
let disk = "";
|
||||
if (fs.existsSync(fp)) {
|
||||
try {
|
||||
disk = await loadText(fp);
|
||||
} catch {
|
||||
disk = "";
|
||||
}
|
||||
}
|
||||
if (!normalizeOverride(disk)) return false;
|
||||
if (hashOverride(disk) === defaultOverrideHash()) return false;
|
||||
const state = await readOverrideState(dshHome);
|
||||
if (state.customized === false) return false;
|
||||
if (state.customized === true) return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function overrideStatus(dshHome) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
if (!fs.existsSync(fp)) return "missing";
|
||||
try {
|
||||
const content = await loadText(fp);
|
||||
if (content.trim().length === 0) return "empty";
|
||||
return "edited";
|
||||
if (!normalizeOverride(content)) return "empty";
|
||||
if (await isUserCustomizedOverride(dshHome)) return "edited";
|
||||
return "default";
|
||||
} catch {
|
||||
return "missing";
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置页:未自行改过就显示并维持内置默认提示词。 */
|
||||
export async function readOverrideForUi(dshHome) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
const defaultContent = defaultOverrideText();
|
||||
const exists = fs.existsSync(fp);
|
||||
let disk = "";
|
||||
if (exists) {
|
||||
try {
|
||||
disk = await loadText(fp);
|
||||
} catch {
|
||||
disk = "";
|
||||
}
|
||||
}
|
||||
const customized = await isUserCustomizedOverride(dshHome);
|
||||
return {
|
||||
path: fp,
|
||||
exists,
|
||||
empty: !normalizeOverride(disk),
|
||||
customized,
|
||||
usingDefault: !customized,
|
||||
content: customized ? disk : defaultContent,
|
||||
defaultContent,
|
||||
};
|
||||
}
|
||||
|
||||
export async function installOverride(dshHome, force = false) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
await fsp.mkdir(dshHome, { recursive: true });
|
||||
if (fs.existsSync(fp) && !force) {
|
||||
const existing = await loadText(fp);
|
||||
// 空文件就是空:不注入、不改写。
|
||||
return existing.trim().length > 0 ? "exists" : "empty";
|
||||
}
|
||||
await fsp.writeFile(fp, defaultOverrideText(), "utf8");
|
||||
if (!force && await isUserCustomizedOverride(dshHome)) return "exists";
|
||||
const bundled = defaultOverrideText();
|
||||
await fsp.writeFile(fp, bundled, "utf8");
|
||||
await markOverrideCustomized(dshHome, false, bundled);
|
||||
return "wrote";
|
||||
}
|
||||
|
||||
export async function saveOverrideContent(dshHome, content) {
|
||||
const bundled = defaultOverrideText();
|
||||
const incoming = typeof content === "string" ? content : "";
|
||||
const customized = Boolean(normalizeOverride(incoming))
|
||||
&& normalizeOverride(incoming) !== normalizeOverride(bundled);
|
||||
const toWrite = customized ? incoming : bundled;
|
||||
const fp = findOverrideFile(dshHome);
|
||||
await fsp.mkdir(dshHome, { recursive: true });
|
||||
await fsp.writeFile(fp, toWrite, "utf8");
|
||||
await markOverrideCustomized(dshHome, customized, toWrite);
|
||||
return { path: fp, customized, content: toWrite };
|
||||
}
|
||||
|
||||
export async function ensureOverrideContent(dshHome, force = false) {
|
||||
const installed = await installOverride(dshHome, force);
|
||||
const fp = findOverrideFile(dshHome);
|
||||
const content = fs.existsSync(fp) ? await loadText(fp) : "";
|
||||
return { path: fp, content, installed };
|
||||
const ui = await readOverrideForUi(dshHome);
|
||||
return { ...ui, installed };
|
||||
}
|
||||
|
||||
export function editOverride(dshHome) {
|
||||
|
||||
+123
-10
@@ -12,6 +12,7 @@ import {
|
||||
shouldInjectPrompt,
|
||||
} from "./identity.js";
|
||||
import * as rewind from "./rewind.js";
|
||||
import * as continueRetry from "./continue-retry.js";
|
||||
import * as uninstaller from "./uninstall.js";
|
||||
|
||||
export const name = "dsh-purge";
|
||||
@@ -28,6 +29,11 @@ const DEFAULTS = {
|
||||
postPrompt: "",
|
||||
postPromptOrder: 5100,
|
||||
verbose: false,
|
||||
autoRetry: true,
|
||||
retryMax: 3,
|
||||
autoContinue: true,
|
||||
continueMax: 3,
|
||||
continueText: "继续",
|
||||
};
|
||||
|
||||
const log = (config, ...args) => {
|
||||
@@ -35,6 +41,33 @@ const log = (config, ...args) => {
|
||||
};
|
||||
|
||||
let webTreeReady = false;
|
||||
let continueRuntime = null;
|
||||
let savedContinueSettings = {};
|
||||
let continuePluginCfg = { ...DEFAULTS };
|
||||
|
||||
function currentContinueConfig() {
|
||||
return continueRetry.mergeConfig(continuePluginCfg, savedContinueSettings);
|
||||
}
|
||||
|
||||
function continueStatusPayload(ctx, sessionId) {
|
||||
const cfg = currentContinueConfig();
|
||||
const agent = sessionId ? continueRetry.resolveAgent(ctx, sessionId) : null;
|
||||
if (agent && continueRuntime) return continueRuntime.status(agent);
|
||||
return {
|
||||
ok: true,
|
||||
sessionId: sessionId || "",
|
||||
canContinue: false,
|
||||
reason: "",
|
||||
userAbort: false,
|
||||
retryUsed: 0,
|
||||
continueUsed: 0,
|
||||
retryMax: cfg.retryMax,
|
||||
continueMax: cfg.continueMax,
|
||||
autoRetry: cfg.autoRetry,
|
||||
autoContinue: cfg.autoContinue,
|
||||
continueText: cfg.continueText,
|
||||
};
|
||||
}
|
||||
|
||||
function watchWebTreeReady(ctx) {
|
||||
// 必须挂在 connection 上再 await,与官方打印 URL 同一时刻。
|
||||
@@ -531,6 +564,12 @@ export function apply(ctx, config) {
|
||||
const injectFile = core.findOverrideFile(core.findDshHome());
|
||||
registerPromptSections(ctx, cfg, injectFile);
|
||||
|
||||
// 继续/重试先关掉,需要时再打开下面这段。
|
||||
// continuePluginCfg = cfg;
|
||||
// savedContinueSettings = continueRetry.loadSettings(core.findDshHome());
|
||||
// try { continueRuntime?.dispose?.(); } catch { /* ignore */ }
|
||||
// continueRuntime = continueRetry.installContinueRetry(ctx, { getConfig: currentContinueConfig });
|
||||
|
||||
const commands = ctx.get?.("commands");
|
||||
if (commands) {
|
||||
commands.register({
|
||||
@@ -570,6 +609,19 @@ export function apply(ctx, config) {
|
||||
};
|
||||
},
|
||||
});
|
||||
// commands.register({
|
||||
// name: "continue",
|
||||
// description: "异常停止或中断后发送继续(计入继续次数)",
|
||||
// input: { hint: "继续当前异常停止的会话" },
|
||||
// handler: async (invocation) => {
|
||||
// const sessionId = rewind.invocationSessionId(invocation);
|
||||
// const agent = continueRetry.resolveAgent(ctx, sessionId);
|
||||
// if (!agent || !continueRuntime) return { kind: "error", text: "当前会话不能继续" };
|
||||
// const result = continueRuntime.continueNow(agent);
|
||||
// if (!result.ok) return { kind: "error", text: result.error };
|
||||
// return { kind: "success", text: `已发送继续(${result.used}/${result.max})` };
|
||||
// },
|
||||
// });
|
||||
}
|
||||
|
||||
if (ctx.tools) {
|
||||
@@ -784,6 +836,73 @@ function installWebServer(ctx, cfg) {
|
||||
response.end();
|
||||
},
|
||||
}, "dsh-purge: rewind");
|
||||
// host.webServer.register({
|
||||
// kind: "exact",
|
||||
// path: "/dsh-purge/continue",
|
||||
// handler: async (request, response) => {
|
||||
// if (request.method === "GET") {
|
||||
// try {
|
||||
// const url = new URL(request.url, "http://127.0.0.1");
|
||||
// const sessionId = String(url.searchParams.get("sessionId") || "").trim();
|
||||
// sendJson(response, 200, continueStatusPayload(ctx, sessionId));
|
||||
// } 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 agent = continueRetry.resolveAgent(ctx, sessionId);
|
||||
// if (!agent || !continueRuntime) {
|
||||
// sendJson(response, 409, { ok: false, error: "当前会话不能继续" });
|
||||
// return;
|
||||
// }
|
||||
// const result = continueRuntime.continueNow(agent, { force: Boolean(body?.force) });
|
||||
// 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: continue");
|
||||
// host.webServer.register({
|
||||
// kind: "exact",
|
||||
// path: "/dsh-purge/continue/settings",
|
||||
// handler: async (request, response) => {
|
||||
// if (request.method === "GET") {
|
||||
// try {
|
||||
// sendJson(response, 200, { ok: true, ...currentContinueConfig() });
|
||||
// } catch (e) {
|
||||
// sendJson(response, 500, { ok: false, error: String(e) });
|
||||
// }
|
||||
// return;
|
||||
// }
|
||||
// if (request.method === "POST") {
|
||||
// try {
|
||||
// const body = await readJsonBody(request);
|
||||
// savedContinueSettings = await continueRetry.saveSettings(core.findDshHome(), {
|
||||
// ...currentContinueConfig(),
|
||||
// ...body,
|
||||
// });
|
||||
// sendJson(response, 200, { ok: true, ...currentContinueConfig() });
|
||||
// } catch (e) {
|
||||
// sendJson(response, 500, { ok: false, error: String(e) });
|
||||
// }
|
||||
// return;
|
||||
// }
|
||||
// response.writeHead(405, { allow: "GET, POST" });
|
||||
// response.end();
|
||||
// },
|
||||
// }, "dsh-purge: continue settings");
|
||||
host.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/update",
|
||||
@@ -919,11 +1038,8 @@ function installWebServer(ctx, cfg) {
|
||||
handler: async (request, response) => {
|
||||
if (request.method === "GET") {
|
||||
try {
|
||||
const dshHome = core.findDshHome();
|
||||
const fp = core.findOverrideFile(dshHome);
|
||||
let content = "";
|
||||
if (fs.existsSync(fp)) content = await fsp.readFile(fp, "utf8");
|
||||
sendJson(response, 200, { ok: true, exists: fs.existsSync(fp), content, path: fp });
|
||||
const ui = await core.ensureOverrideContent(core.findDshHome(), false);
|
||||
sendJson(response, 200, { ok: true, ...ui });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
@@ -937,11 +1053,8 @@ function installWebServer(ctx, cfg) {
|
||||
sendJson(response, 400, { ok: false, error: "content must be a string" });
|
||||
return;
|
||||
}
|
||||
const dshHome = core.findDshHome();
|
||||
const fp = core.findOverrideFile(dshHome);
|
||||
await fsp.mkdir(dshHome, { recursive: true });
|
||||
await fsp.writeFile(fp, content, "utf8");
|
||||
sendJson(response, 200, { ok: true, path: fp });
|
||||
const saved = await core.saveOverrideContent(core.findDshHome(), content);
|
||||
sendJson(response, 200, { ok: true, ...saved });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user