mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 11:30:22 +08:00
加入默认的破限制提示词,修改显示,支持桌面端
This commit is contained in:
1 parent
d6392202d3
commit
dd53482b21
13 files changed
+2064
-838
No files matched your search
+738
-260
File diff suppressed because it is too large.
Load diff
+342
-12
@@ -2,12 +2,16 @@
|
||||
// 功能(移植自 dsh_purge.py,一个不差):
|
||||
// 1. 启动自动重洗(autoApplyOnStart)— 解决 npm 升级覆盖 node_modules 后需手动重跑的痛点
|
||||
// 2. /purge 命令 — status / apply / revert / edit / help
|
||||
// 2b. /rules 命令 — list / use / create / delete / reset
|
||||
// 3. 模型工具 — purge_status / purge_apply / purge_revert
|
||||
// 4. systemPrompt 注入 — 会话强指令 section(兜底,不依赖改文件)
|
||||
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as core from "./core.js";
|
||||
import * as rules from "./rules.js";
|
||||
|
||||
export const name = "dsh-purge";
|
||||
|
||||
@@ -22,7 +26,7 @@ const DEFAULTS = {
|
||||
verbose: false,
|
||||
};
|
||||
|
||||
const GLOBAL_PROMPT_ORDER = 100;
|
||||
const GLOBAL_PROMPT_ORDER = -40;
|
||||
|
||||
const log = (config, ...args) => {
|
||||
if (config?.verbose) console.log("[dsh-purge]", ...args);
|
||||
@@ -63,7 +67,7 @@ function renderStatus(state) {
|
||||
out.push(` ${mark} [#${String(p.id).padEnd(2)}] ${p.name.padEnd(30)} ${p.layer}/${p.layer_en} — ${s}`);
|
||||
}
|
||||
out.push("");
|
||||
out.push(`shim: dsh.cmd=${state.shim_cmd} dsh.ps1=${state.shim_ps1}`);
|
||||
out.push(`shim: dsh.cmd=${state.shim_cmd} dsh.ps1=${state.shim_ps1} dsh=${state.shim_bin}`);
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
@@ -82,6 +86,19 @@ export function registerPromptSections(ctx, config, injectFile) {
|
||||
},
|
||||
});
|
||||
|
||||
ctx.systemPrompt.section({
|
||||
name: "dsh-purge:rules",
|
||||
order: GLOBAL_PROMPT_ORDER + 1,
|
||||
text: () => {
|
||||
if (!config.enabled) return "";
|
||||
try {
|
||||
return rules.activeRuleText(core.findDshHome());
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const postPrompt = typeof config.postPrompt === "string" ? config.postPrompt.trim() : "";
|
||||
if (!postPrompt) return;
|
||||
if (!Number.isFinite(config.postPromptOrder) || config.postPromptOrder <= GLOBAL_PROMPT_ORDER) {
|
||||
@@ -99,7 +116,7 @@ export function registerPromptSections(ctx, config, injectFile) {
|
||||
async function autoApply(config) {
|
||||
try {
|
||||
const state = await core.gatherState();
|
||||
// 始终确保 override 文件存在(缺失则建空文件,不覆盖已有内容)
|
||||
// 始终确保 override 文件存在(缺失或空则写入插件默认文案,不覆盖已有内容)
|
||||
await core.installOverride(state.dsh_home, false);
|
||||
if (!state.ai_base) {
|
||||
log(config, "skip auto-apply: plugin root not found");
|
||||
@@ -202,7 +219,117 @@ async function handlePurgeCommand(rawInput, config) {
|
||||
" /purge apply 应用全部清洗(提示词+代码+shim+override)\n" +
|
||||
" /purge revert 回滚还原\n" +
|
||||
" /purge edit 编辑注入文件 prompt-inject.md\n" +
|
||||
" /purge help 显示帮助",
|
||||
" /purge help 显示帮助\n" +
|
||||
"规则集切换见 /rules(list | use <id> | create | delete | reset)",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function renderRulesStatus(st) {
|
||||
const out = [];
|
||||
out.push("规则集 / Rule Sets");
|
||||
out.push(` 存储目录 / store ${st.rules_dir}`);
|
||||
const targetLine = st.active
|
||||
? `${st.agents_path} (${st.active_target})`
|
||||
: "(无激活)";
|
||||
out.push(` 目标文件 / target ${targetLine} — exists=${st.agents_exists}, synced=${st.agents_synced}`);
|
||||
out.push("");
|
||||
if (st.rules.length === 0) {
|
||||
out.push(" (暂无规则 / no rules — 用 /rules create <id> 或设置页新建)");
|
||||
}
|
||||
for (const r of st.rules) {
|
||||
const isActive = r.id === st.active;
|
||||
const label = r.name !== r.id ? `${r.name} (${r.id})` : r.id;
|
||||
out.push(` ${isActive ? "▶" : "·"} ${label}${isActive ? " ★ 当前" : ""} [${r.target}] (${rules.formatSize(r.size)})`);
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
async function handleRulesCommand(rawInput) {
|
||||
const args = (rawInput || "").trim().split(/\s+/).filter(Boolean);
|
||||
const sub = (args[0] || "list").toLowerCase();
|
||||
const dshHome = core.findDshHome();
|
||||
|
||||
switch (sub) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "s":
|
||||
return { kind: "success", text: renderRulesStatus(await rules.rulesStatus(dshHome)) };
|
||||
case "use":
|
||||
case "activate":
|
||||
case "u": {
|
||||
const id = args[1];
|
||||
if (!id) return { kind: "error", text: "用法: /rules use <id>" };
|
||||
try {
|
||||
const meta = await rules.activateRule(dshHome, id);
|
||||
return {
|
||||
kind: "success",
|
||||
text: `✓ 已激活规则 ${meta.name}(${id})→ 写入 ${rules.targetPath(dshHome, meta.target)},并注入 systemPrompt。新会话生效。`,
|
||||
};
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `激活失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "create":
|
||||
case "new":
|
||||
case "c": {
|
||||
const id = args[1];
|
||||
if (!id) return { kind: "error", text: "用法: /rules create <id> [别名] [AGENTS.md|CLAUDE.md]" };
|
||||
const name = args[2] || id;
|
||||
const target = args[3] || "AGENTS.md";
|
||||
if (!rules.validTarget(target)) {
|
||||
return { kind: "error", text: `无效目标: ${target}(只能是 AGENTS.md 或 CLAUDE.md)` };
|
||||
}
|
||||
try {
|
||||
await rules.saveRule(dshHome, id, "", { name, target });
|
||||
return {
|
||||
kind: "success",
|
||||
text: `✓ 已创建规则 ${name}(${id} → ${target})。在设置页「规则设定」编辑内容后保存。`,
|
||||
};
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `创建失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "delete":
|
||||
case "rm":
|
||||
case "d": {
|
||||
const id = args[1];
|
||||
if (!id) return { kind: "error", text: "用法: /rules delete <id>" };
|
||||
try {
|
||||
await rules.deleteRule(dshHome, id);
|
||||
return { kind: "success", text: `✓ 已删除规则 ${id}。` };
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `删除失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "reset":
|
||||
case "restore":
|
||||
case "还原": {
|
||||
try {
|
||||
const r = await rules.resetToOriginal(dshHome);
|
||||
const lines = [];
|
||||
if (r.removed.length > 0) lines.push(`✓ 已删除插件写入的目标文件: ${r.removed.join(", ")}`);
|
||||
if (r.skipped.length > 0) {
|
||||
lines.push(`⚠ 跳过(文件内容与规则不一致,可能被手动修改): ${r.skipped.join(", ")}`);
|
||||
}
|
||||
lines.push("已清空激活状态。规则库内容保留,随时可重新激活。现在回到出厂状态:无全局指令。");
|
||||
return { kind: "success", text: lines.join("\n") };
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `还原失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "help":
|
||||
case "h":
|
||||
default:
|
||||
return {
|
||||
kind: "success",
|
||||
text: "规则集命令:\n" +
|
||||
" /rules list 列出所有规则\n" +
|
||||
" /rules use <id> 激活规则(写入 AGENTS.md/CLAUDE.md,并注入 systemPrompt)\n" +
|
||||
" /rules create <id> [别名] [目标] 新建规则\n" +
|
||||
" /rules delete <id> 删除规则\n" +
|
||||
" /rules reset 还原原始状态\n" +
|
||||
" /rules help 显示帮助",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -217,6 +344,9 @@ export function apply(ctx, config) {
|
||||
// 1. 启动自动重洗(异步,不阻塞启动)
|
||||
setImmediate(() => {
|
||||
autoApply(cfg).then((r) => log(cfg, "auto-apply:", r));
|
||||
rules.ensureInitialState(core.findDshHome())
|
||||
.then((r) => log(cfg, "rules init:", JSON.stringify(r)))
|
||||
.catch((e) => console.warn("[dsh-purge] rules init error:", String(e)));
|
||||
});
|
||||
|
||||
// 2. systemPrompt 注入(注入用户"全局提示词"内容;默认空则什么都不注入)
|
||||
@@ -232,6 +362,12 @@ export function apply(ctx, config) {
|
||||
input: { hint: "status | apply | revert | edit | help" },
|
||||
handler: async (invocation) => handlePurgeCommand(invocation.rawInput ?? "", cfg),
|
||||
});
|
||||
commands.register({
|
||||
name: "rules",
|
||||
description: "规则集切换(写入 AGENTS.md/CLAUDE.md): list | use <id> | create <id> [别名] [目标] | delete <id> | reset | help",
|
||||
input: { hint: "list | use <id> | create <id> [别名] [目标] | delete <id> | reset | help" },
|
||||
handler: async (invocation) => handleRulesCommand(invocation.rawInput ?? ""),
|
||||
});
|
||||
}
|
||||
|
||||
// 4. 模型工具(原始 JSON-Schema ToolDefinition,零 peer 依赖)
|
||||
@@ -318,6 +454,45 @@ export function apply(ctx, config) {
|
||||
installWebServer(ctx, cfg);
|
||||
}
|
||||
|
||||
function portFromRequest(request) {
|
||||
const hostHeader = String(request.headers?.host || "");
|
||||
const match = hostHeader.match(/:(\d+)$/);
|
||||
if (match) return Number(match[1]);
|
||||
return 3080;
|
||||
}
|
||||
|
||||
function hostFromRequest(request) {
|
||||
const hostHeader = String(request.headers?.host || "127.0.0.1");
|
||||
return hostHeader.replace(/:\d+$/, "") || "127.0.0.1";
|
||||
}
|
||||
|
||||
function restartArgv() {
|
||||
const argv = process.argv.slice(1).filter((arg) => arg !== "--no-open");
|
||||
argv.push("--no-open");
|
||||
return argv;
|
||||
}
|
||||
|
||||
function scheduleWebRestart(request) {
|
||||
const helper = fileURLToPath(new URL("./restart-web.js", import.meta.url));
|
||||
const child = spawn(process.execPath, [helper], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
env: {
|
||||
...process.env,
|
||||
DSH_PURGE_RESTART: JSON.stringify({
|
||||
execPath: process.execPath,
|
||||
argv: restartArgv(),
|
||||
cwd: process.cwd(),
|
||||
host: hostFromRequest(request),
|
||||
port: portFromRequest(request),
|
||||
}),
|
||||
},
|
||||
});
|
||||
child.unref();
|
||||
setTimeout(() => process.exit(0), 250);
|
||||
}
|
||||
|
||||
// ── Web UI 设置面板后端(HTTP 路由)──────────────────────────────
|
||||
|
||||
function installWebServer(ctx, cfg) {
|
||||
@@ -346,6 +521,7 @@ function installWebServer(ctx, cfg) {
|
||||
patch_names,
|
||||
shim_cmd: state.shim_cmd,
|
||||
shim_ps1: state.shim_ps1,
|
||||
shim_bin: state.shim_bin,
|
||||
has_backup: state.has_backup,
|
||||
override_status: state.override_status,
|
||||
override_path: state.override_path,
|
||||
@@ -373,14 +549,16 @@ function installWebServer(ctx, cfg) {
|
||||
}
|
||||
await core.backupAll(state.ai_base);
|
||||
const report = await core.applyPatches(state.ai_base);
|
||||
await core.installOverride(state.dsh_home, false);
|
||||
const override = await core.ensureOverrideContent(state.dsh_home, false);
|
||||
if (state.shim_dir) await core.patchShim(state.shim_dir);
|
||||
sendJson(response, 200, {
|
||||
ok: true,
|
||||
applied: report.filter((r) => r.status === "applied").length,
|
||||
already: report.filter((r) => r.status === "already").length,
|
||||
report: report.map((r) => ({ id: r.patch_id, name: r.name, status: r.status })),
|
||||
note: "重启 dsh 完全生效",
|
||||
override_content: override.content,
|
||||
override_path: override.path,
|
||||
override_installed: override.installed,
|
||||
});
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
@@ -419,8 +597,8 @@ function installWebServer(ctx, cfg) {
|
||||
handler: async (request, response) => {
|
||||
if (request.method === "GET") {
|
||||
try {
|
||||
const state = await core.gatherState();
|
||||
const fp = core.findOverrideFile(state.dsh_home);
|
||||
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 });
|
||||
@@ -437,9 +615,9 @@ function installWebServer(ctx, cfg) {
|
||||
sendJson(response, 400, { ok: false, error: "content must be a string" });
|
||||
return;
|
||||
}
|
||||
const state = await core.gatherState();
|
||||
const fp = core.findOverrideFile(state.dsh_home);
|
||||
await fsp.mkdir(state.dsh_home, { recursive: true });
|
||||
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 });
|
||||
} catch (e) {
|
||||
@@ -451,10 +629,162 @@ function installWebServer(ctx, cfg) {
|
||||
response.end();
|
||||
},
|
||||
}, "dsh-purge: override");
|
||||
installRulesHttp(host.webServer);
|
||||
host.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/restart",
|
||||
handler: async (request, response) => {
|
||||
if (request.method !== "POST") {
|
||||
response.writeHead(405, { allow: "POST" });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
scheduleWebRestart(request);
|
||||
sendJson(response, 200, { ok: true, note: "正在重启 dsh web…" });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: restart");
|
||||
}, "dsh-purge: http routes");
|
||||
});
|
||||
}
|
||||
|
||||
function methodNotAllowed(request, response, allow) {
|
||||
if (allow.includes(request.method)) return false;
|
||||
response.writeHead(405, { allow: allow.join(", ") });
|
||||
response.end();
|
||||
return true;
|
||||
}
|
||||
|
||||
function installRulesHttp(webServer) {
|
||||
const dshHome = core.findDshHome();
|
||||
|
||||
webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/rules/status",
|
||||
handler: async (request, response) => {
|
||||
if (methodNotAllowed(request, response, ["GET"])) return;
|
||||
try {
|
||||
sendJson(response, 200, { ok: true, ...(await rules.rulesStatus(dshHome)) });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: rules status");
|
||||
|
||||
webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/rules/read",
|
||||
handler: async (request, response) => {
|
||||
if (methodNotAllowed(request, response, ["GET"])) return;
|
||||
try {
|
||||
const url = new URL(request.url ?? "", "http://localhost");
|
||||
const id = url.searchParams.get("id") ?? "";
|
||||
if (!rules.validRuleId(id)) {
|
||||
sendJson(response, 400, { ok: false, error: "invalid id" });
|
||||
return;
|
||||
}
|
||||
const content = await rules.readRule(dshHome, id);
|
||||
if (content === null) {
|
||||
sendJson(response, 404, { ok: false, error: `rule not found: ${id}` });
|
||||
return;
|
||||
}
|
||||
const meta = await rules.readRuleMeta(dshHome, id);
|
||||
sendJson(response, 200, { ok: true, id, name: meta.name, target: meta.target, content });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: rules read");
|
||||
|
||||
webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/rules/save",
|
||||
handler: async (request, response) => {
|
||||
if (methodNotAllowed(request, response, ["POST"])) return;
|
||||
try {
|
||||
const body = await readJsonBody(request);
|
||||
const id = typeof body?.id === "string" ? body.id : "";
|
||||
const content = typeof body?.content === "string" ? body.content : null;
|
||||
if (!rules.validRuleId(id) || content === null) {
|
||||
sendJson(response, 400, { ok: false, error: "id and content (string) required" });
|
||||
return;
|
||||
}
|
||||
await rules.saveRule(dshHome, id, content, {
|
||||
name: typeof body?.name === "string" ? body.name : undefined,
|
||||
target: typeof body?.target === "string" ? body.target : undefined,
|
||||
});
|
||||
sendJson(response, 200, { ok: true, id });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: rules save");
|
||||
|
||||
webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/rules/activate",
|
||||
handler: async (request, response) => {
|
||||
if (methodNotAllowed(request, response, ["POST"])) return;
|
||||
try {
|
||||
const body = await readJsonBody(request);
|
||||
const id = typeof body?.id === "string" ? body.id : "";
|
||||
if (!rules.validRuleId(id)) {
|
||||
sendJson(response, 400, { ok: false, error: "invalid id" });
|
||||
return;
|
||||
}
|
||||
const meta = await rules.activateRule(dshHome, id);
|
||||
sendJson(response, 200, {
|
||||
ok: true,
|
||||
id,
|
||||
name: meta.name,
|
||||
target: meta.target,
|
||||
agents_path: rules.targetPath(dshHome, meta.target),
|
||||
note: "已写入目标文件并注入 systemPrompt,新会话生效",
|
||||
});
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: rules activate");
|
||||
|
||||
webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/rules/delete",
|
||||
handler: async (request, response) => {
|
||||
if (methodNotAllowed(request, response, ["POST"])) return;
|
||||
try {
|
||||
const body = await readJsonBody(request);
|
||||
const id = typeof body?.id === "string" ? body.id : "";
|
||||
if (!rules.validRuleId(id)) {
|
||||
sendJson(response, 400, { ok: false, error: "invalid id" });
|
||||
return;
|
||||
}
|
||||
await rules.deleteRule(dshHome, id);
|
||||
sendJson(response, 200, { ok: true, id });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: rules delete");
|
||||
|
||||
webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/rules/reset",
|
||||
handler: async (request, response) => {
|
||||
if (methodNotAllowed(request, response, ["POST"])) return;
|
||||
try {
|
||||
const r = await rules.resetToOriginal(dshHome);
|
||||
sendJson(response, 200, { ok: true, ...r, note: "已还原出厂状态(无全局指令);规则库保留" });
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: rules reset");
|
||||
}
|
||||
|
||||
function sendJson(response, status, payload) {
|
||||
response.writeHead(status, {
|
||||
"cache-control": "no-store",
|
||||
@@ -469,7 +799,7 @@ async function readJsonBody(request) {
|
||||
for await (const chunk of request) {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
size += buffer.length;
|
||||
if (size > 256 * 1024) throw new Error("request body too large");
|
||||
if (size > 512 * 1024) throw new Error("request body too large");
|
||||
chunks.push(buffer);
|
||||
}
|
||||
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Spawned by /dsh-purge/restart: wait until the old web port is free, then relaunch.
|
||||
import net from "node:net";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const encoded = process.env.DSH_PURGE_RESTART;
|
||||
if (!encoded) process.exit(1);
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = JSON.parse(encoded);
|
||||
} catch {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const port = Number(info.port) || 3080;
|
||||
const host = typeof info.host === "string" && info.host ? info.host : "127.0.0.1";
|
||||
|
||||
function portFree() {
|
||||
return new Promise((resolve) => {
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
socket.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
socket.on("error", () => resolve(true));
|
||||
});
|
||||
}
|
||||
|
||||
async function waitFree() {
|
||||
for (let i = 0; i < 80; i++) {
|
||||
if (await portFree()) return true;
|
||||
await new Promise((r) => setTimeout(r, 120));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const ok = await waitFree();
|
||||
if (!ok) process.exit(1);
|
||||
|
||||
const child = spawn(info.execPath, info.argv, {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
cwd: info.cwd || process.cwd(),
|
||||
env: process.env,
|
||||
windowsHide: true,
|
||||
});
|
||||
child.unref();
|
||||
process.exit(0);
|
||||
+14
-1
@@ -1,6 +1,7 @@
|
||||
// 规则集:多套 AGENTS.md / CLAUDE.md,切换即写入 ~/.dsh 原生全局指令通道
|
||||
// 规则集:多套 AGENTS.md / CLAUDE.md;激活时写入目标文件,并被 systemPrompt 段实时注入
|
||||
// 存储: $DSH_HOME/rules/<id>.md + <id>.json ;状态: rules/state.json
|
||||
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { findDshHome } from "./core.js";
|
||||
@@ -155,6 +156,18 @@ export async function setActive(dshHome, id) {
|
||||
await fsp.writeFile(stateFile(dshHome), JSON.stringify({ active: id }, null, 2), "utf8");
|
||||
}
|
||||
|
||||
/** Sync read for systemPrompt.section text(); empty string if none. */
|
||||
export function activeRuleText(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();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export async function activateRule(dshHome, id) {
|
||||
const content = await readRule(dshHome, id);
|
||||
if (content === null) throw new Error(`rule not found: ${id}`);
|
||||
|
||||
Reference in new issue
Block a user