@gluztm/dsh-guard 2.4.2 → 2.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/inspector.mjs CHANGED
@@ -3,19 +3,42 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
5
  import { execFileSync, spawn } from 'node:child_process';
6
-
7
- export const PACKAGE_VERSION = '2.4.2';
6
+ import {
7
+ appendAuditEntry,
8
+ atomicWriteText,
9
+ detectActiveProfile,
10
+ discoverProfiles,
11
+ formatContextAuditText,
12
+ formatMcpProbeText,
13
+ inspectContextAudit,
14
+ inspectSkills,
15
+ normalizeProfileTarget,
16
+ probeMcpServers,
17
+ readAuditLog,
18
+ toggleSkillVisibility,
19
+ validateProfileName,
20
+ } from './governance.mjs';
21
+
22
+ export const PACKAGE_VERSION = '2.4.4';
23
+ export const DESKTOP_RELEASE_VERSION = '2.4.3';
8
24
  export const REPO_URL = 'https://github.com/gluztm/DSHGuard';
9
- export const RELEASE_URL = `https://github.com/gluztm/DSHGuard/releases/tag/${PACKAGE_VERSION}`;
10
- export const INSTALLER_URL = `https://github.com/gluztm/DSHGuard/releases/download/${PACKAGE_VERSION}/DSHGuard-Setup-${PACKAGE_VERSION}.exe`;
25
+ export const RELEASE_URL = `https://github.com/gluztm/DSHGuard/releases/tag/${DESKTOP_RELEASE_VERSION}`;
26
+ export const INSTALLER_URL = `https://github.com/gluztm/DSHGuard/releases/download/${DESKTOP_RELEASE_VERSION}/DSHGuard-Setup-${DESKTOP_RELEASE_VERSION}.exe`;
11
27
 
12
28
  const SELF_PLUGIN_NAME = '@gluztm/dsh-guard';
13
29
  const SELF_LOADER_IDS = new Set(['dsh-guard', SELF_PLUGIN_NAME]);
14
30
  const MCP_CLIENT_PKG = '@deepseek-ai/dsh-mcp-client';
15
31
  const LLM_PLUGIN_IDS = new Set(['llm-pi-ai', '@deepseek-ai/dsh-llm-pi-ai']);
16
- const RESTORABLE_REL_RE = /^(?:profiles\/(?:web|desktop|headless)\/(?:cordis\.patch\.yml|cordis\.yml|package\.json)|settings\.yaml)$/;
32
+ const SYSTEM_PROMPT_IDS = new Set(['system-prompt', '@deepseek-ai/dsh-system-prompt']);
33
+ const RESTORABLE_REL_RE = /^(?:profiles\/(?:web|desktop)\/(?:cordis\.patch\.yml|cordis\.yml|package\.json)|settings\.yaml)$/;
17
34
  const SNAPSHOT_SAFE_EXT_RE = /\.(?:ya?ml|json)$/i;
18
35
  const CRED_SKIP_RE = /(?:cred|secret|token|auth|\.pem$|\.key$)/i;
36
+ const AUTO_SNAPSHOT_KEEP = 40;
37
+
38
+ function resolveTargetProfile(target, fallback = detectActiveProfile()) {
39
+ if (target === undefined || target === null || target === '' || target === 'all') return fallback;
40
+ return normalizeProfileTarget(String(target), null);
41
+ }
19
42
 
20
43
  function safeReadText(filePath) {
21
44
  try {
@@ -48,22 +71,6 @@ function sha256File(filePath) {
48
71
  }
49
72
  }
50
73
 
51
- function atomicWriteText(filePath, content, secureMode = false) {
52
- const dir = path.dirname(filePath);
53
- fs.mkdirSync(dir, { recursive: true });
54
- const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
55
- const opts = secureMode && process.platform !== 'win32' ? { encoding: 'utf8', mode: 0o600 } : 'utf8';
56
- fs.writeFileSync(tmpPath, content, opts);
57
- fs.renameSync(tmpPath, filePath);
58
- if (secureMode && process.platform !== 'win32') {
59
- try {
60
- fs.chmodSync(filePath, 0o600);
61
- } catch {
62
- // Ignore chmod failures on restricted filesystems.
63
- }
64
- }
65
- }
66
-
67
74
  export function resolveDshHome(overrideHome) {
68
75
  if (overrideHome && String(overrideHome).trim()) {
69
76
  return path.resolve(String(overrideHome).trim());
@@ -76,20 +83,23 @@ export function resolveDshHome(overrideHome) {
76
83
 
77
84
  function readRegistryInstallLocation() {
78
85
  if (process.platform !== 'win32') return null;
79
- const regKeys = [
80
- 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DSHGuard',
81
- 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DSHGuard',
86
+ const regQueries = [
87
+ { key: 'HKCU\\Software\\DSHGuard', valueName: 'InstallDir' },
88
+ { key: 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{9E1F7C34-5B2A-4D18-9C77-6A0E5D3B21F4}_is1', valueName: 'InstallLocation' },
89
+ { key: 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{9E1F7C34-5B2A-4D18-9C77-6A0E5D3B21F4}_is1', valueName: 'InstallLocation' },
90
+ { key: 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DSHGuard', valueName: 'InstallLocation' },
91
+ { key: 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DSHGuard', valueName: 'InstallLocation' },
82
92
  ];
83
- for (const key of regKeys) {
93
+ for (const { key, valueName } of regQueries) {
84
94
  try {
85
- const out = execFileSync('reg.exe', ['query', key, '/v', 'InstallLocation'], {
95
+ const out = execFileSync('reg.exe', ['query', key, '/v', valueName], {
86
96
  encoding: 'utf8',
87
97
  stdio: ['ignore', 'pipe', 'ignore'],
88
98
  timeout: 1500,
89
99
  });
90
- const match = /InstallLocation\s+REG_\w+\s+(.+)/i.exec(out);
100
+ const match = new RegExp(`${valueName}\\s+REG_\\w+\\s+(.+)`, 'i').exec(out);
91
101
  if (match && match[1]) {
92
- const dir = match[1].trim();
102
+ const dir = match[1].trim().replace(/[\\/]+$/, '');
93
103
  if (dir) return dir;
94
104
  }
95
105
  } catch {
@@ -568,6 +578,10 @@ export function inspectProfile(dshHome, profileName) {
568
578
  if (parsedPatch) collectApiKeyEnvs(parsedPatch, referencedEnvSet);
569
579
  const mcpCount = patchEntries.filter((e) => e.kind === 'insert' && e.name === MCP_CLIENT_PKG).length;
570
580
  const disabledOverrides = patchEntries.filter((e) => e.disabled === true);
581
+ const sysPromptNode = patchEntries.find((e) => SYSTEM_PROMPT_IDS.has(e.id || '') || SYSTEM_PROMPT_IDS.has(e.name || ''));
582
+ const systemPromptChars = sysPromptNode?.config && typeof sysPromptNode.config === 'object'
583
+ ? JSON.stringify(sysPromptNode.config).length
584
+ : 0;
571
585
 
572
586
  return {
573
587
  name: profileName,
@@ -583,6 +597,7 @@ export function inspectProfile(dshHome, profileName) {
583
597
  disabledEntryCount: disabledOverrides.length,
584
598
  brokenLinks,
585
599
  brokenLinkCount: brokenLinks.length,
600
+ systemPromptChars,
586
601
  patchPresent: patchText !== null,
587
602
  patchHash: patchText !== null ? sha256Text(patchText).slice(0, 12) : null,
588
603
  patchBytes: patchText !== null ? Buffer.byteLength(patchText, 'utf8') : 0,
@@ -760,6 +775,12 @@ export function upsertCredentialKey(dshHome, keyName, secretValue) {
760
775
  if (!fs.existsSync(credPath)) {
761
776
  const initial = `version: 1\nrecords: []\nrefs:\n${formattedLine}\n`;
762
777
  atomicWriteText(credPath, initial, true);
778
+ appendAuditEntry(dshHome, {
779
+ action: 'credential.upsert',
780
+ target: 'credentials',
781
+ summary: `初始化并单向写入凭据键 ${key}`,
782
+ ok: true,
783
+ });
763
784
  return { ok: true, key, path: credPath, created: true };
764
785
  }
765
786
 
@@ -792,16 +813,23 @@ export function upsertCredentialKey(dshHome, keyName, secretValue) {
792
813
 
793
814
  const output = `${lines.join('\n').replace(/\n+$/, '')}\n`;
794
815
  atomicWriteText(credPath, output, true);
816
+ appendAuditEntry(dshHome, {
817
+ action: 'credential.upsert',
818
+ target: 'credentials',
819
+ summary: `${existing ? '更新' : '新增'}凭据键 ${key}(单向盲写)`,
820
+ ok: true,
821
+ });
795
822
  return { ok: true, key, path: credPath, created: !existing };
796
823
  }
797
824
 
798
- export function inspectProviders(dshHome) {
825
+ export function inspectProviders(dshHome, target = null) {
799
826
  const maskedCreds = inspectCredentialKeysMasked(dshHome);
800
827
  const readyKeys = new Set(maskedCreds.keys.filter((k) => k.present).map((k) => k.key));
801
828
  const merged = new Map();
829
+ const profileName = normalizeProfileTarget(target) || detectActiveProfile();
802
830
 
803
- for (const profileName of ['web', 'desktop']) {
804
- const profileDir = path.join(dshHome, 'profiles', profileName);
831
+ for (const pName of [profileName]) {
832
+ const profileDir = path.join(dshHome, 'profiles', pName);
805
833
  for (const fileName of ['cordis.patch.yml', 'cordis.yml']) {
806
834
  const text = safeReadText(path.join(profileDir, fileName));
807
835
  if (!text) continue;
@@ -822,8 +850,8 @@ export function inspectProviders(dshHome) {
822
850
  profiles: [],
823
851
  models: [],
824
852
  };
825
- if (!existing.profiles.includes(profileName)) {
826
- existing.profiles.push(profileName);
853
+ if (!existing.profiles.includes(pName)) {
854
+ existing.profiles.push(pName);
827
855
  }
828
856
  if (Array.isArray(cfg.models) && existing.models.length === 0) {
829
857
  existing.models = cfg.models
@@ -889,8 +917,8 @@ function readPackageLoaderIds(profileDir, pkgName, guard) {
889
917
  return { ids, description: typeof pkgJson?.description === 'string' ? pkgJson.description : '', version: pkgJson?.version || '' };
890
918
  }
891
919
 
892
- export function inspectExtensions(dshHome, target = 'web', guard = null) {
893
- const profileName = target === 'desktop' ? 'desktop' : 'web';
920
+ export function inspectExtensions(dshHome, target = null, guard = null) {
921
+ const profileName = resolveTargetProfile(target) || detectActiveProfile();
894
922
  const profileDir = path.join(dshHome, 'profiles', profileName);
895
923
  const pkg = safeReadJson(path.join(profileDir, 'package.json'));
896
924
  const patchPath = path.join(profileDir, 'cordis.patch.yml');
@@ -950,12 +978,17 @@ export function inspectExtensions(dshHome, target = 'web', guard = null) {
950
978
  const overrideDisabled = disabledMap.get(n.id);
951
979
  const isDisabled = overrideDisabled !== undefined ? overrideDisabled : n.disabled === true;
952
980
  const cfg = n.config || {};
981
+ const parsedTimeout = Number(cfg.toolCallTimeoutMs);
982
+ const timeoutConfigured = Number.isFinite(parsedTimeout) && parsedTimeout > 0;
953
983
  mcpServers.push({
954
984
  id: n.id,
955
985
  serverName: String(cfg.serverName || n.id.replace(/^mcp-/, '')),
956
986
  transport: String(cfg.transport || (cfg.url ? 'sse' : 'stdio')),
957
987
  command: cfg.command ? String(cfg.command) : null,
988
+ args: Array.isArray(cfg.args) ? cfg.args.map((a) => String(a)) : [],
958
989
  url: cfg.url ? String(cfg.url) : null,
990
+ toolCallTimeoutMs: timeoutConfigured ? parsedTimeout : 60000,
991
+ timeoutConfigured,
959
992
  enabled: !isDisabled,
960
993
  disabled: isDisabled,
961
994
  canToggle: true,
@@ -972,15 +1005,26 @@ export function inspectExtensions(dshHome, target = 'web', guard = null) {
972
1005
  };
973
1006
  }
974
1007
 
975
- export function repairBrokenModuleLinks(dshHome, target = 'web') {
976
- const profileName = target === 'desktop' ? 'desktop' : 'web';
1008
+ export function repairBrokenModuleLinks(dshHome, target = null) {
1009
+ const profileName = resolveTargetProfile(target);
1010
+ if (!profileName) {
1011
+ return { ok: false, error: '仅支持 web 或 desktop 档案', target: String(target || ''), repairedCount: 0, unresolvableCount: 0, results: [] };
1012
+ }
977
1013
  const profileDir = path.join(dshHome, 'profiles', profileName);
978
1014
  const broken = findBrokenModuleLinks(profileDir);
979
1015
  if (broken.length === 0) {
980
- return { ok: true, target: profileName, repairedCount: 0, unresolvableCount: 0, results: [] };
1016
+ return {
1017
+ ok: true,
1018
+ allRepaired: true,
1019
+ target: profileName,
1020
+ repairedCount: 0,
1021
+ unresolvableCount: 0,
1022
+ results: [],
1023
+ message: '当前档案无断裂依赖软链接',
1024
+ };
981
1025
  }
982
1026
 
983
- const otherProfile = profileName === 'web' ? 'desktop' : 'web';
1027
+ const otherProfile = profileName === 'desktop' ? 'web' : 'desktop';
984
1028
  const results = [];
985
1029
 
986
1030
  for (const item of broken) {
@@ -1033,11 +1077,30 @@ export function repairBrokenModuleLinks(dshHome, target = 'web') {
1033
1077
  }
1034
1078
  }
1035
1079
 
1080
+ const repairedCount = results.filter((r) => r.status === 'repaired').length;
1081
+ const unresolvedItems = results.filter((r) => r.status !== 'repaired');
1082
+ const unresolvableCount = unresolvedItems.length;
1083
+ const unresolvedNames = unresolvedItems.map((r) => r.name);
1084
+ const allRepaired = unresolvableCount === 0;
1085
+ const message = allRepaired
1086
+ ? `已成功修复 ${repairedCount} 个断裂依赖软链接`
1087
+ : `已修复 ${repairedCount} 个,另有 ${unresolvableCount} 个断链(${unresolvedNames.join('、')})在本地无可用源包,请重新安装或卸载对应插件`;
1088
+
1089
+ appendAuditEntry(dshHome, {
1090
+ action: 'links.repair',
1091
+ target: profileName,
1092
+ summary: `修复断裂依赖链接:成功 ${repairedCount},未解析 ${unresolvableCount}`,
1093
+ ok: true,
1094
+ });
1095
+
1036
1096
  return {
1037
- ok: results.every((r) => r.status === 'repaired'),
1097
+ ok: true,
1098
+ allRepaired,
1038
1099
  target: profileName,
1039
- repairedCount: results.filter((r) => r.status === 'repaired').length,
1040
- unresolvableCount: results.filter((r) => r.status !== 'repaired').length,
1100
+ repairedCount,
1101
+ unresolvableCount,
1102
+ unresolvedNames,
1103
+ message,
1041
1104
  results,
1042
1105
  };
1043
1106
  }
@@ -1047,21 +1110,52 @@ function getSnapshotsRoot(dshHome) {
1047
1110
  }
1048
1111
 
1049
1112
  function collectSnapshotCandidates(dshHome, target) {
1050
- const profiles = target === 'all' ? ['web', 'desktop'] : [target === 'desktop' ? 'desktop' : 'web'];
1051
- const list = [];
1052
- for (const p of profiles) {
1053
- const dir = path.join(dshHome, 'profiles', p);
1054
- const prefix = profiles.length > 1 ? `profile-${p}-` : 'profile-';
1055
- list.push({ relPath: `profiles/${p}/cordis.patch.yml`, snapFile: `${prefix}cordis.patch.yml`, absPath: path.join(dir, 'cordis.patch.yml') });
1056
- list.push({ relPath: `profiles/${p}/cordis.yml`, snapFile: `${prefix}cordis.yml`, absPath: path.join(dir, 'cordis.yml') });
1057
- list.push({ relPath: `profiles/${p}/package.json`, snapFile: `${prefix}package.json`, absPath: path.join(dir, 'package.json') });
1058
- }
1059
- list.push({ relPath: 'settings.yaml', snapFile: 'home-settings.yaml', absPath: path.join(dshHome, 'settings.yaml') });
1113
+ const p = normalizeProfileTarget(target) || detectActiveProfile();
1114
+ const dir = path.join(dshHome, 'profiles', p);
1115
+ const list = [
1116
+ { relPath: `profiles/${p}/cordis.patch.yml`, snapFile: 'profile-cordis.patch.yml', absPath: path.join(dir, 'cordis.patch.yml') },
1117
+ { relPath: `profiles/${p}/cordis.yml`, snapFile: 'profile-cordis.yml', absPath: path.join(dir, 'cordis.yml') },
1118
+ { relPath: `profiles/${p}/package.json`, snapFile: 'profile-package.json', absPath: path.join(dir, 'package.json') },
1119
+ { relPath: 'settings.yaml', snapFile: 'home-settings.yaml', absPath: path.join(dshHome, 'settings.yaml') },
1120
+ ];
1060
1121
  return list;
1061
1122
  }
1062
1123
 
1063
- export function createSnapshot(dshHome, target = 'web', kind = 'manual', reason = '') {
1064
- const normTarget = target === 'desktop' || target === 'all' ? target : 'web';
1124
+ function pruneOldAutoSnapshots(dshHome, keepCount = AUTO_SNAPSHOT_KEEP) {
1125
+ const root = getSnapshotsRoot(dshHome);
1126
+ if (!fs.existsSync(root)) return;
1127
+ let dirs = [];
1128
+ try {
1129
+ dirs = fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory());
1130
+ } catch {
1131
+ return;
1132
+ }
1133
+
1134
+ const autoUnpinned = [];
1135
+ for (const d of dirs) {
1136
+ const full = path.join(root, d.name);
1137
+ const manifest = safeReadJson(path.join(full, 'manifest.json'));
1138
+ const kind = String(manifest?.kind || '');
1139
+ const pinned = Boolean(manifest?.pinned);
1140
+ if (!pinned && kind.startsWith('auto-')) {
1141
+ const ts = manifest?.createdAt ? Date.parse(manifest.createdAt) : 0;
1142
+ autoUnpinned.push({ full, ts, name: d.name });
1143
+ }
1144
+ }
1145
+
1146
+ if (autoUnpinned.length <= keepCount) return;
1147
+ autoUnpinned.sort((a, b) => b.ts - a.ts || b.name.localeCompare(a.name));
1148
+ for (const old of autoUnpinned.slice(keepCount)) {
1149
+ try {
1150
+ fs.rmSync(old.full, { recursive: true, force: true });
1151
+ } catch {
1152
+ // Ignore cleanup errors for locked directories.
1153
+ }
1154
+ }
1155
+ }
1156
+
1157
+ export function createSnapshot(dshHome, target = null, kind = 'manual', reason = '') {
1158
+ const normTarget = resolveTargetProfile(target) || detectActiveProfile();
1065
1159
  const now = new Date();
1066
1160
  const stamp = [
1067
1161
  now.getUTCFullYear(),
@@ -1103,15 +1197,70 @@ export function createSnapshot(dshHome, target = 'web', kind = 'manual', reason
1103
1197
  kind: safeKind,
1104
1198
  reason: String(reason || (safeKind === 'manual' ? '手动配置快照' : safeKind)),
1105
1199
  createdAt: now.toISOString(),
1200
+ pinned: false,
1201
+ pinLabel: '',
1106
1202
  itemCount: items.length,
1107
1203
  items,
1108
1204
  };
1109
1205
  atomicWriteText(path.join(snapDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
1206
+ if (safeKind.startsWith('auto-')) {
1207
+ pruneOldAutoSnapshots(dshHome, AUTO_SNAPSHOT_KEEP);
1208
+ } else {
1209
+ appendAuditEntry(dshHome, {
1210
+ action: 'snapshot.create',
1211
+ target: normTarget,
1212
+ summary: `${manifest.reason}(${items.length} 个文件)`,
1213
+ snapshotId: id,
1214
+ ok: true,
1215
+ });
1216
+ }
1110
1217
  return { ok: true, snapshot: manifest, dir: snapDir };
1111
1218
  }
1112
1219
 
1113
- export function togglePatchEntry(dshHome, target = 'web', id, disabled, guard = null) {
1114
- const profileName = target === 'desktop' ? 'desktop' : 'web';
1220
+ export function pinSnapshot(dshHome, snapshotId, pinned, pinLabel = '') {
1221
+ const id = String(snapshotId || '').trim();
1222
+ if (!id || /[\\/]|\.\./.test(id)) {
1223
+ return { ok: false, error: '无效的快照 ID' };
1224
+ }
1225
+
1226
+ const snapDir = path.join(getSnapshotsRoot(dshHome), id);
1227
+ const manifestPath = path.join(snapDir, 'manifest.json');
1228
+ if (!fs.existsSync(manifestPath)) {
1229
+ return { ok: false, error: '仅支持置顶插件原生配置快照(~/.dsh/guard-snapshots)' };
1230
+ }
1231
+
1232
+ const manifest = safeReadJson(manifestPath);
1233
+ if (!manifest || typeof manifest !== 'object') {
1234
+ return { ok: false, error: '快照清单已损坏或无法解析' };
1235
+ }
1236
+
1237
+ const nextPinned = Boolean(pinned);
1238
+ const nextLabel = nextPinned ? String(pinLabel || '').trim().slice(0, 60) : '';
1239
+ manifest.pinned = nextPinned;
1240
+ manifest.pinLabel = nextLabel;
1241
+ atomicWriteText(manifestPath, JSON.stringify(manifest, null, 2));
1242
+
1243
+ appendAuditEntry(dshHome, {
1244
+ action: nextPinned ? 'snapshot.pin' : 'snapshot.unpin',
1245
+ target: String(manifest.target || 'web'),
1246
+ summary: nextPinned ? `置顶保护快照${nextLabel ? ` (${nextLabel})` : ''}` : '取消快照置顶',
1247
+ snapshotId: id,
1248
+ ok: true,
1249
+ });
1250
+
1251
+ return {
1252
+ ok: true,
1253
+ snapshotId: id,
1254
+ pinned: nextPinned,
1255
+ pinLabel: nextLabel,
1256
+ };
1257
+ }
1258
+
1259
+ export function togglePatchEntry(dshHome, target = null, id, disabled, guard = null) {
1260
+ const profileName = resolveTargetProfile(target);
1261
+ if (!profileName) {
1262
+ return { ok: false, error: '仅支持 web 或 desktop 档案' };
1263
+ }
1115
1264
  const entryId = String(id || '').trim();
1116
1265
  if (!entryId) return { ok: false, error: '缺少条目 ID' };
1117
1266
  if (SELF_LOADER_IDS.has(entryId)) {
@@ -1194,6 +1343,13 @@ export function togglePatchEntry(dshHome, target = 'web', id, disabled, guard =
1194
1343
 
1195
1344
  const finalBody = nextLines.length > 0 ? `${nextLines.join('\n').replace(/\n+$/, '')}\n` : '';
1196
1345
  atomicWriteText(patchPath, finalBody);
1346
+ appendAuditEntry(dshHome, {
1347
+ action: 'entry.toggle',
1348
+ target: profileName,
1349
+ summary: `${wantDisabled ? '禁用' : '启用'} ${targetId}`,
1350
+ snapshotId: preSnap.snapshot.id,
1351
+ ok: true,
1352
+ });
1197
1353
 
1198
1354
  return {
1199
1355
  ok: true,
@@ -1205,7 +1361,168 @@ export function togglePatchEntry(dshHome, target = 'web', id, disabled, guard =
1205
1361
  patchPath,
1206
1362
  restartHint: profileName === 'web'
1207
1363
  ? '已写入 Web 配置文件,重载 DSH 服务后生效(已在变更前自动保存快照)'
1208
- : '已写入桌面端配置文件,重启 DSH 桌面端后生效(已在变更前自动保存快照)',
1364
+ : `已写入 ${profileName} 配置文件,重启对应 DSH 端后生效(已在变更前自动保存快照)`,
1365
+ };
1366
+ }
1367
+
1368
+ /**
1369
+ * Losslessly update or insert `toolCallTimeoutMs` on a @deepseek-ai/dsh-mcp-client insert block.
1370
+ */
1371
+ export function updateMcpTimeout(dshHome, target = null, id, timeoutMs, guard = null) {
1372
+ const profileName = resolveTargetProfile(target);
1373
+ if (!profileName) {
1374
+ return { ok: false, error: '仅支持 web 或 desktop 档案' };
1375
+ }
1376
+ const entryId = String(id || '').trim();
1377
+ if (!entryId) return { ok: false, error: '缺少 MCP 条目 ID' };
1378
+
1379
+ const ms = Math.round(Number(timeoutMs));
1380
+ if (!Number.isFinite(ms) || ms < 5000 || ms > 600000) {
1381
+ return { ok: false, error: '超时范围须在 5000 ms 到 600000 ms 之间' };
1382
+ }
1383
+
1384
+ const ext = inspectExtensions(dshHome, profileName, guard);
1385
+ const mcp = ext.mcpServers.find((m) => m.id === entryId);
1386
+ if (!mcp) {
1387
+ return { ok: false, error: `在 ${profileName} 中未找到 MCP 服务 ${entryId}` };
1388
+ }
1389
+
1390
+ const patchPath = path.join(dshHome, 'profiles', profileName, 'cordis.patch.yml');
1391
+ const existingText = safeReadText(patchPath) ?? '';
1392
+ const rawLines = existingText.replace(/\r\n/g, '\n').split('\n');
1393
+ const nodes = collectPatchNodes(parseYamlStructure(existingText));
1394
+ const targetNode = nodes.find(
1395
+ (n) => n.kind === 'insert' && n.name === MCP_CLIENT_PKG && n.id === entryId && Array.isArray(n.lineRange),
1396
+ );
1397
+ if (!targetNode) {
1398
+ return { ok: false, error: `未定位到 ${entryId} 的 YAML 配置块` };
1399
+ }
1400
+
1401
+ const [blockStart, blockEnd] = targetNode.lineRange;
1402
+ let idLineIdx = -1;
1403
+ for (let i = blockStart; i <= Math.min(blockEnd, rawLines.length - 1); i += 1) {
1404
+ const clean = stripYamlComment(rawLines[i]).trimStart();
1405
+ const afterDash = clean.startsWith('- ') ? clean.slice(2).trimStart() : clean;
1406
+ const kv = splitKeyValue(afterDash);
1407
+ if (kv && kv.key === 'id' && unquoteYamlScalar(kv.val) === entryId) {
1408
+ idLineIdx = i;
1409
+ break;
1410
+ }
1411
+ }
1412
+ if (idLineIdx === -1) {
1413
+ return { ok: false, error: `未找到 MCP ${entryId} 的 id 定义行` };
1414
+ }
1415
+
1416
+ const idLine = rawLines[idLineIdx];
1417
+ const idCleanTrim = idLine.trimStart();
1418
+ const idBaseIndent = idLine.length - idCleanTrim.length;
1419
+ const idIsListItem = idCleanTrim.startsWith('- ');
1420
+ const propIndent = idIsListItem ? idBaseIndent + 2 : idBaseIndent;
1421
+
1422
+ let itemEnd = Math.min(blockEnd, rawLines.length - 1);
1423
+ if (idIsListItem) {
1424
+ for (let i = idLineIdx + 1; i <= itemEnd; i += 1) {
1425
+ const clean = stripYamlComment(rawLines[i]);
1426
+ if (!clean.trim()) continue;
1427
+ const ind = clean.length - clean.trimStart().length;
1428
+ if (ind < idBaseIndent || (ind === idBaseIndent && clean.trimStart().startsWith('- '))) {
1429
+ itemEnd = i - 1;
1430
+ break;
1431
+ }
1432
+ }
1433
+ }
1434
+
1435
+ let configLineIdx = -1;
1436
+ let cfgIndent = propIndent;
1437
+ for (let i = Math.min(blockStart, idLineIdx); i <= itemEnd; i += 1) {
1438
+ if (!idIsListItem && i < blockStart) continue;
1439
+ if (idIsListItem && i <= idLineIdx) continue;
1440
+ const clean = stripYamlComment(rawLines[i]);
1441
+ if (!clean.trim()) continue;
1442
+ const ind = clean.length - clean.trimStart().length;
1443
+ const kv = splitKeyValue(clean.trimStart());
1444
+ if (kv && kv.key === 'config' && ind >= propIndent - 2 && ind <= propIndent + 2) {
1445
+ configLineIdx = i;
1446
+ cfgIndent = ind;
1447
+ break;
1448
+ }
1449
+ }
1450
+
1451
+ const preSnap = createSnapshot(
1452
+ dshHome,
1453
+ profileName,
1454
+ 'auto-mcp',
1455
+ `调整 MCP ${entryId} 超时为 ${ms}ms 前自动快照`,
1456
+ );
1457
+
1458
+ if (configLineIdx !== -1) {
1459
+ let cfgSubEnd = configLineIdx;
1460
+ let timeoutLineIdx = -1;
1461
+ let childIndent = cfgIndent + 2;
1462
+ let lastNonEmptyInCfg = configLineIdx;
1463
+
1464
+ for (let i = configLineIdx + 1; i <= itemEnd; i += 1) {
1465
+ const clean = stripYamlComment(rawLines[i]);
1466
+ if (!clean.trim()) continue;
1467
+ const ind = clean.length - clean.trimStart().length;
1468
+ if (ind <= cfgIndent) break;
1469
+ cfgSubEnd = i;
1470
+ lastNonEmptyInCfg = i;
1471
+ const trimmed = clean.trimStart();
1472
+ if (!trimmed.startsWith('-')) {
1473
+ const kv = splitKeyValue(trimmed);
1474
+ if (kv) {
1475
+ if (childIndent === cfgIndent + 2 || ind < childIndent) {
1476
+ childIndent = ind;
1477
+ }
1478
+ if (kv.key === 'toolCallTimeoutMs' && ind === childIndent) {
1479
+ timeoutLineIdx = i;
1480
+ }
1481
+ }
1482
+ }
1483
+ }
1484
+
1485
+ if (timeoutLineIdx !== -1) {
1486
+ const orig = rawLines[timeoutLineIdx];
1487
+ const lead = (orig.match(/^(\s*)/) || ['', ' '.repeat(childIndent)])[1];
1488
+ const cleanNoComment = stripYamlComment(orig);
1489
+ const commentSuffix = orig.slice(cleanNoComment.length);
1490
+ rawLines[timeoutLineIdx] = `${lead}toolCallTimeoutMs: ${ms}${commentSuffix}`;
1491
+ } else {
1492
+ const insertAt = Math.max(configLineIdx + 1, lastNonEmptyInCfg + 1);
1493
+ rawLines.splice(insertAt, 0, `${' '.repeat(childIndent)}toolCallTimeoutMs: ${ms}`);
1494
+ }
1495
+ } else {
1496
+ let insertAt = idLineIdx + 1;
1497
+ for (let i = idLineIdx; i <= itemEnd; i += 1) {
1498
+ if (rawLines[i].trim()) insertAt = i + 1;
1499
+ }
1500
+ rawLines.splice(
1501
+ insertAt,
1502
+ 0,
1503
+ `${' '.repeat(propIndent)}config:`,
1504
+ `${' '.repeat(propIndent + 2)}toolCallTimeoutMs: ${ms}`,
1505
+ );
1506
+ }
1507
+
1508
+ const finalBody = `${rawLines.join('\n').replace(/\n+$/, '')}\n`;
1509
+ atomicWriteText(patchPath, finalBody);
1510
+
1511
+ appendAuditEntry(dshHome, {
1512
+ action: 'mcp.timeout',
1513
+ target: profileName,
1514
+ summary: `调整 MCP ${entryId} toolCallTimeoutMs 为 ${ms}ms`,
1515
+ snapshotId: preSnap.snapshot.id,
1516
+ ok: true,
1517
+ });
1518
+
1519
+ return {
1520
+ ok: true,
1521
+ target: profileName,
1522
+ id: entryId,
1523
+ toolCallTimeoutMs: ms,
1524
+ preSnapshotId: preSnap.snapshot.id,
1525
+ patchPath,
1209
1526
  };
1210
1527
  }
1211
1528
 
@@ -1312,6 +1629,8 @@ function readSnapshotRecordsFromDir(rootDir, sourceKind, dshHome) {
1312
1629
  kind: manifest?.kind || manifest?.Kind || 'snapshot',
1313
1630
  reason: manifest?.reason || manifest?.Reason || '',
1314
1631
  createdAt,
1632
+ pinned: Boolean(manifest?.pinned ?? manifest?.Pinned),
1633
+ pinLabel: String(manifest?.pinLabel ?? manifest?.PinLabel ?? ''),
1315
1634
  itemCount: Number(manifest?.itemCount || manifest?.ItemCount || files.length),
1316
1635
  changedCount,
1317
1636
  restorableCount: files.filter((f) => f.restorableInPlugin).length,
@@ -1325,7 +1644,9 @@ export function inspectSnapshots(options = {}) {
1325
1644
  const dshHome = resolveDshHome(options.dshHome);
1326
1645
  const guard = options.guard || locateGuardInstallation(options);
1327
1646
  const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(50, options.limit)) : 10;
1328
- const targetFilter = options.target === 'web' || options.target === 'desktop' ? options.target : 'all';
1647
+ const targetFilter = options.target && options.target !== 'all'
1648
+ ? (normalizeProfileTarget(String(options.target)) || 'all')
1649
+ : 'all';
1329
1650
 
1330
1651
  const isolateGuardOnly = Boolean(options.guardHome && !options.dshHome && !process.env.DSH_HOME);
1331
1652
  const pluginRoot = getSnapshotsRoot(dshHome);
@@ -1380,9 +1701,10 @@ export function restoreSnapshotConfig(dshHome, guard, snapshotId) {
1380
1701
  };
1381
1702
  }
1382
1703
 
1704
+ const preSnapTarget = snap.target === 'all' ? 'all' : (resolveTargetProfile(snap.target) || 'web');
1383
1705
  const preSnap = createSnapshot(
1384
1706
  dshHome,
1385
- snap.target === 'desktop' || snap.target === 'all' ? snap.target : 'web',
1707
+ preSnapTarget,
1386
1708
  'pre-restore',
1387
1709
  `恢复快照 ${id} 前自动备份`,
1388
1710
  );
@@ -1418,6 +1740,14 @@ export function restoreSnapshotConfig(dshHome, guard, snapshotId) {
1418
1740
  restoredFiles.push(f.relPath);
1419
1741
  }
1420
1742
 
1743
+ appendAuditEntry(dshHome, {
1744
+ action: 'snapshot.restore',
1745
+ target: preSnapTarget,
1746
+ summary: `从快照 ${id} 恢复 ${restoredFiles.length} 个配置文件`,
1747
+ snapshotId: preSnap.snapshot.id,
1748
+ ok: restoredFiles.length > 0,
1749
+ });
1750
+
1421
1751
  return {
1422
1752
  ok: restoredFiles.length > 0,
1423
1753
  snapshotId: id,
@@ -1430,42 +1760,37 @@ export function restoreSnapshotConfig(dshHome, guard, snapshotId) {
1430
1760
  export function inspectHealth(options = {}) {
1431
1761
  const dshHome = resolveDshHome(options.dshHome);
1432
1762
  const guard = locateGuardInstallation(options);
1433
- const web = inspectProfile(dshHome, 'web');
1434
- const desktop = inspectProfile(dshHome, 'desktop');
1763
+ const activeProfile =
1764
+ normalizeProfileTarget(options.activeProfile || (options.target && options.target !== 'all' ? options.target : null)) ||
1765
+ detectActiveProfile({ ctx: options.ctx, dshHome });
1766
+
1767
+ const profile = inspectProfile(dshHome, activeProfile);
1768
+ const ext = inspectExtensions(dshHome, activeProfile, guard);
1769
+ const profiles = { [activeProfile]: profile };
1770
+ const extensions = { [activeProfile]: ext };
1771
+ const referencedEnvSet = new Set(profile.referencedEnvKeys || []);
1772
+
1435
1773
  const credentials = inspectCredentialKeysMasked(dshHome);
1436
- const providers = inspectProviders(dshHome);
1437
- const extensionsWeb = inspectExtensions(dshHome, 'web', guard);
1438
- const extensionsDesktop = inspectExtensions(dshHome, 'desktop', guard);
1439
- const snapshots = inspectSnapshots({ dshHome, guard, limit: 8 });
1774
+ const providers = inspectProviders(dshHome, activeProfile);
1775
+ const snapshots = inspectSnapshots({ dshHome, guard, target: activeProfile, limit: 15 });
1440
1776
 
1441
1777
  const readyKeySet = new Set(credentials.keys.filter((k) => k.present || k.envSet).map((k) => k.key));
1442
- const referencedEnvSet = new Set([...(web.referencedEnvKeys || []), ...(desktop.referencedEnvKeys || [])]);
1443
1778
  const missingReferencedKeys = Array.from(referencedEnvSet).filter((k) => !readyKeySet.has(k));
1444
1779
  credentials.missingReferencedKeys = missingReferencedKeys;
1445
1780
 
1781
+ const trackTitle = activeProfile === 'desktop' ? '桌面端' : 'Web 端';
1446
1782
  const issues = [];
1447
1783
  if (!fs.existsSync(dshHome)) {
1448
1784
  issues.push(`未找到 DSH 目录: ${dshHome}`);
1449
1785
  }
1450
- if (web.missingBundles && web.missingBundles.length > 0) {
1451
- issues.push(`web 存在未在 dependencies 注册的 bundle: ${web.missingBundles.join(', ')}`);
1786
+ if (!profile.exists) {
1787
+ issues.push(`未找到 ${trackTitle} (${activeProfile}) 运行档案目录`);
1452
1788
  }
1453
- if (desktop.missingBundles && desktop.missingBundles.length > 0) {
1454
- issues.push(`desktop 存在未在 dependencies 注册的 bundle: ${desktop.missingBundles.join(', ')}`);
1789
+ if (profile.missingBundles && profile.missingBundles.length > 0) {
1790
+ issues.push(`${trackTitle}存在未在 dependencies 注册的 bundle: ${profile.missingBundles.join(', ')}`);
1455
1791
  }
1456
- if (web.exists && desktop.exists) {
1457
- if (web.patchHash && desktop.patchHash && web.patchHash !== desktop.patchHash) {
1458
- issues.push('web 和 desktop 的 cordis.patch.yml 存在配置漂移');
1459
- }
1460
- if (web.totalDependencies !== desktop.totalDependencies) {
1461
- issues.push(`依赖数量差异: web=${web.totalDependencies}, desktop=${desktop.totalDependencies}`);
1462
- }
1463
- }
1464
- if (web.brokenLinkCount > 0) {
1465
- issues.push(`web 存在 ${web.brokenLinkCount} 个断裂依赖软链接`);
1466
- }
1467
- if (desktop.brokenLinkCount > 0) {
1468
- issues.push(`desktop 存在 ${desktop.brokenLinkCount} 个断裂依赖软链接`);
1792
+ if (profile.brokenLinkCount > 0) {
1793
+ issues.push(`${trackTitle}存在 ${profile.brokenLinkCount} 个断裂依赖软链接`);
1469
1794
  }
1470
1795
  if (!credentials.present) {
1471
1796
  issues.push('.credentials.yaml 尚未初始化');
@@ -1474,24 +1799,34 @@ export function inspectHealth(options = {}) {
1474
1799
  issues.push(`配置中引用的凭据键缺失: ${missingReferencedKeys.join(', ')}`);
1475
1800
  }
1476
1801
 
1802
+ const contextAudit = inspectContextAudit(
1803
+ dshHome,
1804
+ { activeProfile, profile, profiles, extensions },
1805
+ activeProfile,
1806
+ { agentsHome: options.agentsHome },
1807
+ );
1808
+ const auditLog = readAuditLog(dshHome, 20);
1809
+
1477
1810
  return {
1478
1811
  companionVersion: PACKAGE_VERSION,
1479
1812
  checkedAt: new Date().toISOString(),
1480
1813
  platform: process.platform,
1481
1814
  dshHome,
1482
1815
  dshHomeExists: fs.existsSync(dshHome),
1816
+ activeProfile,
1817
+ profileNames: [activeProfile],
1818
+ profile,
1483
1819
  healthy: issues.length === 0,
1484
1820
  issuesCount: issues.length,
1485
1821
  issues,
1486
1822
  driftWarnings: issues,
1487
1823
  guard,
1488
- profiles: { web, desktop },
1824
+ profiles,
1489
1825
  credentials,
1490
1826
  providers,
1491
- extensions: {
1492
- web: extensionsWeb,
1493
- desktop: extensionsDesktop,
1494
- },
1827
+ extensions,
1828
+ contextAudit,
1829
+ auditLog,
1495
1830
  snapshots,
1496
1831
  };
1497
1832
  }
@@ -1569,23 +1904,27 @@ export function openGuard(options = {}) {
1569
1904
  }
1570
1905
 
1571
1906
  export function formatHealthText(report) {
1572
- const web = report.profiles.web;
1573
- const desk = report.profiles.desktop;
1574
1907
  const cred = report.credentials;
1575
1908
  const provCount = Array.isArray(report.providers) ? report.providers.length : 0;
1576
- const mcpCount = (report.extensions?.web?.mcpServers?.length || 0);
1909
+ const activeName = normalizeProfileTarget(report.activeProfile) || report.profileNames?.[0] || 'web';
1910
+ const p = report.profile || report.profiles?.[activeName];
1911
+ const mcpCount = report.extensions?.[activeName]?.mcpServers?.length || 0;
1577
1912
  const lines = [
1578
1913
  `[dsh-guard v${report.companionVersion}] DSH Home: ${report.dshHome} (${report.dshHomeExists ? '已找到' : '未找到'})`,
1579
1914
  `桌面端: ${report.guard.installed ? `已安装 (${report.guard.exePath})` : report.platform === 'win32' ? '未检测到本地 DSHGuard.exe(非必需,插件功能可独立运行)' : `${report.platform}(原生桌面端仅限 Windows)`}`,
1580
- `Web 档案: ${web.exists ? `${web.totalDependencies} 依赖(第三方 ${web.thirdPartyCount}),MCP ${mcpCount},断链 ${web.brokenLinkCount},patch=${web.patchHash || '无'}` : '未找到'}`,
1581
- `桌面档案: ${desk.exists ? `${desk.totalDependencies} 依赖(第三方 ${desk.thirdPartyCount}),断链 ${desk.brokenLinkCount},patch=${desk.patchHash || '无'}` : '未找到'}`,
1582
- `凭据与模型: ${cred.present ? `${cred.count} 个密钥引用(含 ${cred.protectedCount} 保护账号)` : '未找到 .credentials.yaml'} · ${provCount} 个模型提供商`,
1583
- `快照: 共 ${report.snapshots.total} 份`,
1915
+ `当前运行端 (${activeName}): ${p?.exists ? `${p.totalDependencies} 依赖(第三方 ${p.thirdPartyCount}),MCP ${mcpCount},断链 ${p.brokenLinkCount},patch=${p.patchHash || '无'}` : '未找到'}`,
1584
1916
  ];
1917
+ const ctxSummary = report.contextAudit
1918
+ ? ` · 技能 ${report.contextAudit.skills?.modelVisibleCount || 0}/${report.contextAudit.skills?.total || 0}(模型可见)`
1919
+ : '';
1920
+ lines.push(
1921
+ `凭据与模型: ${cred.present ? `${cred.count} 个密钥引用(含 ${cred.protectedCount} 保护账号)` : '未找到 .credentials.yaml'} · ${provCount} 个模型提供商${ctxSummary}`,
1922
+ );
1923
+ lines.push(`快照: 共 ${report.snapshots.total} 份`);
1585
1924
  if (report.driftWarnings.length > 0) {
1586
1925
  lines.push(`提示: ${report.driftWarnings.join(';')}`);
1587
1926
  } else {
1588
- lines.push('状态: web/desktop 结构一致且无断链。');
1927
+ lines.push(`状态: ${activeName} 档案结构健康且无断链。`);
1589
1928
  }
1590
1929
  return lines.join('\n');
1591
1930
  }
@@ -1601,8 +1940,23 @@ export function formatSnapshotsText(snapReport) {
1601
1940
  }
1602
1941
  for (const s of snapReport.snapshots) {
1603
1942
  const srcTag = s.source === 'desktop' ? '桌面端' : '插件';
1943
+ const pinTag = s.pinned ? '📌 ' : '';
1604
1944
  const diffTag = s.changedCount > 0 ? ` · 与磁盘有 ${s.changedCount} 处差异` : '';
1605
- lines.push(`- ${s.id} [${srcTag}/${s.target}/${s.kind}]${s.reason ? ` (${s.reason})` : ''} · ${s.itemCount} 文件${diffTag}`);
1945
+ lines.push(`- ${pinTag}${s.id} [${srcTag}/${s.target}/${s.kind}]${s.reason ? ` (${s.reason})` : ''} · ${s.itemCount} 文件${diffTag}`);
1606
1946
  }
1607
1947
  return lines.join('\n');
1608
1948
  }
1949
+
1950
+ export {
1951
+ detectActiveProfile,
1952
+ discoverProfiles,
1953
+ formatContextAuditText,
1954
+ formatMcpProbeText,
1955
+ inspectContextAudit,
1956
+ inspectSkills,
1957
+ normalizeProfileTarget,
1958
+ probeMcpServers,
1959
+ readAuditLog,
1960
+ toggleSkillVisibility,
1961
+ validateProfileName,
1962
+ };