feat: 发布 1.1.3,提示词只注入一次并修复插件加载

This commit is contained in:
叫我小杨同学 committed 2026-09-18 14:10:58 +08:00
1 parent 8f860d4a53
commit 238b39b8ff
10 files changed
+434 -61

No files matched your search

+108 -12
View File
@@ -90,12 +90,9 @@ function stripHarnessPersona(text) {
}
function collectInjectText(purgeSections, fallbackText) {
const fromSections = purgeSections
.map((s) => String(s.text || "").trim())
.filter(Boolean)
.join("\n\n")
.trim();
if (fromSections) return fromSections;
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() : "";
}
@@ -116,6 +113,92 @@ function isPersonaFoldTarget(name, preferPrefix) {
return PERSONA_PREFIX_NAMES.has(name) || PERSONA_LEGACY_NAMES.has(name);
}
function eventList(session) {
if (!session) return [];
if (typeof session.snapshotEvents === "function") {
try {
const events = session.snapshotEvents();
if (Array.isArray(events)) return events;
} catch {}
}
if (Array.isArray(session.events)) return session.events;
return [];
}
function messageText(message) {
if (typeof message === "string") return message;
const content = message?.content;
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
return content.map((block) => (typeof block?.text === "string" ? block.text : "")).join("\n");
}
export function existingSystemPrompt(context) {
const events = eventList(context?.agent?.session || context?.session);
let latest = "";
for (const event of events) {
if (event?.type !== "system/message") continue;
const text = messageText(event.data?.message || event.data).trim();
if (text) latest = text;
}
return latest;
}
export function isFirstConversationTurn(context) {
if (!context || typeof context !== "object") return true;
const explicit = context.turn ?? context.turnIndex ?? context.userTurn ?? context.messageIndex;
if (explicit != null && Number.isFinite(Number(explicit))) return Number(explicit) <= 1;
const events = eventList(context.agent?.session || context.session);
if (events.length > 0) return !events.some((event) => event?.type === "turn/end");
const msgs = context.messages || context.history || [];
if (!Array.isArray(msgs) || msgs.length === 0) return true;
const users = msgs.filter((m) => {
const role = String(m?.role || m?.type || m?.kind || "").toLowerCase();
return role === "user" || role === "human";
});
return users.length <= 1;
}
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)));
}
export function shouldInjectPrompt(context, injectOnce = true, injectText = "") {
if (injectOnce === false) return true;
if (isFirstConversationTurn(context)) return true;
return !promptAlreadyInjected(existingSystemPrompt(context), injectText);
}
export function isMnemonPluginMessage(message) {
const source = message?.source;
if (!source || typeof source !== "object") return false;
const plugin = String(source.plugin || "").toLowerCase();
return source.kind === "plugin" && plugin.includes("mnemon");
}
function isMnemonSection(name) {
return String(name || "").toLowerCase().includes("mnemon");
}
function normalizeRewriteOptions(fallbackInject, options) {
if (fallbackInject && typeof fallbackInject === "object" && !Array.isArray(fallbackInject)) {
return {
fallbackInject: typeof fallbackInject.fallbackInject === "string" ? fallbackInject.fallbackInject : "",
dropMnemon: fallbackInject.dropMnemon !== false,
dropPurgeAfterFold: fallbackInject.dropPurgeAfterFold !== false,
pinPersonaText: typeof fallbackInject.pinPersonaText === "string" ? fallbackInject.pinPersonaText : "",
};
}
return {
fallbackInject: typeof fallbackInject === "string" ? fallbackInject : "",
dropMnemon: options?.dropMnemon !== false,
dropPurgeAfterFold: options?.dropPurgeAfterFold !== false,
pinPersonaText: typeof options?.pinPersonaText === "string" ? options.pinPersonaText : "",
};
}
// 0.1.5 优先写入 persona-prefix;无 prefix 时写入 legacy persona。
function foldInjectIntoPersona(sections, injectText) {
const inject = typeof injectText === "string" ? injectText.trim() : "";
@@ -138,23 +221,36 @@ function foldInjectIntoPersona(sections, injectText) {
return [{ name: "deployment:persona-prefix", text: inject }, ...out];
}
export function rewritePromptAssembly(assembled, fallbackInject = "") {
export function rewritePromptAssembly(assembled, fallbackInject = "", options = {}) {
if (!assembled || !Array.isArray(assembled.sections)) return assembled;
const opts = normalizeRewriteOptions(fallbackInject, options);
if (opts.pinPersonaText) {
assembled.sections = [{ name: "deployment:persona-prefix", text: opts.pinPersonaText }];
return assembled;
}
const rest = [];
const purge = [];
for (const section of assembled.sections) {
if (!section || section.name === "harness:identity") continue;
if (section.name === "dsh-purge:identity") continue;
if (opts.dropMnemon && isMnemonSection(section.name)) continue;
const next = { ...section };
if (typeof next.text === "string" && !String(next.name).startsWith("dsh-purge")) {
next.text = stripHarnessPersona(next.text);
}
if (String(next.name).startsWith("dsh-purge")) purge.push(next);
else rest.push(next);
if (String(next.name).startsWith("dsh-purge")) {
if (!opts.fallbackInject) continue;
purge.push(next);
} else {
rest.push(next);
}
}
// fallbackInject:section 被滤掉时从 prompt-inject.md 补回。
const injectText = collectInjectText(purge, fallbackInject);
assembled.sections = [...foldInjectIntoPersona(rest, injectText), ...purge];
const injectText = opts.fallbackInject ? 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];
return assembled;
}
+79 -14
View File
@@ -2,13 +2,17 @@ import fs from "node:fs";
import { promises as fsp } from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { AsyncLocalStorage } from "node:async_hooks";
import { fileURLToPath } from "node:url";
import * as core from "./core.js";
import * as rules from "./rules.js";
import * as updater from "./update.js";
import {
GLOBAL_PROMPT_ORDER,
existingSystemPrompt,
isMnemonPluginMessage,
rewritePromptAssembly,
shouldInjectPrompt,
} from "./identity.js";
import * as rewind from "./rewind.js";
@@ -21,6 +25,8 @@ const DEFAULTS = {
autoApplyOnStart: true,
autoUpdateOnStart: true,
autoRevertOnMissing: false,
injectOnce: true,
stripMnemon: true,
postPrompt: "",
postPromptOrder: 5100,
verbose: false,
@@ -108,12 +114,20 @@ function readInjectFile(injectFile) {
}
}
const assembleState = new AsyncLocalStorage();
function injectAllowedNow(config) {
if (config.enabled === false) return false;
const state = assembleState.getStore();
return !state || state.allow !== false;
}
export function registerPromptSections(ctx, config, injectFile) {
ctx.systemPrompt.section({
name: "dsh-purge",
order: GLOBAL_PROMPT_ORDER,
text: () => {
if (!config.enabled) return "";
if (!injectAllowedNow(config)) return "";
return readInjectFile(injectFile);
},
});
@@ -122,7 +136,7 @@ export function registerPromptSections(ctx, config, injectFile) {
name: "dsh-purge:rules",
order: GLOBAL_PROMPT_ORDER + 1,
text: () => {
if (!config.enabled) return "";
if (!injectAllowedNow(config)) return "";
try {
return rules.activeRuleText(core.findDshHome());
} catch {
@@ -139,7 +153,7 @@ export function registerPromptSections(ctx, config, injectFile) {
ctx.systemPrompt.section({
name: "dsh-purge:post",
order: config.postPromptOrder,
text: postPrompt,
text: () => (injectAllowedNow(config) ? postPrompt : ""),
});
}
@@ -165,26 +179,50 @@ function readInjectFallback() {
}
}
function installIdentityOverride(ctx) {
function installMnemonMessageStrip(ctx, config = {}) {
if (config.stripMnemon === false) return;
if (typeof ctx.on !== "function") return;
const hook = async (_assembly, _context, next) => {
const assembled = typeof next === "function" ? await next() : _assembly;
return rewritePromptAssembly(assembled, readInjectFallback());
if (ctx.__dshPurgeMnemonStrip) return;
ctx.__dshPurgeMnemonStrip = true;
const wrap = async (_payload, next) => {
const decision = await next();
if (!decision || !Array.isArray(decision.messages)) return decision;
const messages = decision.messages.filter((message) => !isMnemonPluginMessage(message));
if (messages.length === decision.messages.length) return decision;
return { ...decision, messages };
};
// prepend:false 先于 phase-1 滤镜;prepend:true 在滤镜之后再折一次。
try {
ctx.on("system-prompt/assemble", hook, { global: true, prepend: false });
} catch {}
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
const late = () => {
try {
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
ctx.on("agent/pre-step", wrap, { global: true, prepend: true });
} catch {}
};
late();
queueMicrotask(late);
setTimeout(late, 1500);
}
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);
const pin = !allow && existingSystemPrompt(context);
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,
pinPersonaText: pin,
});
});
};
// 只挂一次:挂多次会让同一轮 assemble 折两遍,UI 也会显示两次注入。
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
}
const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"];
function desktopShimNeedsPatch(dirs) {
@@ -483,7 +521,8 @@ export function apply(ctx, config) {
}
});
installIdentityOverride(ctx);
installIdentityOverride(ctx, cfg);
installMnemonMessageStrip(ctx, cfg);
const injectFile = core.findOverrideFile(core.findDshHome());
registerPromptSections(ctx, cfg, injectFile);
@@ -726,6 +765,24 @@ function installWebServer(ctx, cfg) {
}
},
}, "dsh-purge: status");
host.webServer.register({
kind: "exact",
path: "/dsh-purge/last-user",
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.readLastUserText(ctx, sessionId));
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
}
},
}, "dsh-purge: last user");
host.webServer.register({
kind: "exact",
path: "/dsh-purge/rewind/options",
@@ -1088,3 +1145,11 @@ async function readJsonBody(request) {
if (!raw) return {};
return JSON.parse(raw);
}
const plugin = {
name,
inject,
apply,
};
export default plugin;
+18
View File
@@ -202,6 +202,24 @@ export function getPending() {
return lastPending;
}
export function lastHumanUserText(events) {
const list = Array.isArray(events) ? events : [];
for (let i = list.length - 1; i >= 0; i -= 1) {
if (isHumanUserEvent(list[i])) return userTextFromEvent(list[i]);
}
return "";
}
export async function readLastUserText(ctx, sessionId) {
if (!sessionId) return { ok: false, text: "", error: "没有当前会话" };
try {
const log = await readSessionLog(ctx, sessionId);
return { ok: true, text: lastHumanUserText(log.events) };
} catch (err) {
return { ok: false, text: "", error: errorText(err) };
}
}
function disposeObservation(observed) {
try {
observed?.[Symbol.dispose]?.();