mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 10:10:22 +08:00
feat: 发布 1.1.10,空提示词拦截并修首轮注入
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6a6293524a
commit
fedda6d338
9 files changed
+334
-175
No files matched your search
+35
-15
@@ -2975,11 +2975,11 @@ const NEW_TOOL_PATCHES = [
|
||||
"\t\t\t...transformed,\n" +
|
||||
"\t\t\tsections: completeSection === void 0 ? transformed.sections : (function (complete, assembled) {\n" +
|
||||
"\t\t\t\tconst sections = assembled.sections || [];\n" +
|
||||
"\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\").trim()).filter(Boolean).join(\"\\n\\n\");\n" +
|
||||
"\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\")).filter((t) => t.length > 0).join(\"\\n\\n\");\n" +
|
||||
"\t\t\t\tconst folded = sections.find((s) => s && s.name === complete.name);\n" +
|
||||
"\t\t\t\tconst base = folded && typeof folded.text === \"string\" ? { ...complete, text: folded.text } : { ...complete };\n" +
|
||||
"\t\t\t\tif (!inject) return [base];\n" +
|
||||
"\t\t\t\tif (String(base.text || \"\").includes(inject.slice(0, Math.min(80, inject.length)))) return [base];\n" +
|
||||
"\t\t\t\tif (String(base.text || \"\").includes(inject)) return [base];\n" +
|
||||
"\t\t\t\treturn [{ ...base, text: inject + \"\\n\\n\" + base.text }]; // [dsh-purge] complete prompt keeps inject\n" +
|
||||
"\t\t\t})(completeSection, transformed),\n" +
|
||||
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
|
||||
@@ -4249,16 +4249,20 @@ export function overrideStatePath(dshHome) {
|
||||
return path.join(dshHome, "dsh-purge", "override-state.json");
|
||||
}
|
||||
|
||||
export async function readOverrideState(dshHome) {
|
||||
export function readOverrideStateSync(dshHome) {
|
||||
const fp = overrideStatePath(dshHome);
|
||||
try {
|
||||
const raw = JSON.parse(await fsp.readFile(fp, "utf8"));
|
||||
const raw = JSON.parse(fs.readFileSync(fp, "utf8"));
|
||||
return raw && typeof raw === "object" ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function readOverrideState(dshHome) {
|
||||
return readOverrideStateSync(dshHome);
|
||||
}
|
||||
|
||||
export async function writeOverrideState(dshHome, state) {
|
||||
const fp = overrideStatePath(dshHome);
|
||||
await fsp.mkdir(path.dirname(fp), { recursive: true });
|
||||
@@ -4275,6 +4279,9 @@ export async function markOverrideCustomized(dshHome, customized, text) {
|
||||
}
|
||||
|
||||
export async function isUserCustomizedOverride(dshHome) {
|
||||
const state = await readOverrideState(dshHome);
|
||||
if (state.customized === true) return true;
|
||||
if (state.customized === false) return false;
|
||||
const fp = findOverrideFile(dshHome);
|
||||
let disk = "";
|
||||
if (fs.existsSync(fp)) {
|
||||
@@ -4286,9 +4293,6 @@ export async function isUserCustomizedOverride(dshHome) {
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -4319,11 +4323,11 @@ export async function readOverrideForUi(dshHome) {
|
||||
}
|
||||
}
|
||||
const customized = await isUserCustomizedOverride(dshHome);
|
||||
const show = customized && normalizeOverride(disk) ? disk : defaultContent;
|
||||
const show = customized ? disk : defaultContent;
|
||||
return {
|
||||
path: fp,
|
||||
exists,
|
||||
empty: !normalizeOverride(disk),
|
||||
empty: !normalizeOverride(show),
|
||||
customized,
|
||||
usingDefault: !customized,
|
||||
content: show,
|
||||
@@ -4331,6 +4335,24 @@ export async function readOverrideForUi(dshHome) {
|
||||
};
|
||||
}
|
||||
|
||||
/** 插件加载时同步落下默认提示词,避免第一轮 assemble 读到空文件。 */
|
||||
export function seedOverrideSync(dshHome) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
fs.mkdirSync(dshHome, { recursive: true });
|
||||
if (readOverrideStateSync(dshHome).customized === true) return "exists";
|
||||
let disk = "";
|
||||
try {
|
||||
if (fs.existsSync(fp)) disk = fs.readFileSync(fp, "utf8");
|
||||
} catch {
|
||||
disk = "";
|
||||
}
|
||||
if (normalizeOverride(disk)) return "exists";
|
||||
const bundled = defaultOverrideText();
|
||||
if (!normalizeOverride(bundled)) return fs.existsSync(fp) ? "empty" : "missing";
|
||||
fs.writeFileSync(fp, bundled, "utf8");
|
||||
return "wrote";
|
||||
}
|
||||
|
||||
export async function installOverride(dshHome, force = false) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
await fsp.mkdir(dshHome, { recursive: true });
|
||||
@@ -4345,14 +4367,12 @@ export async function installOverride(dshHome, force = false) {
|
||||
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 customized = normalizeOverride(incoming) !== normalizeOverride(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 };
|
||||
await fsp.writeFile(fp, incoming, "utf8");
|
||||
await markOverrideCustomized(dshHome, customized, incoming);
|
||||
return { path: fp, customized, content: incoming, defaultContent: bundled };
|
||||
}
|
||||
|
||||
export async function ensureOverrideContent(dshHome, force = false) {
|
||||
|
||||
+29
-20
@@ -90,10 +90,20 @@ function stripHarnessPersona(text) {
|
||||
}
|
||||
|
||||
function collectInjectText(purgeSections, fallbackText) {
|
||||
const fallback = typeof fallbackText === "string" ? fallbackText : "";
|
||||
if (fallback) return fallback;
|
||||
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() : "";
|
||||
return String(main?.text || "");
|
||||
}
|
||||
|
||||
function assemblyHasExactInject(sections, inject) {
|
||||
if (!inject) return true;
|
||||
return sections.some((section) => String(section?.text || "").includes(inject));
|
||||
}
|
||||
|
||||
function ensureFullInject(sections, inject) {
|
||||
if (!inject || assemblyHasExactInject(sections, inject)) return sections;
|
||||
return [{ name: "dsh-purge", text: inject, order: -10000 }, ...sections];
|
||||
}
|
||||
|
||||
function stripIdentityPrefix(text) {
|
||||
@@ -135,13 +145,13 @@ function messageText(message) {
|
||||
|
||||
export function existingSystemPrompt(context) {
|
||||
const events = eventList(context?.agent?.session || context?.session);
|
||||
let latest = "";
|
||||
const texts = [];
|
||||
for (const event of events) {
|
||||
if (event?.type !== "system/message") continue;
|
||||
const text = messageText(event.data?.message || event.data).trim();
|
||||
if (text) latest = text;
|
||||
if (text) texts.push(text);
|
||||
}
|
||||
return latest;
|
||||
return texts.join("\n\n");
|
||||
}
|
||||
|
||||
export function isFirstConversationTurn(context) {
|
||||
@@ -162,13 +172,13 @@ export function isFirstConversationTurn(context) {
|
||||
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)));
|
||||
return String(existing || "").includes(inject);
|
||||
}
|
||||
|
||||
export function shouldInjectPrompt(context, injectOnce = true, injectText = "") {
|
||||
if (injectOnce === false) return true;
|
||||
if (isFirstConversationTurn(context)) return true;
|
||||
return !promptAlreadyInjected(existingSystemPrompt(context), injectText);
|
||||
export function shouldInjectPrompt(_context, _injectOnce = true, _injectText = "") {
|
||||
// 0.1.5 in-history:渲染少了注入就会再追加一条 system/message。
|
||||
// 用「最后一条是否含注入」决定本步掏空注入,会 A/B 死循环。每步都必须留下完整注入。
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isMnemonPluginMessage(message) {
|
||||
@@ -199,7 +209,7 @@ function normalizeRewriteOptions(fallbackInject, options) {
|
||||
|
||||
// 0.1.5 优先写入 persona-prefix;无 prefix 时写入 legacy persona。
|
||||
function foldInjectIntoPersona(sections, injectText) {
|
||||
const inject = typeof injectText === "string" ? injectText.trim() : "";
|
||||
const inject = typeof injectText === "string" ? injectText : "";
|
||||
const names = sections.map((s) => String(s?.name || ""));
|
||||
const hasPrefix = names.some((n) => PERSONA_PREFIX_NAMES.has(n));
|
||||
let folded = false;
|
||||
@@ -207,16 +217,16 @@ function foldInjectIntoPersona(sections, injectText) {
|
||||
const name = String(section?.name || "");
|
||||
if (!isPersonaFoldTarget(name, hasPrefix)) return section;
|
||||
folded = true;
|
||||
const prior = stripIdentityPrefix(String(section.text || "").trim());
|
||||
const prior = stripIdentityPrefix(String(section.text || ""));
|
||||
if (!inject) return { ...section, text: prior };
|
||||
if (prior.includes(inject.slice(0, Math.min(80, inject.length)))) {
|
||||
return { ...section, text: prior };
|
||||
}
|
||||
if (prior.includes(inject)) return { ...section, text: prior };
|
||||
return { ...section, text: prior ? `${inject}\n\n${prior}` : inject };
|
||||
});
|
||||
if (folded) return out;
|
||||
if (!inject) return out;
|
||||
return [{ name: "deployment:persona-prefix", text: inject }, ...out];
|
||||
const orders = sections.map((s) => s?.order).filter((n) => Number.isFinite(n));
|
||||
const order = orders.length ? Math.min(0, ...orders) : 0;
|
||||
return [{ name: "deployment:persona-prefix", text: inject, order }, ...out];
|
||||
}
|
||||
|
||||
export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) {
|
||||
@@ -233,18 +243,17 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options =
|
||||
next.text = stripHarnessPersona(next.text);
|
||||
}
|
||||
if (String(next.name).startsWith("dsh-purge")) {
|
||||
if (!opts.fallbackInject) continue;
|
||||
purge.push(next);
|
||||
} else {
|
||||
rest.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
const injectText = opts.fallbackInject ? collectInjectText(purge, opts.fallbackInject) : "";
|
||||
const injectText = 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];
|
||||
assembled.sections = ensureFullInject([...folded, ...extras], injectText);
|
||||
return assembled;
|
||||
}
|
||||
+76
-67
@@ -1,6 +1,5 @@
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import * as core from "./core.js";
|
||||
import * as hostctl from "./host.js";
|
||||
import * as rules from "./rules.js";
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
GLOBAL_PROMPT_ORDER,
|
||||
isMnemonPluginMessage,
|
||||
rewritePromptAssembly,
|
||||
shouldInjectPrompt,
|
||||
} from "./identity.js";
|
||||
import * as rewind from "./rewind.js";
|
||||
import * as continueRetry from "./continue-retry.js";
|
||||
@@ -24,7 +22,7 @@ const DEFAULTS = {
|
||||
autoApplyOnStart: true,
|
||||
autoUpdateOnStart: true,
|
||||
autoRevertOnMissing: false,
|
||||
injectOnce: true,
|
||||
injectOnce: false,
|
||||
stripMnemon: true,
|
||||
postPrompt: "",
|
||||
postPromptOrder: 5100,
|
||||
@@ -138,43 +136,39 @@ function renderStatus(state) {
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
function readInjectFile(injectFile) {
|
||||
try {
|
||||
if (!injectFile || !fs.existsSync(injectFile)) return "";
|
||||
return fs.readFileSync(injectFile, "utf8").trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
const assembleState = new AsyncLocalStorage();
|
||||
|
||||
function injectAllowedNow(config) {
|
||||
if (config.enabled === false) return false;
|
||||
const state = assembleState.getStore();
|
||||
return !state || state.allow !== false;
|
||||
return config.enabled !== false;
|
||||
}
|
||||
|
||||
export function registerPromptSections(ctx, config, injectFile) {
|
||||
function injectSnapshot(dshHome = core.findDshHome()) {
|
||||
const resolved = rules.resolveInjectText(dshHome);
|
||||
return {
|
||||
injectSource: resolved.source,
|
||||
injectRuleId: resolved.ruleId,
|
||||
needPrompt: resolved.source === "none",
|
||||
};
|
||||
}
|
||||
|
||||
/** 以设置页文本框为准;空框且没有启用中的规则集则必须补提示词。 */
|
||||
function injectSnapshotFromBox(dshHome, boxText) {
|
||||
if (typeof boxText !== "string") return injectSnapshot(dshHome);
|
||||
if (core.normalizeOverride(boxText)) {
|
||||
return { injectSource: "prompt", injectRuleId: null, needPrompt: false };
|
||||
}
|
||||
const ruleId = rules.activeRuleId(dshHome);
|
||||
if (core.normalizeOverride(rules.activeRuleText(dshHome))) {
|
||||
return { injectSource: "rule", injectRuleId: ruleId, needPrompt: false };
|
||||
}
|
||||
return { injectSource: "none", injectRuleId: ruleId, needPrompt: true };
|
||||
}
|
||||
|
||||
export function registerPromptSections(ctx, config, _injectFile) {
|
||||
ctx.systemPrompt.section({
|
||||
name: "dsh-purge",
|
||||
order: GLOBAL_PROMPT_ORDER,
|
||||
text: () => {
|
||||
if (!injectAllowedNow(config)) return "";
|
||||
return readInjectFile(injectFile);
|
||||
},
|
||||
});
|
||||
|
||||
ctx.systemPrompt.section({
|
||||
name: "dsh-purge:rules",
|
||||
order: GLOBAL_PROMPT_ORDER + 1,
|
||||
text: () => {
|
||||
if (!injectAllowedNow(config)) return "";
|
||||
try {
|
||||
return rules.activeRuleText(core.findDshHome());
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
return rules.resolveInjectText(core.findDshHome()).text;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -190,26 +184,8 @@ export function registerPromptSections(ctx, config, injectFile) {
|
||||
});
|
||||
}
|
||||
|
||||
const INJECT_FALLBACK_MAX_BYTES = 512 * 1024;
|
||||
|
||||
function readInjectFallback() {
|
||||
try {
|
||||
const fp = core.findOverrideFile(core.findDshHome());
|
||||
if (!fp || !fs.existsSync(fp)) return "";
|
||||
const st = fs.statSync(fp);
|
||||
if (!st.isFile() || st.size <= 0) return "";
|
||||
if (st.size <= INJECT_FALLBACK_MAX_BYTES) return fs.readFileSync(fp, "utf8");
|
||||
const fd = fs.openSync(fp, "r");
|
||||
try {
|
||||
const buf = Buffer.alloc(INJECT_FALLBACK_MAX_BYTES);
|
||||
const n = fs.readSync(fd, buf, 0, INJECT_FALLBACK_MAX_BYTES, 0);
|
||||
return buf.toString("utf8", 0, n);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
return rules.resolveInjectText(core.findDshHome()).text;
|
||||
}
|
||||
|
||||
function installMnemonMessageStrip(ctx, config = {}) {
|
||||
@@ -238,16 +214,14 @@ 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);
|
||||
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,
|
||||
});
|
||||
const hook = async (_assembly, _context, next) => {
|
||||
const assembled = typeof next === "function" ? await next() : _assembly;
|
||||
const enabled = config.enabled !== false;
|
||||
const inject = enabled ? readInjectFallback() : "";
|
||||
return rewritePromptAssembly(assembled, {
|
||||
fallbackInject: inject,
|
||||
dropMnemon: config.stripMnemon !== false,
|
||||
dropPurgeAfterFold: true,
|
||||
});
|
||||
};
|
||||
// 只挂一次:挂多次会让同一轮 assemble 折两遍,UI 也会显示两次注入。
|
||||
@@ -559,6 +533,11 @@ export function apply(ctx, config) {
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
core.seedOverrideSync(core.findDshHome());
|
||||
} catch (e) {
|
||||
console.warn("[dsh-purge] seed override error:", String(e));
|
||||
}
|
||||
installIdentityOverride(ctx, cfg);
|
||||
installMnemonMessageStrip(ctx, cfg);
|
||||
const injectFile = core.findOverrideFile(core.findDshHome());
|
||||
@@ -948,9 +927,24 @@ function installWebServer(ctx, cfg) {
|
||||
sendJson(response, 500, { ok: false, error: core.missingAiBaseMessage() });
|
||||
return;
|
||||
}
|
||||
const body = await readJsonBody(request);
|
||||
const ui = await core.readOverrideForUi(state.dsh_home);
|
||||
const boxText = typeof body?.content === "string" ? body.content : ui.content;
|
||||
const snap = injectSnapshotFromBox(state.dsh_home, boxText);
|
||||
if (snap.needPrompt) {
|
||||
sendJson(response, 400, {
|
||||
ok: false,
|
||||
needPrompt: true,
|
||||
error: "提示词和规则集都是空的,必须先添加提示词",
|
||||
override_content: boxText,
|
||||
defaultContent: ui.defaultContent,
|
||||
...snap,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await core.backupAll(state.ai_base);
|
||||
const report = await core.applyPatches(state.ai_base);
|
||||
const override = await core.ensureOverrideContent(state.dsh_home, false);
|
||||
const override = await core.readOverrideForUi(state.dsh_home);
|
||||
const shim = await core.patchAllShims();
|
||||
const flash = core.silenceCmdFlash(state.ai_base);
|
||||
const summary = core.summarizeApplyReport(report);
|
||||
@@ -968,6 +962,8 @@ function installWebServer(ctx, cfg) {
|
||||
})),
|
||||
report: report.map((r) => ({ id: r.patch_id, name: r.name, status: r.status })),
|
||||
override_content: override.content,
|
||||
defaultContent: override.defaultContent,
|
||||
...injectSnapshot(state.dsh_home),
|
||||
override_path: override.path,
|
||||
override_installed: override.installed,
|
||||
shim,
|
||||
@@ -1038,8 +1034,9 @@ function installWebServer(ctx, cfg) {
|
||||
handler: async (request, response) => {
|
||||
if (request.method === "GET") {
|
||||
try {
|
||||
const ui = await core.ensureOverrideContent(core.findDshHome(), false);
|
||||
sendJson(response, 200, { ok: true, ...ui });
|
||||
const home = core.findDshHome();
|
||||
const ui = await core.readOverrideForUi(home);
|
||||
sendJson(response, 200, { ok: true, ...ui, ...injectSnapshot(home) });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
@@ -1053,8 +1050,19 @@ function installWebServer(ctx, cfg) {
|
||||
sendJson(response, 400, { ok: false, error: "content must be a string" });
|
||||
return;
|
||||
}
|
||||
const saved = await core.saveOverrideContent(core.findDshHome(), content);
|
||||
sendJson(response, 200, { ok: true, ...saved });
|
||||
const home = core.findDshHome();
|
||||
const snap = injectSnapshotFromBox(home, content);
|
||||
if (snap.needPrompt) {
|
||||
sendJson(response, 400, {
|
||||
ok: false,
|
||||
error: "提示词和规则集都是空的,必须先添加提示词",
|
||||
content,
|
||||
...snap,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const saved = await core.saveOverrideContent(home, content);
|
||||
sendJson(response, 200, { ok: true, ...saved, ...injectSnapshot(home) });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
@@ -1121,7 +1129,7 @@ async function handleRulesOp(op, body, queryId) {
|
||||
name: typeof body?.name === "string" ? body.name : undefined,
|
||||
target: typeof body?.target === "string" ? body.target : undefined,
|
||||
});
|
||||
return { ok: true, id };
|
||||
return { ok: true, id, ...injectSnapshot(dshHome) };
|
||||
}
|
||||
if (op === "activate") {
|
||||
if (!rules.validRuleId(id)) return { status: 400, ok: false, error: "invalid id" };
|
||||
@@ -1133,6 +1141,7 @@ async function handleRulesOp(op, body, queryId) {
|
||||
target: meta.target,
|
||||
agents_path: rules.targetPath(dshHome, meta.target),
|
||||
note: "已写入目标文件并注入 systemPrompt,新会话生效",
|
||||
...injectSnapshot(dshHome),
|
||||
};
|
||||
}
|
||||
if (op === "delete") {
|
||||
|
||||
+37
-19
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { findDshHome } from "./core.js";
|
||||
import { findDshHome, findOverrideFile, normalizeOverride } from "./core.js";
|
||||
|
||||
const RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
||||
const MAX_RULE_BYTES = 256 * 1024;
|
||||
@@ -151,17 +151,46 @@ export async function setActive(dshHome, id) {
|
||||
await fsp.writeFile(stateFile(dshHome), JSON.stringify({ active: id }, null, 2), "utf8");
|
||||
}
|
||||
|
||||
export function activeRuleText(dshHome) {
|
||||
export function activeRuleId(dshHome) {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(stateFile(dshHome), "utf8"));
|
||||
const id = parsed?.active;
|
||||
if (!validRuleId(id)) return "";
|
||||
return fs.readFileSync(rulePath(dshHome, id), "utf8").trim();
|
||||
return validRuleId(id) ? id : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function activeRuleText(dshHome) {
|
||||
const id = activeRuleId(dshHome);
|
||||
if (!id) return "";
|
||||
try {
|
||||
return fs.readFileSync(rulePath(dshHome, id), "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function overrideFileText(dshHome) {
|
||||
const fp = findOverrideFile(dshHome);
|
||||
try {
|
||||
if (!fp || !fs.existsSync(fp)) return "";
|
||||
return fs.readFileSync(fp, "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** 提示词优先;为空则用当前启用的规则集。两边都空则不注入。 */
|
||||
export function resolveInjectText(dshHome) {
|
||||
const prompt = overrideFileText(dshHome);
|
||||
if (normalizeOverride(prompt)) return { text: prompt, source: "prompt", ruleId: null };
|
||||
const ruleId = activeRuleId(dshHome);
|
||||
const rule = activeRuleText(dshHome);
|
||||
if (normalizeOverride(rule)) return { text: rule, source: "rule", ruleId };
|
||||
return { text: "", source: "none", ruleId };
|
||||
}
|
||||
|
||||
export async function activateRule(dshHome, id) {
|
||||
const content = await readRule(dshHome, id);
|
||||
if (content === null) throw new Error(`rule not found: ${id}`);
|
||||
@@ -181,21 +210,7 @@ export async function ensureInitialState(dshHome) {
|
||||
}
|
||||
active = null;
|
||||
}
|
||||
if (active !== null) return { active };
|
||||
if (listed.length > 0) return { active: null };
|
||||
for (const target of RULE_TARGETS) {
|
||||
try {
|
||||
const content = await fsp.readFile(targetPath(dshHome, target), "utf8");
|
||||
if (content.trim().length > 0) {
|
||||
await saveRule(dshHome, "default", content, { name: "默认规则", target });
|
||||
await setActive(dshHome, "default");
|
||||
return { active: "default", imported: target };
|
||||
}
|
||||
} catch {
|
||||
// 当前 target 文件不存在,试下一个
|
||||
}
|
||||
}
|
||||
return { active: null };
|
||||
return { active };
|
||||
}
|
||||
|
||||
export async function resetToOriginal(dshHome) {
|
||||
@@ -243,9 +258,12 @@ export async function rulesStatus(dshHome) {
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
const inject = resolveInjectText(dshHome);
|
||||
return {
|
||||
rules: listed,
|
||||
active,
|
||||
injectSource: inject.source,
|
||||
injectRuleId: inject.ruleId,
|
||||
active_target,
|
||||
agents_exists,
|
||||
agents_synced,
|
||||
|
||||
Reference in new issue
Block a user