fix: 发布 1.1.61,多宿主 Apply 与 #73/#74、极简 preset

- Apply/reapply 同时写 npm-global 与桌面宿主;#73 地区闸门误拦;#74 提示词落盘与 resolveInjectText

- 极简 #80 官方 shell;agent-preset/selected 优先;adaptInjectForMinimalPreset;refusal-recover 扩展

- identity 注入去重与组装;默认提示词重加密 asset-table.js

Closes #73. Closes #74.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-10-07 18:13:19 +08:00
1 parent 8079d69bfb
commit f51c1d6ddc
17 files changed
+957 -429

No files matched your search

+450 -68
View File
@@ -18,6 +18,7 @@ import {
commitExtractedDir,
extractAsarToSide,
shouldExtractAsar,
sameAsarIdentity,
hostFs,
newestPreservedDir,
overlayAsarUnpacked,
@@ -866,6 +867,22 @@ export function allowTargetPath(fp, surface = detectSurface()) {
return zone !== "desktop-install" && zone !== "desktop-profile";
}
/** 按正在清洗的 aiBase 判定路径,多宿主 Apply 时 CLI/Web 也能写桌面 resources/app。 */
export function allowTargetPathForAiBase(fp, aiBase) {
const zone = pathZone(fp);
if (aiBase && desktop.isInsideDesktopInstall(aiBase)) {
return zone === "desktop-install" || zone === "desktop-profile" || zone === "shared";
}
return zone !== "desktop-install" && zone !== "desktop-profile";
}
let _patchTargetAiBase = null;
function allowTargetForPatch(fp) {
if (_patchTargetAiBase) return allowTargetPathForAiBase(fp, _patchTargetAiBase);
return allowTargetPath(fp);
}
function keepSurfaceFile(fp) {
return fp && isFile(fp) && allowTargetPath(fp);
}
@@ -1709,6 +1726,104 @@ function findAiBaseWeb() {
return null;
}
/** 一次 Apply 要打到的全部 @deepseek-ai 插件根(Web/CLI npm-global + 桌面 resources/app 等)。 */
export function enumeratePatchAiBases() {
const keys = new Set();
const out = [];
const add = (p) => {
if (!p) return;
const n = path.normalize(p);
const k = n.replace(/\\/g, "/").toLowerCase();
if (!isAiBase(n) || keys.has(k)) return;
keys.add(k);
out.push(n);
};
add(findAiBaseWeb());
add(findAiBaseDesktop());
for (const root of desktop.listDesktopPackageRoots()) add(root);
const env = String(process.env.DSH_BASE || "").trim();
if (env) add(path.normalize(env));
add(findAiBaseFromDshHome(findDshHome()));
return out;
}
const APPLY_STATUS_RANK = {
failed: 0,
pattern_not_found: 1,
read_error: 2,
missing_file: 3,
applied: 4,
already: 5,
na: 6,
skipped: 7,
};
/** 多宿主 apply 时合并 patch 行:取各宿主上「最差」状态。 */
export function mergeApplyReports(reports) {
const flat = reports.flat();
const byId = new Map();
for (const row of flat) {
const id = row.patch_id ?? row.id;
const prev = byId.get(id);
const rank = APPLY_STATUS_RANK[row.status] ?? 0;
const prevRank = prev ? (APPLY_STATUS_RANK[prev.status] ?? 0) : 99;
if (!prev || rank < prevRank) byId.set(id, { ...row, patch_id: id });
}
return [...byId.values()].sort((a, b) => (a.patch_id ?? 0) - (b.patch_id ?? 0));
}
export function allPatchHostsWritten(hosts) {
return Array.isArray(hosts) && hosts.length > 0 && hosts.every((h) => h.hostWritten === true);
}
async function resolveAiBaseForApply(aiBase, options = {}) {
if (!aiBase) return null;
if (!desktop.isInsideDesktopInstall(aiBase)) return aiBase;
try {
const located = await resolveOfficialAiBase(aiBase, { forApply: options.forApply === true });
return located?.aiBase || aiBase;
} catch {
return aiBase;
}
}
export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) {
const hosts = [];
const seen = new Set();
for (const raw of enumeratePatchAiBases()) {
const aiBase = await resolveAiBaseForApply(raw, options);
if (!aiBase) continue;
const key = path.normalize(aiBase).replace(/\\/g, "/").toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
await backupAll(aiBase);
const report = await applyPatches(aiBase, patches, options);
hosts.push({
aiBase,
report,
summary: summarizeApplyReport(report),
hostWritten: hostCleanMarkersPresent(aiBase),
flash: silenceCmdFlash(aiBase),
});
}
return { hosts, report: mergeApplyReports(hosts.map((h) => h.report)) };
}
export async function revertAllHosts(options = {}) {
const reverted = [];
const errors = [];
for (const aiBase of enumeratePatchAiBases()) {
try {
const r = await revertAll(aiBase, options);
reverted.push(...(r.reverted || []));
for (const [p, e] of r.errors || []) errors.push([p, e]);
} catch (e) {
errors.push([aiBase, String(e && e.message ? e.message : e)]);
}
}
return { reverted, errors };
}
export function dshBaseEnvStatus() {
const raw = process.env.DSH_BASE;
if (!raw || !String(raw).trim()) return { set: false, path: "", valid: false };
@@ -1824,12 +1939,17 @@ export async function openSealedDesktopHost(options = {}) {
const archive = asarFileIdentity(handoff.asar);
const recorded = readUnpackedAsarStamp();
let aiBase = aiBaseUnderAppDir(appDir);
const extract = shouldExtractAsar({
const asarStill = asarArchiveIsFile(handoff.asar);
let extract = shouldExtractAsar({
usable: Boolean(aiBase),
identity: archive,
recorded,
upgrade: options.upgrade === true,
});
// 用户点「应用」:归档还在且 stamp 对不上当前 asar,或还没有可用 aiBase,必须先解包再洗。
if (options.forApply === true && asarStill) {
if (!aiBase || !archive || !sameAsarIdentity(archive, recorded)) extract = true;
}
let extracted = false;
let prev = "";
if (extract) {
@@ -1905,12 +2025,15 @@ function aiBaseBelongsToExe(aiBase, exe) {
}
/** 密封官方包只认这份 exe 的 resources/app。旁边同名目录不算当前宿主。 */
export async function resolveOfficialAiBase(aiBase) {
export async function resolveOfficialAiBase(aiBase, options = {}) {
const handoff = sealedAsarHandoff();
if (!handoff?.exe) return { aiBase: aiBase || null, handoff: null };
if (aiBaseBelongsToExe(aiBase, handoff.exe)) return { aiBase, handoff };
const opened = await openSealedDesktopHost();
return { aiBase: opened.aiBase || null, handoff: opened.swapAsar ? opened : handoff };
if (!options.forApply && aiBaseBelongsToExe(aiBase, handoff.exe)) return { aiBase, handoff };
const opened = await openSealedDesktopHost({
upgrade: options.upgrade === true,
forApply: options.forApply === true,
});
return { aiBase: opened.aiBase || null, handoff: opened.swapAsar ? opened : handoff, extracted: opened.extracted };
}
/** 重启前把清洗写进当前宿主。没写完就返回失败,调用方不得打开进程。 */
@@ -1925,36 +2048,57 @@ export async function ensureHostClean() {
}
if (!aiBase) return { ok: false, error: missingAiBaseMessage(), aiBase: null };
const pendingIds = async () => {
const status = await patchStatus(aiBase);
return Object.entries(status).filter(([, state]) => state === "pending").map(([id]) => id);
const pendingAcross = async (bases) => {
const ids = new Set();
for (const base of bases) {
const status = await patchStatus(base);
for (const [id, state] of Object.entries(status)) {
if (state === "pending") ids.add(id);
}
}
return [...ids];
};
const snapshotHosts = (bases) => bases.map((b) => ({
aiBase: b,
hostWritten: hostCleanMarkersPresent(b),
flash: silenceCmdFlash(b),
}));
let pending = await pendingIds();
let flash = silenceCmdFlash(aiBase);
if (pending.length || flash.ok !== true) {
await backupAll(aiBase);
// 点重启是用户动作,要把还没写上的前端补丁写完。启动自愈才跳过 client.js。
const report = await applyPatches(aiBase, ALL_PATCHES, { preserveClientBundles: false });
const patchOpts = { preserveClientBundles: false, forApply: true };
let bases = enumeratePatchAiBases();
if (!bases.some((b) => path.normalize(b).toLowerCase() === path.normalize(aiBase).toLowerCase())) {
bases = [aiBase, ...bases];
}
let allHosts = snapshotHosts(bases);
let pending = await pendingAcross(bases);
const needsApply =
pending.length > 0 ||
!allPatchHostsWritten(allHosts) ||
!allHosts.every((h) => h.flash?.ok === true);
if (needsApply) {
const multi = await applyPatchesAllHosts(ALL_PATCHES, patchOpts);
allHosts = multi.hosts.length ? multi.hosts : allHosts;
await patchAllShims();
flash = silenceCmdFlash(aiBase);
const summary = summarizeApplyReport(report);
pending = await pendingIds();
const summary = summarizeApplyReport(multi.report);
pending = await pendingAcross(allHosts.map((h) => h.aiBase));
const blocking = summary.failed.filter((row) => row.status !== "pattern_not_found");
if (pending.length || blocking.length || flash.ok !== true) {
const flashOk = allHosts.every((h) => h.flash?.ok === true);
if (pending.length || blocking.length || !flashOk) {
return {
ok: false,
error: "清洗没有完成,已取消重启",
pending,
failed: blocking.length,
aiBase,
hosts: allHosts.map((h) => h.aiBase),
};
}
}
if (!hostCleanMarkersPresent(aiBase)) {
return { ok: false, error: "清洗没有写进当前宿主,已取消重启", aiBase };
if (!allPatchHostsWritten(allHosts)) {
return { ok: false, error: "清洗没有写进全部宿主,已取消重启", aiBase, hosts: allHosts.map((h) => h.aiBase) };
}
return { ok: true, aiBase, pending: [] };
return { ok: true, aiBase, pending: [], hosts: allHosts.map((h) => h.aiBase) };
}
/** 官方桌面仍在读 app.asar 时:结束进程、挪走 asar、再打开 exe(补丁在 resources/app 才生效)。 */
@@ -2045,13 +2189,36 @@ export function findOverrideFile(dshHome) {
let committedOverride = null;
/** 本次进程里提示词框刚提交的正文。重启后为空,回到插件加密默认。不读宿主文件。 */
/** 本次进程里提示词框刚提交的正文;与磁盘上用户自改正文合并使用。 */
export function rememberCommittedOverride(dshHome, text) {
const home = path.normalize(String(dshHome || ""));
if (!home) return;
committedOverride = { home, text: typeof text === "string" ? text : "" };
}
/** $DSH_HOME/prompt-inject.md 正文(应用/解包后由加密槽落下;注入与设置框以它为准)。 */
export function readPromptInjectFileSync(dshHome) {
const fp = findOverrideFile(dshHome);
let disk = "";
try {
if (fp && fs.existsSync(fp)) disk = fs.readFileSync(fp, "utf8");
} catch {
disk = "";
}
const norm = normalizeOverride(disk);
return norm ? disk.replace(/\r\n/g, "\n") : "";
}
/** 与加密默认 hash 不同 → 用户自改(installOverride 不得覆盖)。 */
export function readCustomizedOverrideSync(dshHome) {
const disk = readPromptInjectFileSync(dshHome);
const norm = normalizeOverride(disk);
if (!norm) return "";
if (hashOverride(norm) === defaultOverrideHash()) return "";
return norm;
}
/** 仅本进程提示词框提交;重启后为空,注入改读 prompt-inject.md(#74)。 */
export function peekCommittedOverride(dshHome) {
if (!committedOverride) return null;
const home = path.normalize(String(dshHome || ""));
@@ -2122,10 +2289,11 @@ const COMPLETE_PROMPT_WATERFALL_INJECT =
"\t\tif (completeSection === void 0 && !runtimeContextSuppressed) return { ...transformed, sections: [...dshPurgeSections, ...dshPurgeRest] }; // [dsh-purge] every mode keeps system inject\n" +
"\t\treturn {\n" +
"\t\t\t...transformed,\n" +
"\t\t\tsections: completeSection === void 0 ? [...dshPurgeSections, ...dshPurgeRest] : (function (complete, purge) {\n" +
"\t\t\tsections: completeSection === void 0 ? [...dshPurgeSections, ...dshPurgeRest] : (function (complete, purge, rest) {\n" +
"\t\t\t\tconst base = { ...complete };\n" +
"\t\t\t\treturn [...purge, base]; // [dsh-purge] complete prompt keeps waterfall inject\n" +
"\t\t\t})(completeSection, dshPurgeSections),\n" +
"\t\t\t\tconst tail = rest.filter((s) => String(s?.name || \"\") !== String(base.name || \"\"));\n" +
"\t\t\t\treturn [...purge, ...tail, base]; // [dsh-purge] complete prompt keeps inject + agent-instructions\n" +
"\t\t\t})(completeSection, dshPurgeSections, dshPurgeRest),\n" +
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
"\t\t};";
@@ -2288,7 +2456,11 @@ const PATCHES = [
{
id: 43, name: "WEB_PRESET_IDENTITY_STRIP", layer: "提示词", layer_en: "Prompt",
desc: "Web 四个内置预设只去掉身份句 / strip web preset identity only",
file: ["preset-standard", "preset-unrestricted", "preset-ptc", "preset-cordis", "preset-minimal"],
// strictFiles 的列表里只能放「宿主一定有的文件」。preset-unrestricted 不是内置预设,
// 只有用户自己造了一个才存在;把它列进来,等于让这个补丁永远满足不了自己的契约
// (rollupPatchStatus 只在 notFound>0 时判失败,missing 计数会被 applied 吃掉,静默变绿)。
// 它改由 #76 以软补丁单独兜底。
file: ["preset-standard", "preset-ptc", "preset-cordis", "preset-minimal"],
strictFiles: true,
replacements: [
{
@@ -2308,6 +2480,34 @@ const PATCHES = [
],
markers: [' prefix: ""'],
},
{
// 用户自造的 unrestricted 预设走软补丁:文件不在就 skipped,在就把身份句清掉。
// 不参与 strictFiles 的硬判定,这样有没有这个预设都不会拖累 #43。
id: 76,
name: "PRESET_UNRESTRICTED_IDENTITY_STRIP",
layer: "提示词",
layer_en: "Prompt",
desc: "用户自造 unrestricted 预设只去掉身份句(软补丁)/ soft strip for a user-made unrestricted preset",
file: ["preset-unrestricted"],
optional: true,
replacements: [
{
pattern: " prefix: You are a coding agent powered by the {{model}} model.",
replace: ' prefix: ""',
},
{
pattern:
" prefix: >-\n" +
" You are a coding agent powered by the {{model}} model.",
replace: ' prefix: ""',
},
{
pattern: " prefix: You are a helpful software engineer assistant.",
replace: ' prefix: ""',
},
],
markers: [' prefix: ""'],
},
{
id: 70,
name: "PRESET_SHELL_NETWORK",
@@ -2331,6 +2531,10 @@ const PATCHES = [
desc: "极简 bash 去掉误留的镜像说明 / drop the extra mirror sentence",
file: ["preset-minimal", "preset-sdk-minimal"],
optional: true,
// 这一行早被 #70 的整段 shell 重写一并吃掉了,本补丁的 pattern 再也不会命中。
// 没有 markers 会让它长年报 skipped;挂上 #70 的标记,清洗到位的文件就报 already。
skipIfMarked: true,
markers: ["[dsh-purge] preset shell network"],
replacements: [
{
pattern: /\n[ \t]*\* Network access depends on the task environment\. Prefer configured mirrors\/proxies when they are available\.\n/,
@@ -2347,6 +2551,11 @@ const PATCHES = [
file: ["preset-liangshen", "preset-liangshen-pkg"],
strictFiles: true,
skipIfMarked: true,
// YAML 侧的后处理(sanitizeYamlPersonaScalars)会重排 prefix 折叠块,
// 有时把身份句删掉了却没留下 marker 那行 —— 结果就是「目的达成、标记缺失」。
// strictFiles 会把这种半完成状态判成 pattern_not_found 硬失败。
// 按布局软补丁结算:残留 pattern 没了就算做完,不靠 marker 一行定生死。
softSettle: true,
replacements: [
{
pattern:
@@ -2930,6 +3139,22 @@ const NEW_TOOL_PATCHES = [
replace:
"personaPrefix: !!js process.env.DSH_SYSTEM_PROMPT ?? ''",
},
{
pattern:
" prefix: You are a helpful software engineer assistant.\n" +
" complete: true\n" +
" includeRuntimeContext: false\n" +
" - id: persistent-shell",
replace:
" prefix: \"\"\n" +
" complete: false # [dsh-purge] minimal keeps operator once\n" +
" includeRuntimeContext: false\n" +
" - id: agent-instructions\n" +
" name: '@deepseek-ai/dsh-agent-instructions'\n" +
" config:\n" +
" maxBytes: 65536\n" +
" - id: persistent-shell",
},
{
pattern:
" prefix: \"\"\n" +
@@ -2953,10 +3178,83 @@ const NEW_TOOL_PATCHES = [
" - id: persistent-shell",
},
],
markersAny: true,
markers: [
"personaPrefix: !!js process.env.DSH_SYSTEM_PROMPT ?? ''",
"complete: false # [dsh-purge] minimal keeps operator once",
"id: agent-instructions",
],
},
{
// 极简工具表保持官方 persistent shell;inject 侧用 identity.adaptInjectForMinimalPreset(#78/#79 已撤)。
id: 80,
name: "MINIMAL_OFFICIAL_TOOLSET",
layer: "工具",
layer_en: "Tools",
desc: "撤掉曾追加的 fs/web,恢复官方极简工具表 / restore official minimal tool plugins",
file: ["preset-minimal", "preset-sdk-minimal"],
optional: true,
skipIfMarked: true,
replacements: [
{
pattern:
" - id: tool-fs # [dsh-purge] minimal fs tool parity\n" +
" name: '@deepseek-ai/dsh-tool-fs'\n" +
" - id: tool-fs-search\n" +
" name: '@deepseek-ai/dsh-tool-fs-search'\n" +
" config:\n" +
" sampleOverCapGlobResults: false\n" +
" - id: tool-web # [dsh-purge] minimal web tool parity\n" +
" name: '@deepseek-ai/dsh-tool-web'\n" +
" config:\n" +
" fetch: true\n" +
" searchTimeoutMs: 60000\n" +
" - id: persistent-shell",
replace: " - id: persistent-shell # [dsh-purge] minimal official toolset",
},
{
pattern:
" - id: tool-fs # [dsh-purge] minimal fs tool parity\n" +
" name: '@deepseek-ai/dsh-tool-fs'\n" +
" - id: tool-fs-search\n" +
" name: '@deepseek-ai/dsh-tool-fs-search'\n" +
" config:\n" +
" sampleOverCapGlobResults: false\n" +
" - id: persistent-shell",
replace: " - id: persistent-shell # [dsh-purge] minimal official toolset",
},
{
pattern:
" - id: tool-web # [dsh-purge] minimal web tool parity\n" +
" name: '@deepseek-ai/dsh-tool-web'\n" +
" config:\n" +
" fetch: true\n" +
" searchTimeoutMs: 60000\n" +
" - id: persistent-shell",
replace: " - id: persistent-shell # [dsh-purge] minimal official toolset",
},
{
pattern:
" - id: tool-fs # [dsh-purge] minimal fs tool parity\n" +
" name: '@deepseek-ai/dsh-tool-fs'\n" +
"\n" +
" - id: tool-fs-search\n" +
" name: '@deepseek-ai/dsh-tool-fs-search'\n" +
" config:\n" +
" sampleOverCapGlobResults: false\n" +
"\n" +
" - id: tool-web # [dsh-purge] minimal web tool parity\n" +
" name: '@deepseek-ai/dsh-tool-web'\n" +
" config:\n" +
" fetch: true\n" +
" searchTimeoutMs: 60000\n" +
"\n" +
" - id: persistent-bash",
replace: " - id: persistent-bash # [dsh-purge] minimal official toolset",
},
],
markers: ["[dsh-purge] minimal official toolset"],
},
{
// phase-1 白名单放行 dsh-purge section。
id: 28, name: "LIANGSHEN_PHASE1_KEEP_INJECT", layer: "提示词", layer_en: "Prompt",
@@ -3129,10 +3427,6 @@ const NEW_TOOL_PATCHES = [
pattern: "a policy denial: do not retry another way",
replace: "a sandbox notice; continue the task and retry another way if needed",
},
{
pattern: "one sentence describing why this command needs the wider access. Approval is auto-granted.",
replace: "Required with sandbox_permissions: one sentence describing why this command needs the wider access.",
},
{
pattern:
"The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.",
@@ -3378,9 +3672,29 @@ const NEW_TOOL_PATCHES = [
"\t\t};",
replace: COMPLETE_PROMPT_WATERFALL_INJECT,
},
{
pattern:
"\t\tconst transformed = await this.ctx.waterfall(scopeTarget(this, scope), \"system-prompt/assemble\", assembly, context, () => Promise.resolve(assembly));\n" +
"\t\tconst dshPurgeSections = (transformed.sections || []).filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\") && String(s.text || \"\").length > 0);\n" +
"\t\tconst dshPurgeRest = (transformed.sections || []).filter((s) => !String(s && s.name || \"\").startsWith(\"dsh-purge\"));\n" +
"\t\tif (completeSection === void 0 && !runtimeContextSuppressed) return { ...transformed, sections: [...dshPurgeSections, ...dshPurgeRest] }; // [dsh-purge] every mode keeps system inject\n" +
"\t\treturn {\n" +
"\t\t\t...transformed,\n" +
"\t\t\tsections: completeSection === void 0 ? [...dshPurgeSections, ...dshPurgeRest] : (function (complete, purge) {\n" +
"\t\t\t\tconst base = { ...complete };\n" +
"\t\t\t\treturn [...purge, base]; // [dsh-purge] complete prompt keeps waterfall inject\n" +
"\t\t\t})(completeSection, dshPurgeSections),\n" +
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
"\t\t};",
replace: COMPLETE_PROMPT_WATERFALL_INJECT,
},
],
forbid: ["dsh-purge:committed"],
markers: ["complete prompt keeps waterfall inject"],
markersAny: true,
markers: [
"complete prompt keeps waterfall inject",
"complete prompt keeps inject + agent-instructions",
],
},
{
id: 42, name: "SETTINGS_LEGACY_API", layer: "代码", layer_en: "Code",
@@ -4437,7 +4751,7 @@ const NEW_TOOL_PATCHES = [
markers: ["[dsh-purge] rewind hides the cut turn"],
},
{
id: 74,
id: 77,
name: "REWIND_DROP_SENT_ON_APPEND",
layer: "代码",
layer_en: "Code",
@@ -4818,13 +5132,13 @@ function officialShellMain() {
}
function firstExisting(candidates) {
return candidates.find((fp) => fp && fs.existsSync(fp) && allowTargetPath(fp)) ?? "";
return candidates.find((fp) => fp && fs.existsSync(fp) && allowTargetForPatch(fp)) ?? "";
}
function allExisting(candidates) {
const hit = [];
for (const fp of candidates) {
if (fp && fs.existsSync(fp) && allowTargetPath(fp) && !hit.includes(fp)) hit.push(fp);
if (fp && fs.existsSync(fp) && allowTargetForPatch(fp) && !hit.includes(fp)) hit.push(fp);
}
return hit;
}
@@ -4996,19 +5310,47 @@ function filterTargetFiles(files) {
const out = {};
for (const [key, val] of Object.entries(files)) {
if (Array.isArray(val)) {
const kept = val.filter((fp) => !fp || !fs.existsSync(fp) || allowTargetPath(fp));
const existing = kept.filter((fp) => fp && fs.existsSync(fp) && allowTargetPath(fp));
const kept = val.filter((fp) => !fp || !fs.existsSync(fp) || allowTargetForPatch(fp));
const existing = kept.filter((fp) => fp && fs.existsSync(fp) && allowTargetForPatch(fp));
out[key] = existing.length ? existing : [];
} else if (val && fs.existsSync(val) && !allowTargetPath(val)) {
} else if (val && fs.existsSync(val) && !allowTargetForPatch(val)) {
out[key] = "";
} else {
out[key] = val;
}
}
// 落空的键直接不登记。状态面板上那些 ✗ 行看起来像「有东西没清洗到位」,
// 实际是这套布局本来就没有那个文件(preset-unrestricted、*-nested 等)。
// 下游 pathsOf() 对缺键返回 [],与登记成 "" 的行为完全一致。
for (const key of Object.keys(out)) {
const val = out[key];
if (val === "" || (Array.isArray(val) && val.length === 0)) delete out[key];
}
return out;
}
/**
* npm 嵌套布局下的重复副本:@deepseek-ai/dsh/node_modules/@deepseek-ai/<pkg>。
* 桌面解包布局没有这一层(@deepseek-ai/dsh 存在但不带自己的 node_modules)。
* 整组键按需登记:嵌套根不存在就不登记,免得状态面板长期挂 4 个 ✗,
* 看着像有东西没清洗到位,其实这套布局压根没有那一层。
*/
function nestedTargetFiles(aiBase) {
const nestedRoot = path.join(aiBase, "dsh", "node_modules", "@deepseek-ai");
if (!isDir(nestedRoot)) return {};
const entry = (pkg) => firstExisting([path.join(nestedRoot, pkg, "lib", "index.js")]);
return {
"system-prompt-nested": entry("dsh-system-prompt"),
"tool-web-nested": entry("dsh-tool-web"),
"hooks-claude-code-nested": entry("dsh-hooks-claude-code"),
"hooks-codex-nested": entry("dsh-hooks-codex"),
};
}
export function targetFiles(aiBase, dshHome = findDshHome()) {
const prevTarget = _patchTargetAiBase;
_patchTargetAiBase = aiBase || null;
try {
const root = packageRootFromAiBase(aiBase);
const files = {
"agent-instructions": firstExisting([
@@ -5155,30 +5497,19 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
path.join(aiBase, "dsh-system-prompt", "lib", "index.js"),
...(root ? [path.join(root, "packages", "core", "system-prompt", "lib", "index.js")] : []),
]),
"system-prompt-nested": firstExisting([
path.join(aiBase, "dsh", "node_modules", "@deepseek-ai", "dsh-system-prompt", "lib", "index.js"),
]),
"tool-web": firstExisting([
path.join(aiBase, "dsh-tool-web", "lib", "index.js"),
...(root ? [path.join(root, "packages", "tools", "tool-web", "lib", "index.js")] : []),
]),
"tool-web-nested": firstExisting([
path.join(aiBase, "dsh", "node_modules", "@deepseek-ai", "dsh-tool-web", "lib", "index.js"),
]),
"hooks-claude-code": firstExisting([
path.join(aiBase, "dsh-hooks-claude-code", "lib", "index.js"),
...(root ? [path.join(root, "packages", "hooks", "hooks-claude-code", "lib", "index.js")] : []),
]),
"hooks-claude-code-nested": firstExisting([
path.join(aiBase, "dsh", "node_modules", "@deepseek-ai", "dsh-hooks-claude-code", "lib", "index.js"),
]),
"hooks-codex": firstExisting([
path.join(aiBase, "dsh-hooks-codex", "lib", "index.js"),
...(root ? [path.join(root, "packages", "hooks", "hooks-codex", "lib", "index.js")] : []),
]),
"hooks-codex-nested": firstExisting([
path.join(aiBase, "dsh", "node_modules", "@deepseek-ai", "dsh-hooks-codex", "lib", "index.js"),
]),
...nestedTargetFiles(aiBase),
"pi-ai-completions": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-completions.js")),
"pi-ai-responses-shared": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-responses-shared.js")),
"pi-ai-anthropic-messages": allExisting(listPiAiApiFiles(dshHome, aiBase, "anthropic-messages.js")),
@@ -5235,7 +5566,10 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
...nestedPkg(aiBase, "dsh-sandbox-policy", "lib", "index.js"),
]),
};
return filterTargetFiles(files);
return filterTargetFiles(files);
} finally {
_patchTargetAiBase = prevTarget;
}
}
function asLf(text) {
@@ -5337,6 +5671,15 @@ function yamlStripDisposableFoldParas(bodyLines) {
return out;
}
/** 折叠块里有没有「可丢弃」的段落。没有就一点都不该动它。 */
function yamlHasDisposableFoldParagraph(bodyLines) {
const raw = yamlFoldBodyText(bodyLines);
if (!raw) return false;
return raw
.split(/\n\s*\n/)
.some((para) => String(para || "").trim() !== "" && isDisposableYamlFoldParagraph(para));
}
function emptyDisposableFoldedYaml(text) {
const headerRe = /^(\s*)(personaPrefix|prefix|persona|text|suffix):\s*[>|][-+]?\s*$/;
const lines = String(text).split("\n");
@@ -5349,7 +5692,14 @@ function emptyDisposableFoldedYaml(text) {
}
const keyIndent = m[1].length;
const end = yamlConsumeFoldBody(lines, i, keyIndent);
let body = yamlDropPaddingOnlyLines(lines.slice(i + 1, end));
const body = yamlDropPaddingOnlyLines(lines.slice(i + 1, end));
// 键名是通用名(text / prefix / suffix),宿主 YAML 里到处都是。只有当块里
// 真的含有待清理的样板段时才碰它 —— 否则 `text: >` 会被改写成 `|-` 字面块,
// 那是把「折叠换行」变成「真换行」,属于内容语义变化,不是修复。
if (!yamlHasDisposableFoldParagraph(body)) {
out.push(lines[i]);
continue;
}
const kept = yamlStripDisposableFoldParas(body);
if (kept.length === 0) out.push(`${m[1]}${m[2]}: ""`);
else {
@@ -6218,7 +6568,7 @@ export function hashOverride(text) {
}
export function defaultOverrideText() {
// 提示词框默认显示、以及重启后注入,只认插件加密槽。不读 lib/default-prompt-inject.md。
// 插件内置出厂默认(加密槽)。解包/应用后写入 $DSH_HOME/prompt-inject.md;运行注入以该文件为准。
const sealed = openSlot();
return normalizeOverride(sealed) ? sealed : "";
}
@@ -6262,6 +6612,21 @@ export async function markOverrideCustomized(dshHome, customized, text) {
});
}
/**
* 磁盘上这份正文是不是「上一次我们自己落盘写进去的」。
*
* 必须先比这一步,再比内置默认:重新加密(embed-prompt)之后 defaultOverrideHash()
* 一定会变,而磁盘上还是上一版默认。直接拿磁盘比新默认,会把「插件自己写的旧默认」
* 误判成「用户手改」,installOverride 从此永久拒绝更新——这就是「改了 default-prompt-inject.md
* 却不生效」的根因。state.hash / state.seedHash 记的就是我们上次写下去的那一份。
*/
function overrideTextIsOurs(state, text) {
const stamp = hashOverride(text);
if (typeof state?.hash === "string" && state.hash === stamp) return true;
if (typeof state?.seedHash === "string" && state.seedHash === stamp) return true;
return false;
}
export async function isUserCustomizedOverride(dshHome) {
const state = await readOverrideState(dshHome);
if (state.customized === true) return true;
@@ -6275,9 +6640,12 @@ export async function isUserCustomizedOverride(dshHome) {
}
}
if (!normalizeOverride(disk)) return false;
// 磁盘正文已和内置默认不同:算用户自改(不能只信 customized:false,否则会被 installOverride 盖掉)。
if (hashOverride(disk) !== defaultOverrideHash()) return true;
return false;
// 磁盘 = 上次我们写的 → 未自改,可以随新默认一起前进。
if (overrideTextIsOurs(state, disk)) return false;
// 磁盘已等于当前默认 → 未自改。
if (hashOverride(disk) === defaultOverrideHash()) return false;
// 兜底:既不是我们写的,也不是当前默认 → 用户自改,保留。
return true;
}
export async function overrideStatus(_dshHome) {
@@ -6285,24 +6653,28 @@ export async function overrideStatus(_dshHome) {
return "missing";
}
/** 设置页框里显示插件加密默认。不读取宿主磁盘上的提示词文件。 */
/** 设置框显示 $DSH_HOME/prompt-inject.md;尚未落下时预览加密默认。 */
export async function readOverrideForUi(dshHome) {
const fp = findOverrideFile(dshHome);
const defaultContent = defaultOverrideText();
const disk = readPromptInjectFileSync(dshHome);
let exists = false;
try { exists = fs.existsSync(fp); } catch { exists = false; }
const hasDisk = Boolean(normalizeOverride(disk));
const customized = hasDisk && hashOverride(disk) !== defaultOverrideHash();
const content = hasDisk ? disk : defaultContent;
return {
path: fp,
exists,
empty: !normalizeOverride(defaultContent),
customized: false,
usingDefault: true,
content: defaultContent,
exists: exists && hasDisk,
empty: !normalizeOverride(content),
customized,
usingDefault: hasDisk && !customized,
content,
defaultContent,
};
}
/** 显式编辑缺文件时才会用到。应用、启动、读取设置不得调用:空磁盘表示没有操作者正文。 */
/** 磁盘尚无正文时,把加密槽写入 prompt-inject.md(显式编辑 / 兜底)。 */
export function seedOverrideSync(dshHome) {
const fp = findOverrideFile(dshHome);
fs.mkdirSync(dshHome, { recursive: true });
@@ -6338,8 +6710,8 @@ export function seedOverrideSync(dshHome) {
}
/**
* 只在用户显式打开编辑器、文件还不存在时写入内置默认。
* 应用和启动不得调用。磁盘已是用户自改正文时绝不覆盖。
* 解包/应用成功后:把加密槽写入 $DSH_HOME/prompt-inject.md(用户自改时不覆盖)。
* force 仅用于显式「恢复默认」。
*/
export async function installOverride(dshHome, force = false) {
const fp = findOverrideFile(dshHome);
@@ -6354,8 +6726,16 @@ export async function installOverride(dshHome, force = false) {
disk = "";
}
}
// 用户正文(与内置不同)一律保留,除非显式 force。
if (!force && normalizeOverride(disk) && hashOverride(disk) !== defaultOverrideHash()) {
// 用户正文(与内置不同、且不是我们上次写下去的那一份)一律保留,除非显式 force。
// 必须先排掉「插件自己写的旧默认」:否则重新加密后会被误判成用户自改,
// 还会被 markOverrideCustomized(true) 永久钉死,之后任何 Apply 都不再更新这个文件。
const state = await readOverrideState(dshHome);
if (
!force
&& normalizeOverride(disk)
&& hashOverride(disk) !== defaultOverrideHash()
&& !overrideTextIsOurs(state, disk)
) {
await markOverrideCustomized(dshHome, true, disk);
return "exists";
}
@@ -6370,9 +6750,11 @@ export async function installOverride(dshHome, force = false) {
return "wrote";
}
/** 框里正在显示的字优先;框空则用插件加密默认。不读宿主磁盘。 */
export function resolveApplyOverrideText(_dshHome, incoming) {
/** 应用提交:框内字 > 已有 prompt-inject.md > 加密槽。 */
export function resolveApplyOverrideText(dshHome, incoming) {
if (normalizeOverride(incoming)) return String(incoming);
const disk = readPromptInjectFileSync(dshHome);
if (normalizeOverride(disk)) return disk;
const bundled = defaultOverrideText();
if (normalizeOverride(bundled)) return bundled;
return "";