@gluztm/dsh-guard 2.4.1 → 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/README.en.md +38 -58
- package/README.md +41 -60
- package/bin/dsh-guard.mjs +160 -47
- package/lib/client.js +1942 -1103
- package/lib/governance.mjs +994 -0
- package/lib/index.mjs +396 -53
- package/lib/inspector.mjs +1820 -429
- package/package.json +7 -3
- package/screenshots.json +1 -1
package/lib/inspector.mjs
CHANGED
|
@@ -1,571 +1,1962 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
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';
|
|
5
21
|
|
|
6
|
-
export const PACKAGE_VERSION = '2.4.
|
|
7
|
-
export const
|
|
8
|
-
export const
|
|
9
|
-
export const
|
|
22
|
+
export const PACKAGE_VERSION = '2.4.4';
|
|
23
|
+
export const DESKTOP_RELEASE_VERSION = '2.4.3';
|
|
24
|
+
export const REPO_URL = 'https://github.com/gluztm/DSHGuard';
|
|
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`;
|
|
10
27
|
|
|
11
|
-
const
|
|
12
|
-
const
|
|
28
|
+
const SELF_PLUGIN_NAME = '@gluztm/dsh-guard';
|
|
29
|
+
const SELF_LOADER_IDS = new Set(['dsh-guard', SELF_PLUGIN_NAME]);
|
|
30
|
+
const MCP_CLIENT_PKG = '@deepseek-ai/dsh-mcp-client';
|
|
31
|
+
const LLM_PLUGIN_IDS = new Set(['llm-pi-ai', '@deepseek-ai/dsh-llm-pi-ai']);
|
|
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)$/;
|
|
34
|
+
const SNAPSHOT_SAFE_EXT_RE = /\.(?:ya?ml|json)$/i;
|
|
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
|
+
}
|
|
42
|
+
|
|
43
|
+
function safeReadText(filePath) {
|
|
44
|
+
try {
|
|
45
|
+
return fs.readFileSync(filePath, 'utf8');
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function safeReadJson(filePath) {
|
|
52
|
+
const raw = safeReadText(filePath);
|
|
53
|
+
if (!raw) return null;
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(raw);
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sha256Text(text) {
|
|
62
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function sha256File(filePath) {
|
|
66
|
+
try {
|
|
67
|
+
const buf = fs.readFileSync(filePath);
|
|
68
|
+
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
13
73
|
|
|
14
74
|
export function resolveDshHome(overrideHome) {
|
|
15
75
|
if (overrideHome && String(overrideHome).trim()) {
|
|
16
|
-
return resolve(String(overrideHome).trim())
|
|
76
|
+
return path.resolve(String(overrideHome).trim());
|
|
17
77
|
}
|
|
18
78
|
if (process.env.DSH_HOME && process.env.DSH_HOME.trim()) {
|
|
19
|
-
return resolve(process.env.DSH_HOME.trim())
|
|
79
|
+
return path.resolve(process.env.DSH_HOME.trim());
|
|
20
80
|
}
|
|
21
|
-
return join(homedir(), '.dsh')
|
|
81
|
+
return path.join(os.homedir(), '.dsh');
|
|
22
82
|
}
|
|
23
83
|
|
|
24
|
-
function
|
|
25
|
-
if (process.platform !== 'win32') return null
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
84
|
+
function readRegistryInstallLocation() {
|
|
85
|
+
if (process.platform !== 'win32') return null;
|
|
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' },
|
|
92
|
+
];
|
|
93
|
+
for (const { key, valueName } of regQueries) {
|
|
94
|
+
try {
|
|
95
|
+
const out = execFileSync('reg.exe', ['query', key, '/v', valueName], {
|
|
96
|
+
encoding: 'utf8',
|
|
97
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
98
|
+
timeout: 1500,
|
|
99
|
+
});
|
|
100
|
+
const match = new RegExp(`${valueName}\\s+REG_\\w+\\s+(.+)`, 'i').exec(out);
|
|
101
|
+
if (match && match[1]) {
|
|
102
|
+
const dir = match[1].trim().replace(/[\\/]+$/, '');
|
|
103
|
+
if (dir) return dir;
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// Registry key absent on this machine.
|
|
36
107
|
}
|
|
37
|
-
} catch {
|
|
38
|
-
return null
|
|
39
108
|
}
|
|
40
|
-
return null
|
|
109
|
+
return null;
|
|
41
110
|
}
|
|
42
111
|
|
|
43
|
-
/**
|
|
44
|
-
* Locate local DSHGuard out-of-band installation (strictly read-only).
|
|
45
|
-
*/
|
|
46
112
|
export function locateGuardInstallation(options = {}) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
113
|
+
if (options.disableLookup) {
|
|
114
|
+
return {
|
|
115
|
+
installed: false,
|
|
116
|
+
platform: process.platform,
|
|
117
|
+
exePath: null,
|
|
118
|
+
guardHome: null,
|
|
119
|
+
configDir: null,
|
|
120
|
+
snapshotsDir: null,
|
|
121
|
+
dataDir: null,
|
|
122
|
+
via: null,
|
|
123
|
+
releaseUrl: RELEASE_URL,
|
|
124
|
+
installerUrl: INSTALLER_URL,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
57
127
|
|
|
58
|
-
|
|
59
|
-
|
|
128
|
+
const candidates = [];
|
|
129
|
+
const pushCandidate = (dir, via) => {
|
|
130
|
+
if (!dir) return;
|
|
131
|
+
const resolved = path.resolve(dir);
|
|
132
|
+
candidates.push({ exe: path.join(resolved, 'DSHGuard.exe'), home: resolved, via });
|
|
133
|
+
};
|
|
60
134
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
135
|
+
if (options.guardHome) {
|
|
136
|
+
pushCandidate(options.guardHome, 'option');
|
|
137
|
+
}
|
|
138
|
+
if (process.env.DSHGUARD_HOME) {
|
|
139
|
+
pushCandidate(process.env.DSHGUARD_HOME, 'env:DSHGUARD_HOME');
|
|
65
140
|
}
|
|
66
141
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const exeCandidate = join(dir, 'DSHGuard.exe')
|
|
74
|
-
const snapCandidate = options.snapshotsDir ? resolve(String(options.snapshotsDir)) : join(dir, 'Snapshots')
|
|
75
|
-
if (existsSync(exeCandidate) || existsSync(snapCandidate)) {
|
|
76
|
-
matchedHome = dir
|
|
77
|
-
if (existsSync(exeCandidate)) matchedExe = exeCandidate
|
|
78
|
-
if (existsSync(snapCandidate)) matchedSnapshots = snapCandidate
|
|
79
|
-
break
|
|
142
|
+
if (process.platform === 'win32' && !options.guardHome) {
|
|
143
|
+
const regDir = readRegistryInstallLocation();
|
|
144
|
+
if (regDir) pushCandidate(regDir, 'registry');
|
|
145
|
+
if (process.env.LOCALAPPDATA) {
|
|
146
|
+
pushCandidate(path.join(process.env.LOCALAPPDATA, 'Programs', 'DSHGuard'), 'localappdata');
|
|
147
|
+
pushCandidate(path.join(process.env.LOCALAPPDATA, 'DSHGuard'), 'localappdata-root');
|
|
80
148
|
}
|
|
149
|
+
pushCandidate('D:\\Applications\\DSHGuard', 'default-d-apps');
|
|
150
|
+
pushCandidate('C:\\Program Files\\DSHGuard', 'program-files');
|
|
81
151
|
}
|
|
82
152
|
|
|
83
|
-
|
|
84
|
-
|
|
153
|
+
for (const item of candidates) {
|
|
154
|
+
if (fs.existsSync(item.exe)) {
|
|
155
|
+
const guardHome = path.dirname(item.exe);
|
|
156
|
+
const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
157
|
+
const dataCandidates = [
|
|
158
|
+
path.join(guardHome, 'Snapshots'),
|
|
159
|
+
path.join(localAppData, 'DSHGuard', 'Snapshots'),
|
|
160
|
+
];
|
|
161
|
+
const snapshotsDir = dataCandidates.find((d) => fs.existsSync(d)) || dataCandidates[0];
|
|
162
|
+
const configDir = path.join(guardHome, 'Config');
|
|
163
|
+
return {
|
|
164
|
+
installed: true,
|
|
165
|
+
platform: process.platform,
|
|
166
|
+
exePath: item.exe,
|
|
167
|
+
guardHome,
|
|
168
|
+
configDir: fs.existsSync(configDir) ? configDir : null,
|
|
169
|
+
snapshotsDir,
|
|
170
|
+
dataDir: path.dirname(snapshotsDir),
|
|
171
|
+
via: item.via,
|
|
172
|
+
releaseUrl: RELEASE_URL,
|
|
173
|
+
installerUrl: INSTALLER_URL,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
85
176
|
}
|
|
86
177
|
|
|
87
178
|
return {
|
|
88
|
-
installed:
|
|
89
|
-
|
|
90
|
-
exePath:
|
|
91
|
-
|
|
179
|
+
installed: false,
|
|
180
|
+
platform: process.platform,
|
|
181
|
+
exePath: null,
|
|
182
|
+
guardHome: null,
|
|
183
|
+
configDir: null,
|
|
184
|
+
snapshotsDir: null,
|
|
185
|
+
dataDir: null,
|
|
186
|
+
via: null,
|
|
92
187
|
releaseUrl: RELEASE_URL,
|
|
93
188
|
installerUrl: INSTALLER_URL,
|
|
94
|
-
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function unquoteYamlScalar(raw) {
|
|
193
|
+
const s = String(raw || '').trim();
|
|
194
|
+
if (!s) return '';
|
|
195
|
+
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
|
196
|
+
const inner = s.slice(1, -1);
|
|
197
|
+
if (s.startsWith('"')) {
|
|
198
|
+
return inner.replace(/\\"/g, '"').replace(/\\\\/g, '\\').replace(/\\n/g, '\n');
|
|
199
|
+
}
|
|
200
|
+
return inner.replace(/''/g, "'");
|
|
95
201
|
}
|
|
202
|
+
return s;
|
|
96
203
|
}
|
|
97
204
|
|
|
98
|
-
function
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
205
|
+
function stripYamlComment(line) {
|
|
206
|
+
let inSingle = false;
|
|
207
|
+
let inDouble = false;
|
|
208
|
+
let escaped = false;
|
|
209
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
210
|
+
const ch = line[i];
|
|
211
|
+
if (escaped) {
|
|
212
|
+
escaped = false;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (inDouble && ch === '\\') {
|
|
216
|
+
escaped = true;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (ch === "'" && !inDouble) {
|
|
220
|
+
inSingle = !inSingle;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (ch === '"' && !inSingle) {
|
|
224
|
+
inDouble = !inDouble;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (ch === '#' && !inSingle && !inDouble) {
|
|
228
|
+
if (i === 0 || /\s/.test(line[i - 1])) {
|
|
229
|
+
return line.slice(0, i).replace(/\s+$/, '');
|
|
230
|
+
}
|
|
231
|
+
}
|
|
104
232
|
}
|
|
233
|
+
return line.replace(/\s+$/, '');
|
|
105
234
|
}
|
|
106
235
|
|
|
107
|
-
function
|
|
108
|
-
|
|
109
|
-
|
|
236
|
+
function splitKeyValue(trimmed) {
|
|
237
|
+
let inSingle = false;
|
|
238
|
+
let inDouble = false;
|
|
239
|
+
let escaped = false;
|
|
240
|
+
for (let i = 0; i < trimmed.length; i += 1) {
|
|
241
|
+
const ch = trimmed[i];
|
|
242
|
+
if (escaped) {
|
|
243
|
+
escaped = false;
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (inDouble && ch === '\\') {
|
|
247
|
+
escaped = true;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (ch === "'" && !inDouble) {
|
|
251
|
+
inSingle = !inSingle;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (ch === '"' && !inSingle) {
|
|
255
|
+
inDouble = !inDouble;
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if (ch === ':' && !inSingle && !inDouble) {
|
|
259
|
+
const next = trimmed[i + 1];
|
|
260
|
+
if (next === undefined || /\s/.test(next)) {
|
|
261
|
+
const key = unquoteYamlScalar(trimmed.slice(0, i).trim());
|
|
262
|
+
const val = trimmed.slice(i + 1).trim();
|
|
263
|
+
return { key, val };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
110
266
|
}
|
|
111
|
-
|
|
112
|
-
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function parseSimpleScalar(rawVal) {
|
|
271
|
+
const s = String(rawVal || '').trim();
|
|
272
|
+
if (!s) return undefined;
|
|
273
|
+
if (s === 'true') return true;
|
|
274
|
+
if (s === 'false') return false;
|
|
275
|
+
if (s === 'null' || s === '~') return null;
|
|
276
|
+
if (/^!!js\b/.test(s)) return { __jsTag: s };
|
|
277
|
+
if (/^-?\d+(?:\.\d+)?$/.test(s)) return Number(s);
|
|
278
|
+
if ((s.startsWith('[') && s.endsWith(']')) || (s.startsWith('{') && s.endsWith('}'))) {
|
|
279
|
+
try {
|
|
280
|
+
return JSON.parse(s.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, '"$1"'));
|
|
281
|
+
} catch {
|
|
282
|
+
return s;
|
|
283
|
+
}
|
|
113
284
|
}
|
|
114
|
-
return
|
|
285
|
+
return unquoteYamlScalar(s);
|
|
115
286
|
}
|
|
116
287
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
288
|
+
/**
|
|
289
|
+
* Indentation-driven lightweight YAML parser tailored for Cordis cordis.patch.yml / cordis.yml.
|
|
290
|
+
* Preserves top-level patch structure (`- insert:` and `- id:`) without executing YAML tags.
|
|
291
|
+
*/
|
|
292
|
+
function parseYamlStructure(text) {
|
|
293
|
+
if (!text) return [];
|
|
294
|
+
const rawLines = text.replace(/\r\n/g, '\n').split('\n');
|
|
295
|
+
const tokens = [];
|
|
296
|
+
for (let idx = 0; idx < rawLines.length; idx += 1) {
|
|
297
|
+
const clean = stripYamlComment(rawLines[idx]);
|
|
298
|
+
if (!clean.trim()) continue;
|
|
299
|
+
const indent = clean.length - clean.trimStart().length;
|
|
300
|
+
tokens.push({ lineIdx: idx, indent, text: clean.trimStart(), raw: rawLines[idx] });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
let cursor = 0;
|
|
304
|
+
|
|
305
|
+
function parseBlock(minIndent) {
|
|
306
|
+
if (cursor >= tokens.length) return null;
|
|
307
|
+
const first = tokens[cursor];
|
|
308
|
+
if (first.indent < minIndent) return null;
|
|
309
|
+
if (first.text === '-' || first.text.startsWith('- ')) {
|
|
310
|
+
return parseSequence(first.indent);
|
|
311
|
+
}
|
|
312
|
+
return parseMapping(first.indent);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function parseSequence(seqIndent) {
|
|
316
|
+
const arr = [];
|
|
317
|
+
while (cursor < tokens.length) {
|
|
318
|
+
const tok = tokens[cursor];
|
|
319
|
+
if (tok.indent < seqIndent) break;
|
|
320
|
+
if (tok.indent !== seqIndent || !(tok.text === '-' || tok.text.startsWith('- '))) break;
|
|
321
|
+
const startLine = tok.lineIdx;
|
|
322
|
+
const afterDash = tok.text === '-' ? '' : tok.text.slice(2).trimStart();
|
|
323
|
+
cursor += 1;
|
|
324
|
+
|
|
325
|
+
if (!afterDash) {
|
|
326
|
+
const val = cursor < tokens.length && tokens[cursor].indent > seqIndent
|
|
327
|
+
? parseBlock(seqIndent + 1)
|
|
328
|
+
: null;
|
|
329
|
+
if (val && typeof val === 'object' && !Array.isArray(val)) {
|
|
330
|
+
val.__lineRange = [startLine, cursor > 0 ? tokens[cursor - 1].lineIdx : startLine];
|
|
331
|
+
}
|
|
332
|
+
arr.push(val);
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const kv = splitKeyValue(afterDash);
|
|
337
|
+
if (kv) {
|
|
338
|
+
const obj = {};
|
|
339
|
+
const itemIndent = seqIndent + 2;
|
|
340
|
+
if (kv.val === '|' || kv.val === '>') {
|
|
341
|
+
const lines = [];
|
|
342
|
+
while (cursor < tokens.length && tokens[cursor].indent >= itemIndent + 1) {
|
|
343
|
+
lines.push(tokens[cursor].text);
|
|
344
|
+
cursor += 1;
|
|
345
|
+
}
|
|
346
|
+
obj[kv.key] = lines.join('\n');
|
|
347
|
+
} else if (!kv.val) {
|
|
348
|
+
if (cursor < tokens.length && tokens[cursor].indent > seqIndent) {
|
|
349
|
+
// Handle `- insert:` followed by same-indent `- ...` or deeper indent mapping/list
|
|
350
|
+
obj[kv.key] = parseBlock(seqIndent + 1);
|
|
351
|
+
} else {
|
|
352
|
+
obj[kv.key] = null;
|
|
353
|
+
}
|
|
354
|
+
} else {
|
|
355
|
+
obj[kv.key] = parseSimpleScalar(kv.val);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
while (cursor < tokens.length) {
|
|
359
|
+
const next = tokens[cursor];
|
|
360
|
+
if (next.indent < itemIndent) break;
|
|
361
|
+
if (next.indent === seqIndent && (next.text === '-' || next.text.startsWith('- '))) break;
|
|
362
|
+
if (next.indent > itemIndent && !splitKeyValue(next.text)) {
|
|
363
|
+
cursor += 1;
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
if (next.indent === itemIndent) {
|
|
367
|
+
const subKv = splitKeyValue(next.text);
|
|
368
|
+
if (!subKv) {
|
|
369
|
+
cursor += 1;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
cursor += 1;
|
|
373
|
+
if (subKv.val === '|' || subKv.val === '>') {
|
|
374
|
+
const lines = [];
|
|
375
|
+
while (cursor < tokens.length && tokens[cursor].indent > itemIndent) {
|
|
376
|
+
lines.push(tokens[cursor].text);
|
|
377
|
+
cursor += 1;
|
|
378
|
+
}
|
|
379
|
+
obj[subKv.key] = lines.join('\n');
|
|
380
|
+
} else if (!subKv.val) {
|
|
381
|
+
obj[subKv.key] = cursor < tokens.length && tokens[cursor].indent > itemIndent
|
|
382
|
+
? parseBlock(itemIndent + 1)
|
|
383
|
+
: null;
|
|
384
|
+
} else {
|
|
385
|
+
obj[subKv.key] = parseSimpleScalar(subKv.val);
|
|
386
|
+
}
|
|
387
|
+
} else {
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
obj.__lineRange = [startLine, cursor > 0 ? tokens[cursor - 1].lineIdx : startLine];
|
|
392
|
+
arr.push(obj);
|
|
393
|
+
} else {
|
|
394
|
+
arr.push(parseSimpleScalar(afterDash));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return arr;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function parseMapping(mapIndent) {
|
|
401
|
+
const obj = {};
|
|
402
|
+
while (cursor < tokens.length) {
|
|
403
|
+
const tok = tokens[cursor];
|
|
404
|
+
if (tok.indent < mapIndent) break;
|
|
405
|
+
if (tok.indent !== mapIndent) break;
|
|
406
|
+
if (tok.text === '-' || tok.text.startsWith('- ')) break;
|
|
407
|
+
const kv = splitKeyValue(tok.text);
|
|
408
|
+
if (!kv) {
|
|
409
|
+
cursor += 1;
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
cursor += 1;
|
|
413
|
+
if (kv.val === '|' || kv.val === '>') {
|
|
414
|
+
const lines = [];
|
|
415
|
+
while (cursor < tokens.length && tokens[cursor].indent > mapIndent) {
|
|
416
|
+
lines.push(tokens[cursor].text);
|
|
417
|
+
cursor += 1;
|
|
418
|
+
}
|
|
419
|
+
obj[kv.key] = lines.join('\n');
|
|
420
|
+
} else if (!kv.val) {
|
|
421
|
+
if (cursor < tokens.length) {
|
|
422
|
+
const nxt = tokens[cursor];
|
|
423
|
+
if (nxt.indent > mapIndent || (nxt.indent === mapIndent && (nxt.text === '-' || nxt.text.startsWith('- ')))) {
|
|
424
|
+
obj[kv.key] = parseBlock(nxt.indent);
|
|
425
|
+
} else {
|
|
426
|
+
obj[kv.key] = null;
|
|
427
|
+
}
|
|
428
|
+
} else {
|
|
429
|
+
obj[kv.key] = null;
|
|
430
|
+
}
|
|
431
|
+
} else {
|
|
432
|
+
obj[kv.key] = parseSimpleScalar(kv.val);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return obj;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const parsed = parseBlock(0);
|
|
439
|
+
return parsed ?? [];
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function collectPatchNodes(parsed) {
|
|
443
|
+
const list = Array.isArray(parsed)
|
|
444
|
+
? parsed
|
|
445
|
+
: Array.isArray(parsed?.plugins)
|
|
446
|
+
? parsed.plugins
|
|
447
|
+
: [];
|
|
448
|
+
const entries = [];
|
|
449
|
+
for (const item of list) {
|
|
450
|
+
if (!item || typeof item !== 'object') continue;
|
|
451
|
+
if (item.insert !== undefined && item.insert !== null) {
|
|
452
|
+
const inserts = Array.isArray(item.insert) ? item.insert : [item.insert];
|
|
453
|
+
for (const ins of inserts) {
|
|
454
|
+
if (ins && typeof ins === 'object') {
|
|
455
|
+
entries.push({
|
|
456
|
+
kind: 'insert',
|
|
457
|
+
id: typeof ins.id === 'string' ? ins.id : null,
|
|
458
|
+
name: typeof ins.name === 'string' ? ins.name : null,
|
|
459
|
+
disabled: ins.disabled === true,
|
|
460
|
+
disabledRaw: ins.disabled,
|
|
461
|
+
config: ins.config && typeof ins.config === 'object' ? ins.config : {},
|
|
462
|
+
lineRange: ins.__lineRange || item.__lineRange || null,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
continue;
|
|
128
467
|
}
|
|
468
|
+
entries.push({
|
|
469
|
+
kind: 'override',
|
|
470
|
+
id: typeof item.id === 'string' ? item.id : null,
|
|
471
|
+
name: typeof item.name === 'string' ? item.name : null,
|
|
472
|
+
disabled: item.disabled === true,
|
|
473
|
+
disabledRaw: item.disabled,
|
|
474
|
+
hasConfig: item.config !== undefined,
|
|
475
|
+
config: item.config && typeof item.config === 'object' ? item.config : {},
|
|
476
|
+
keys: Object.keys(item).filter((k) => k !== '__lineRange'),
|
|
477
|
+
lineRange: item.__lineRange || null,
|
|
478
|
+
});
|
|
129
479
|
}
|
|
480
|
+
return entries;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export function quoteYamlId(id) {
|
|
484
|
+
const s = String(id || '');
|
|
485
|
+
if (!s) return '""';
|
|
486
|
+
const needsQuote =
|
|
487
|
+
/^(?:@|!|&|\*|\?|:|-|\[|\{|#|%|\||>|'|"|`)/.test(s) ||
|
|
488
|
+
/^(?:true|false|null|yes|no|on|off|~)$/i.test(s) ||
|
|
489
|
+
/^-?\d+(?:\.\d+)?$/.test(s) ||
|
|
490
|
+
/[:#\s]/.test(s) ||
|
|
491
|
+
/: /.test(s);
|
|
492
|
+
if (!needsQuote) return s;
|
|
493
|
+
return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export function findBrokenModuleLinks(profileDir) {
|
|
497
|
+
const nodeModulesDir = path.join(profileDir, 'node_modules');
|
|
498
|
+
const broken = [];
|
|
499
|
+
if (!fs.existsSync(nodeModulesDir)) return broken;
|
|
500
|
+
|
|
501
|
+
const inspectEntry = (pkgName, fullPath) => {
|
|
502
|
+
try {
|
|
503
|
+
const st = fs.lstatSync(fullPath);
|
|
504
|
+
if (!st.isSymbolicLink()) return;
|
|
505
|
+
let brokenTarget = null;
|
|
506
|
+
try {
|
|
507
|
+
brokenTarget = fs.readlinkSync(fullPath);
|
|
508
|
+
} catch {
|
|
509
|
+
brokenTarget = null;
|
|
510
|
+
}
|
|
511
|
+
if (!fs.existsSync(fullPath)) {
|
|
512
|
+
broken.push({ name: pkgName, linkPath: fullPath, brokenTarget });
|
|
513
|
+
}
|
|
514
|
+
} catch {
|
|
515
|
+
// Ignore unreadable entries.
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
let entries = [];
|
|
130
520
|
try {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
521
|
+
entries = fs.readdirSync(nodeModulesDir, { withFileTypes: true });
|
|
522
|
+
} catch {
|
|
523
|
+
return broken;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
for (const dirent of entries) {
|
|
527
|
+
const fullPath = path.join(nodeModulesDir, dirent.name);
|
|
528
|
+
if (dirent.name.startsWith('@') && !dirent.isSymbolicLink() && dirent.isDirectory()) {
|
|
529
|
+
try {
|
|
530
|
+
const scoped = fs.readdirSync(fullPath, { withFileTypes: true });
|
|
531
|
+
for (const sub of scoped) {
|
|
532
|
+
inspectEntry(`${dirent.name}/${sub.name}`, path.join(fullPath, sub.name));
|
|
533
|
+
}
|
|
534
|
+
} catch {
|
|
535
|
+
// Ignore unreadable scoped folder.
|
|
145
536
|
}
|
|
146
|
-
|
|
147
|
-
|
|
537
|
+
} else if (!dirent.name.startsWith('.')) {
|
|
538
|
+
inspectEntry(dirent.name, fullPath);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return broken;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function collectApiKeyEnvs(node, outSet, depth = 0) {
|
|
545
|
+
if (!node || typeof node !== 'object' || depth > 10) return;
|
|
546
|
+
if (Array.isArray(node)) {
|
|
547
|
+
for (const item of node) collectApiKeyEnvs(item, outSet, depth + 1);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
for (const [k, v] of Object.entries(node)) {
|
|
551
|
+
if (k === 'apiKeyEnv' && typeof v === 'string' && v.trim()) {
|
|
552
|
+
outSet.add(v.trim());
|
|
553
|
+
} else if (v && typeof v === 'object') {
|
|
554
|
+
collectApiKeyEnvs(v, outSet, depth + 1);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export function inspectProfile(dshHome, profileName) {
|
|
560
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
561
|
+
const exists = fs.existsSync(profileDir);
|
|
562
|
+
const pkgPath = path.join(profileDir, 'package.json');
|
|
563
|
+
const patchPath = path.join(profileDir, 'cordis.patch.yml');
|
|
564
|
+
const basePath = path.join(profileDir, 'cordis.yml');
|
|
565
|
+
const pkg = safeReadJson(pkgPath);
|
|
566
|
+
const patchText = safeReadText(patchPath);
|
|
567
|
+
const baseText = safeReadText(basePath);
|
|
568
|
+
const brokenLinks = exists ? findBrokenModuleLinks(profileDir) : [];
|
|
569
|
+
|
|
570
|
+
const deps = pkg && typeof pkg.dependencies === 'object' && pkg.dependencies ? Object.keys(pkg.dependencies) : [];
|
|
571
|
+
const depSet = new Set(deps);
|
|
572
|
+
const bundleNames = pkg?.dsh?.bundles && typeof pkg.dsh.bundles === 'object' ? Object.keys(pkg.dsh.bundles) : [];
|
|
573
|
+
const missingBundles = bundleNames.filter((b) => !depSet.has(b));
|
|
574
|
+
const thirdPartyDeps = deps.filter((name) => !name.startsWith('@deepseek-ai/'));
|
|
575
|
+
const parsedPatch = patchText ? parseYamlStructure(patchText) : null;
|
|
576
|
+
const patchEntries = parsedPatch ? collectPatchNodes(parsedPatch) : [];
|
|
577
|
+
const referencedEnvSet = new Set();
|
|
578
|
+
if (parsedPatch) collectApiKeyEnvs(parsedPatch, referencedEnvSet);
|
|
579
|
+
const mcpCount = patchEntries.filter((e) => e.kind === 'insert' && e.name === MCP_CLIENT_PKG).length;
|
|
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;
|
|
585
|
+
|
|
586
|
+
return {
|
|
587
|
+
name: profileName,
|
|
588
|
+
exists,
|
|
589
|
+
profileDir,
|
|
590
|
+
packageJsonPresent: Boolean(pkg),
|
|
591
|
+
totalDependencies: deps.length,
|
|
592
|
+
thirdPartyCount: thirdPartyDeps.length,
|
|
593
|
+
thirdPartyNames: thirdPartyDeps,
|
|
594
|
+
missingBundles,
|
|
595
|
+
referencedEnvKeys: Array.from(referencedEnvSet),
|
|
596
|
+
mcpCount,
|
|
597
|
+
disabledEntryCount: disabledOverrides.length,
|
|
598
|
+
brokenLinks,
|
|
599
|
+
brokenLinkCount: brokenLinks.length,
|
|
600
|
+
systemPromptChars,
|
|
601
|
+
patchPresent: patchText !== null,
|
|
602
|
+
patchHash: patchText !== null ? sha256Text(patchText).slice(0, 12) : null,
|
|
603
|
+
patchBytes: patchText !== null ? Buffer.byteLength(patchText, 'utf8') : 0,
|
|
604
|
+
basePresent: baseText !== null,
|
|
605
|
+
baseHash: baseText !== null ? sha256Text(baseText).slice(0, 12) : null,
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function parseCredentialRefsDocument(rawText) {
|
|
610
|
+
const lines = rawText ? rawText.replace(/\r\n/g, '\n').split('\n') : [];
|
|
611
|
+
let inRefs = false;
|
|
612
|
+
let refsStart = -1;
|
|
613
|
+
let refsEnd = -1;
|
|
614
|
+
const entries = [];
|
|
615
|
+
let current = null;
|
|
616
|
+
|
|
617
|
+
const flushCurrent = () => {
|
|
618
|
+
if (!current) return;
|
|
619
|
+
entries.push(current);
|
|
620
|
+
current = null;
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
624
|
+
const line = lines[i];
|
|
625
|
+
const trimmed = line.trim();
|
|
626
|
+
|
|
627
|
+
if (/^\S/.test(line) && !trimmed.startsWith('#')) {
|
|
628
|
+
if (inRefs) {
|
|
629
|
+
flushCurrent();
|
|
630
|
+
refsEnd = i;
|
|
631
|
+
inRefs = false;
|
|
148
632
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
633
|
+
if (/^refs:\s*(?:#.*)?$/.test(line)) {
|
|
634
|
+
inRefs = true;
|
|
635
|
+
refsStart = i;
|
|
636
|
+
} else if (/^refs:\s*\{\}\s*(?:#.*)?$/.test(line)) {
|
|
637
|
+
refsStart = i;
|
|
638
|
+
refsEnd = i + 1;
|
|
152
639
|
}
|
|
153
|
-
|
|
154
|
-
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
if (!inRefs) continue;
|
|
644
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
645
|
+
|
|
646
|
+
const indent = line.length - line.trimStart().length;
|
|
647
|
+
if (indent === 2 && !line.trimStart().startsWith('-')) {
|
|
648
|
+
const kv = splitKeyValue(line.trimStart());
|
|
649
|
+
if (kv && kv.key) {
|
|
650
|
+
flushCurrent();
|
|
651
|
+
const isProtectedAccount = /_ACCOUNT(?:_|$)/i.test(kv.key);
|
|
652
|
+
const val = kv.val;
|
|
653
|
+
const isBlock = val === '|' || val === '|-' || val === '|+' || val === '>' || val === '>-' || !val;
|
|
654
|
+
const present = isBlock ? true : val !== '""' && val !== "''" && val !== 'null' && val !== '~';
|
|
655
|
+
current = {
|
|
656
|
+
key: kv.key,
|
|
657
|
+
protected: isProtectedAccount,
|
|
658
|
+
present,
|
|
659
|
+
isMultiline: isBlock,
|
|
660
|
+
startLine: i,
|
|
661
|
+
endLine: i,
|
|
662
|
+
};
|
|
155
663
|
}
|
|
664
|
+
} else if (current && indent > 2) {
|
|
665
|
+
current.endLine = i;
|
|
666
|
+
current.isMultiline = true;
|
|
667
|
+
current.present = true;
|
|
156
668
|
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
if (inRefs) {
|
|
672
|
+
flushCurrent();
|
|
673
|
+
refsEnd = lines.length;
|
|
674
|
+
}
|
|
157
675
|
|
|
158
|
-
|
|
159
|
-
|
|
676
|
+
return { lines, refsStart, refsEnd, entries };
|
|
677
|
+
}
|
|
160
678
|
|
|
679
|
+
/**
|
|
680
|
+
* Inspect .credentials.yaml ONLY for key existence/readiness metadata.
|
|
681
|
+
* Never reads or returns any secret literal, preview, or prefix.
|
|
682
|
+
*/
|
|
683
|
+
export function inspectCredentialKeysMasked(dshHome) {
|
|
684
|
+
const credPath = path.join(dshHome, '.credentials.yaml');
|
|
685
|
+
if (!fs.existsSync(credPath)) {
|
|
161
686
|
return {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
687
|
+
present: false,
|
|
688
|
+
path: credPath,
|
|
689
|
+
count: 0,
|
|
690
|
+
protectedCount: 0,
|
|
691
|
+
keys: [],
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const raw = safeReadText(credPath);
|
|
696
|
+
if (raw === null) {
|
|
172
697
|
return {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
698
|
+
present: true,
|
|
699
|
+
unreadable: true,
|
|
700
|
+
path: credPath,
|
|
701
|
+
count: 0,
|
|
702
|
+
protectedCount: 0,
|
|
703
|
+
keys: [],
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const doc = parseCredentialRefsDocument(raw);
|
|
708
|
+
const seen = new Set();
|
|
709
|
+
const keys = [];
|
|
710
|
+
|
|
711
|
+
for (const entry of doc.entries) {
|
|
712
|
+
if (!entry.key || seen.has(entry.key)) continue;
|
|
713
|
+
seen.add(entry.key);
|
|
714
|
+
keys.push({
|
|
715
|
+
key: entry.key,
|
|
716
|
+
protected: entry.protected,
|
|
717
|
+
present: entry.present,
|
|
718
|
+
source: 'refs',
|
|
719
|
+
envSet: Boolean(process.env[entry.key]),
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// Fallback for flat legacy key: value files without refs: section
|
|
724
|
+
if (doc.refsStart === -1) {
|
|
725
|
+
for (const rawLine of doc.lines) {
|
|
726
|
+
const clean = stripYamlComment(rawLine);
|
|
727
|
+
if (!clean.trim() || /^\s/.test(clean) || clean.trimStart().startsWith('-')) continue;
|
|
728
|
+
const kv = splitKeyValue(clean.trim());
|
|
729
|
+
if (!kv || !kv.key || /^(?:version|records|refs)$/i.test(kv.key) || seen.has(kv.key)) continue;
|
|
730
|
+
seen.add(kv.key);
|
|
731
|
+
keys.push({
|
|
732
|
+
key: kv.key,
|
|
733
|
+
protected: /_ACCOUNT(?:_|$)/i.test(kv.key),
|
|
734
|
+
present: Boolean(kv.val && kv.val !== '""' && kv.val !== "''" && kv.val !== 'null'),
|
|
735
|
+
source: 'root',
|
|
736
|
+
envSet: Boolean(process.env[kv.key]),
|
|
737
|
+
});
|
|
181
738
|
}
|
|
182
739
|
}
|
|
740
|
+
|
|
741
|
+
const nonEmptyKeysCount = keys.filter((k) => k.present).length;
|
|
742
|
+
|
|
743
|
+
return {
|
|
744
|
+
present: true,
|
|
745
|
+
path: credPath,
|
|
746
|
+
count: keys.length,
|
|
747
|
+
nonEmptyKeysCount,
|
|
748
|
+
protectedCount: keys.filter((k) => k.protected).length,
|
|
749
|
+
missingReferencedKeys: [],
|
|
750
|
+
keys,
|
|
751
|
+
};
|
|
183
752
|
}
|
|
184
753
|
|
|
185
754
|
/**
|
|
186
|
-
*
|
|
755
|
+
* One-way secret write into ~/.dsh/.credentials.yaml `refs:` preserving `version`, `records`,
|
|
756
|
+
* comments, and existing `*_ACCOUNT_*` OAuth blocks. Never returns or logs the secret value.
|
|
187
757
|
*/
|
|
188
|
-
export function
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
758
|
+
export function upsertCredentialKey(dshHome, keyName, secretValue) {
|
|
759
|
+
const key = String(keyName || '').trim();
|
|
760
|
+
if (!/^[A-Za-z_][A-Za-z0-9_.-]{1,95}$/.test(key)) {
|
|
761
|
+
return { ok: false, error: '环境变量名格式无效(仅支持字母、数字、下划线、点或连字符)' };
|
|
762
|
+
}
|
|
763
|
+
if (/^(?:version|records|refs)$/i.test(key) || /_ACCOUNT(?:_|$)/i.test(key)) {
|
|
764
|
+
return { ok: false, error: `保护键 ${key} 不可通过插件覆盖写入` };
|
|
765
|
+
}
|
|
766
|
+
const secret = typeof secretValue === 'string' ? secretValue.trim() : '';
|
|
767
|
+
if (!secret || /[\r\n]/.test(secret) || secret.length > 4096) {
|
|
768
|
+
return { ok: false, error: '密钥值不能为空且必须为单行(<= 4096 字符)' };
|
|
769
|
+
}
|
|
192
770
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
771
|
+
const credPath = path.join(dshHome, '.credentials.yaml');
|
|
772
|
+
const escaped = secret.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
773
|
+
const formattedLine = ` ${key}: "${escaped}"`;
|
|
774
|
+
|
|
775
|
+
if (!fs.existsSync(credPath)) {
|
|
776
|
+
const initial = `version: 1\nrecords: []\nrefs:\n${formattedLine}\n`;
|
|
777
|
+
atomicWriteText(credPath, initial, true);
|
|
778
|
+
appendAuditEntry(dshHome, {
|
|
779
|
+
action: 'credential.upsert',
|
|
780
|
+
target: 'credentials',
|
|
781
|
+
summary: `初始化并单向写入凭据键 ${key}`,
|
|
782
|
+
ok: true,
|
|
783
|
+
});
|
|
784
|
+
return { ok: true, key, path: credPath, created: true };
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
const raw = safeReadText(credPath);
|
|
788
|
+
if (raw === null) {
|
|
789
|
+
return { ok: false, error: '无法读取 .credentials.yaml' };
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const doc = parseCredentialRefsDocument(raw);
|
|
793
|
+
const lines = doc.lines.slice();
|
|
794
|
+
const existing = doc.entries.find((e) => e.key === key);
|
|
795
|
+
|
|
796
|
+
if (existing) {
|
|
797
|
+
lines.splice(existing.startLine, existing.endLine - existing.startLine + 1, formattedLine);
|
|
798
|
+
} else if (doc.refsStart !== -1) {
|
|
799
|
+
if (/^refs:\s*\{\}/.test(lines[doc.refsStart])) {
|
|
800
|
+
lines[doc.refsStart] = 'refs:';
|
|
801
|
+
lines.splice(doc.refsStart + 1, 0, formattedLine);
|
|
802
|
+
} else {
|
|
803
|
+
let insertAt = doc.refsStart + 1;
|
|
804
|
+
for (let i = doc.refsStart + 1; i < doc.refsEnd; i += 1) {
|
|
805
|
+
if (lines[i].trim()) insertAt = i + 1;
|
|
806
|
+
}
|
|
807
|
+
lines.splice(insertAt, 0, formattedLine);
|
|
205
808
|
}
|
|
809
|
+
} else {
|
|
810
|
+
while (lines.length > 0 && !lines[lines.length - 1].trim()) lines.pop();
|
|
811
|
+
lines.push('refs:', formattedLine);
|
|
206
812
|
}
|
|
207
813
|
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
814
|
+
const output = `${lines.join('\n').replace(/\n+$/, '')}\n`;
|
|
815
|
+
atomicWriteText(credPath, output, true);
|
|
816
|
+
appendAuditEntry(dshHome, {
|
|
817
|
+
action: 'credential.upsert',
|
|
818
|
+
target: 'credentials',
|
|
819
|
+
summary: `${existing ? '更新' : '新增'}凭据键 ${key}(单向盲写)`,
|
|
820
|
+
ok: true,
|
|
821
|
+
});
|
|
822
|
+
return { ok: true, key, path: credPath, created: !existing };
|
|
823
|
+
}
|
|
211
824
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
const
|
|
825
|
+
export function inspectProviders(dshHome, target = null) {
|
|
826
|
+
const maskedCreds = inspectCredentialKeysMasked(dshHome);
|
|
827
|
+
const readyKeys = new Set(maskedCreds.keys.filter((k) => k.present).map((k) => k.key));
|
|
828
|
+
const merged = new Map();
|
|
829
|
+
const profileName = normalizeProfileTarget(target) || detectActiveProfile();
|
|
217
830
|
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
831
|
+
for (const pName of [profileName]) {
|
|
832
|
+
const profileDir = path.join(dshHome, 'profiles', pName);
|
|
833
|
+
for (const fileName of ['cordis.patch.yml', 'cordis.yml']) {
|
|
834
|
+
const text = safeReadText(path.join(profileDir, fileName));
|
|
835
|
+
if (!text) continue;
|
|
836
|
+
const nodes = collectPatchNodes(parseYamlStructure(text));
|
|
837
|
+
const piNode = nodes.find((n) => LLM_PLUGIN_IDS.has(n.id || '') || LLM_PLUGIN_IDS.has(n.name || ''));
|
|
838
|
+
const providers = piNode?.config?.providers;
|
|
839
|
+
if (!providers || typeof providers !== 'object') continue;
|
|
222
840
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
841
|
+
for (const [pid, cfg] of Object.entries(providers)) {
|
|
842
|
+
if (!cfg || typeof cfg !== 'object') continue;
|
|
843
|
+
const existing = merged.get(pid) || {
|
|
844
|
+
id: pid,
|
|
845
|
+
displayName: String(cfg.displayName || cfg.name || pid),
|
|
846
|
+
api: String(cfg.api || 'openai-completions'),
|
|
847
|
+
baseURL: String(cfg.baseURL || cfg.baseUrl || cfg.url || ''),
|
|
848
|
+
apiKeyEnv: String(cfg.apiKeyEnv || ''),
|
|
849
|
+
keyConfigured: false,
|
|
850
|
+
profiles: [],
|
|
851
|
+
models: [],
|
|
852
|
+
};
|
|
853
|
+
if (!existing.profiles.includes(pName)) {
|
|
854
|
+
existing.profiles.push(pName);
|
|
855
|
+
}
|
|
856
|
+
if (Array.isArray(cfg.models) && existing.models.length === 0) {
|
|
857
|
+
existing.models = cfg.models
|
|
858
|
+
.map((m) => {
|
|
859
|
+
if (typeof m === 'string') return { id: m, name: m };
|
|
860
|
+
if (m && typeof m === 'object') {
|
|
861
|
+
return { id: String(m.id || m.name || ''), name: String(m.name || m.id || '') };
|
|
862
|
+
}
|
|
863
|
+
return null;
|
|
864
|
+
})
|
|
865
|
+
.filter((m) => m && m.id);
|
|
866
|
+
}
|
|
867
|
+
existing.keyConfigured = existing.apiKeyEnv
|
|
868
|
+
? readyKeys.has(existing.apiKeyEnv) || Boolean(process.env[existing.apiKeyEnv])
|
|
869
|
+
: false;
|
|
870
|
+
merged.set(pid, existing);
|
|
871
|
+
}
|
|
872
|
+
break;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
228
875
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
876
|
+
return Array.from(merged.values());
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
function readPackageLoaderIds(profileDir, pkgName, guard) {
|
|
880
|
+
const pkgDir = path.join(profileDir, 'node_modules', ...pkgName.split('/'));
|
|
881
|
+
const pkgJson = safeReadJson(path.join(pkgDir, 'package.json'));
|
|
882
|
+
const patchRel = pkgJson?.dsh?.bundle?.patch;
|
|
883
|
+
const candidateFiles = [];
|
|
884
|
+
if (typeof patchRel === 'string' && patchRel.trim()) {
|
|
885
|
+
const resolved = path.resolve(pkgDir, patchRel.trim());
|
|
886
|
+
if (resolved.startsWith(pkgDir)) candidateFiles.push(resolved);
|
|
233
887
|
}
|
|
234
|
-
|
|
235
|
-
|
|
888
|
+
candidateFiles.push(path.join(pkgDir, 'cordis.patch.yml'));
|
|
889
|
+
|
|
890
|
+
const ids = [];
|
|
891
|
+
const pushId = (val) => {
|
|
892
|
+
if (typeof val === 'string' && val.trim() && !ids.includes(val.trim())) {
|
|
893
|
+
ids.push(val.trim());
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
for (const file of candidateFiles) {
|
|
898
|
+
const text = safeReadText(file);
|
|
899
|
+
if (!text) continue;
|
|
900
|
+
const nodes = collectPatchNodes(parseYamlStructure(text));
|
|
901
|
+
for (const n of nodes) {
|
|
902
|
+
if (n.kind === 'insert' && n.id) pushId(n.id);
|
|
903
|
+
}
|
|
904
|
+
if (ids.length > 0) break;
|
|
236
905
|
}
|
|
237
|
-
|
|
238
|
-
|
|
906
|
+
|
|
907
|
+
if (guard?.configDir) {
|
|
908
|
+
const mapJson = safeReadJson(path.join(guard.configDir, 'loader-ids.json'));
|
|
909
|
+
const mapped = mapJson?.[pkgName];
|
|
910
|
+
if (Array.isArray(mapped)) {
|
|
911
|
+
for (const m of mapped) pushId(m);
|
|
912
|
+
} else if (typeof mapped === 'string') {
|
|
913
|
+
pushId(mapped);
|
|
914
|
+
}
|
|
239
915
|
}
|
|
240
|
-
|
|
241
|
-
|
|
916
|
+
|
|
917
|
+
return { ids, description: typeof pkgJson?.description === 'string' ? pkgJson.description : '', version: pkgJson?.version || '' };
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
export function inspectExtensions(dshHome, target = null, guard = null) {
|
|
921
|
+
const profileName = resolveTargetProfile(target) || detectActiveProfile();
|
|
922
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
923
|
+
const pkg = safeReadJson(path.join(profileDir, 'package.json'));
|
|
924
|
+
const patchPath = path.join(profileDir, 'cordis.patch.yml');
|
|
925
|
+
const patchText = safeReadText(patchPath) || '';
|
|
926
|
+
const patchNodes = collectPatchNodes(parseYamlStructure(patchText));
|
|
927
|
+
|
|
928
|
+
const disabledMap = new Map();
|
|
929
|
+
for (const n of patchNodes) {
|
|
930
|
+
if (n.id && n.kind === 'override') {
|
|
931
|
+
if (n.disabled === true) disabledMap.set(n.id, true);
|
|
932
|
+
else if (n.disabled === false || n.disabledRaw === false) disabledMap.set(n.id, false);
|
|
933
|
+
}
|
|
242
934
|
}
|
|
243
935
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
936
|
+
const deps = pkg?.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {};
|
|
937
|
+
const plugins = [];
|
|
938
|
+
for (const [name, versionSpec] of Object.entries(deps)) {
|
|
939
|
+
const isCore = name.startsWith('@deepseek-ai/');
|
|
940
|
+
const isSelf = SELF_LOADER_IDS.has(name);
|
|
941
|
+
const meta = readPackageLoaderIds(profileDir, name, guard);
|
|
942
|
+
const loaderIds = [...meta.ids];
|
|
943
|
+
for (const n of patchNodes) {
|
|
944
|
+
if (n.name === name && n.id && !loaderIds.includes(n.id)) {
|
|
945
|
+
loaderIds.push(n.id);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
if (loaderIds.length === 0) {
|
|
949
|
+
const short = name.includes('/') ? name.split('/').pop() : name;
|
|
950
|
+
loaderIds.push(short);
|
|
951
|
+
if (short !== name) loaderIds.push(name);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const disabled = loaderIds.some((id) => disabledMap.get(id) === true);
|
|
955
|
+
plugins.push({
|
|
956
|
+
name,
|
|
957
|
+
version: meta.version || String(versionSpec || ''),
|
|
958
|
+
description: meta.description,
|
|
959
|
+
isCore,
|
|
960
|
+
isSelf,
|
|
961
|
+
canToggle: !isCore && !isSelf,
|
|
962
|
+
loaderIds,
|
|
963
|
+
primaryId: loaderIds[0],
|
|
964
|
+
enabled: !disabled,
|
|
965
|
+
disabled,
|
|
966
|
+
});
|
|
255
967
|
}
|
|
968
|
+
|
|
969
|
+
plugins.sort((a, b) => {
|
|
970
|
+
if (a.isSelf !== b.isSelf) return a.isSelf ? -1 : 1;
|
|
971
|
+
if (a.isCore !== b.isCore) return a.isCore ? 1 : -1;
|
|
972
|
+
return a.name.localeCompare(b.name);
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
const mcpServers = [];
|
|
976
|
+
for (const n of patchNodes) {
|
|
977
|
+
if (n.kind === 'insert' && n.name === MCP_CLIENT_PKG && n.id) {
|
|
978
|
+
const overrideDisabled = disabledMap.get(n.id);
|
|
979
|
+
const isDisabled = overrideDisabled !== undefined ? overrideDisabled : n.disabled === true;
|
|
980
|
+
const cfg = n.config || {};
|
|
981
|
+
const parsedTimeout = Number(cfg.toolCallTimeoutMs);
|
|
982
|
+
const timeoutConfigured = Number.isFinite(parsedTimeout) && parsedTimeout > 0;
|
|
983
|
+
mcpServers.push({
|
|
984
|
+
id: n.id,
|
|
985
|
+
serverName: String(cfg.serverName || n.id.replace(/^mcp-/, '')),
|
|
986
|
+
transport: String(cfg.transport || (cfg.url ? 'sse' : 'stdio')),
|
|
987
|
+
command: cfg.command ? String(cfg.command) : null,
|
|
988
|
+
args: Array.isArray(cfg.args) ? cfg.args.map((a) => String(a)) : [],
|
|
989
|
+
url: cfg.url ? String(cfg.url) : null,
|
|
990
|
+
toolCallTimeoutMs: timeoutConfigured ? parsedTimeout : 60000,
|
|
991
|
+
timeoutConfigured,
|
|
992
|
+
enabled: !isDisabled,
|
|
993
|
+
disabled: isDisabled,
|
|
994
|
+
canToggle: true,
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
return {
|
|
1000
|
+
target: profileName,
|
|
1001
|
+
profileExists: fs.existsSync(profileDir),
|
|
1002
|
+
patchPath,
|
|
1003
|
+
plugins,
|
|
1004
|
+
mcpServers,
|
|
1005
|
+
};
|
|
256
1006
|
}
|
|
257
1007
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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
|
+
}
|
|
1013
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
1014
|
+
const broken = findBrokenModuleLinks(profileDir);
|
|
1015
|
+
if (broken.length === 0) {
|
|
1016
|
+
return {
|
|
1017
|
+
ok: true,
|
|
1018
|
+
allRepaired: true,
|
|
1019
|
+
target: profileName,
|
|
1020
|
+
repairedCount: 0,
|
|
1021
|
+
unresolvableCount: 0,
|
|
1022
|
+
results: [],
|
|
1023
|
+
message: '当前档案无断裂依赖软链接',
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
const otherProfile = profileName === 'desktop' ? 'web' : 'desktop';
|
|
1028
|
+
const results = [];
|
|
1029
|
+
|
|
1030
|
+
for (const item of broken) {
|
|
1031
|
+
const parts = item.name.split('/');
|
|
1032
|
+
const candidates = [
|
|
1033
|
+
path.join(dshHome, '.dsh-module-fallback', 'node_modules', ...parts),
|
|
1034
|
+
path.join(dshHome, 'profiles', otherProfile, 'node_modules', ...parts),
|
|
1035
|
+
path.join(dshHome, 'node_modules', ...parts),
|
|
1036
|
+
];
|
|
1037
|
+
|
|
1038
|
+
let resolvedSource = null;
|
|
1039
|
+
for (const cand of candidates) {
|
|
1040
|
+
try {
|
|
1041
|
+
if (fs.existsSync(cand)) {
|
|
1042
|
+
const real = fs.realpathSync(cand);
|
|
1043
|
+
if (fs.existsSync(path.join(real, 'package.json'))) {
|
|
1044
|
+
resolvedSource = real;
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
283
1047
|
}
|
|
1048
|
+
} catch {
|
|
1049
|
+
// Ignore broken candidate.
|
|
284
1050
|
}
|
|
285
|
-
}
|
|
286
|
-
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
if (!resolvedSource) {
|
|
1054
|
+
results.push({ name: item.name, status: 'unresolvable', linkPath: item.linkPath });
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
try {
|
|
1059
|
+
try {
|
|
1060
|
+
fs.unlinkSync(item.linkPath);
|
|
1061
|
+
} catch {
|
|
1062
|
+
fs.rmSync(item.linkPath, { recursive: true, force: true });
|
|
1063
|
+
}
|
|
1064
|
+
fs.symlinkSync(
|
|
1065
|
+
resolvedSource,
|
|
1066
|
+
item.linkPath,
|
|
1067
|
+
process.platform === 'win32' ? 'junction' : 'dir',
|
|
1068
|
+
);
|
|
1069
|
+
results.push({ name: item.name, status: 'repaired', linkPath: item.linkPath, targetDir: resolvedSource });
|
|
1070
|
+
} catch (err) {
|
|
1071
|
+
results.push({
|
|
1072
|
+
name: item.name,
|
|
1073
|
+
status: 'error',
|
|
1074
|
+
linkPath: item.linkPath,
|
|
1075
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1076
|
+
});
|
|
287
1077
|
}
|
|
288
1078
|
}
|
|
289
1079
|
|
|
290
|
-
const
|
|
291
|
-
const
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const
|
|
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
|
+
});
|
|
296
1095
|
|
|
297
1096
|
return {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
1097
|
+
ok: true,
|
|
1098
|
+
allRepaired,
|
|
1099
|
+
target: profileName,
|
|
1100
|
+
repairedCount,
|
|
1101
|
+
unresolvableCount,
|
|
1102
|
+
unresolvedNames,
|
|
1103
|
+
message,
|
|
1104
|
+
results,
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function getSnapshotsRoot(dshHome) {
|
|
1109
|
+
return path.join(dshHome, 'guard-snapshots');
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
function collectSnapshotCandidates(dshHome, target) {
|
|
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
|
+
];
|
|
1121
|
+
return list;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
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
|
+
}
|
|
303
1154
|
}
|
|
304
1155
|
}
|
|
305
1156
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
1157
|
+
export function createSnapshot(dshHome, target = null, kind = 'manual', reason = '') {
|
|
1158
|
+
const normTarget = resolveTargetProfile(target) || detectActiveProfile();
|
|
1159
|
+
const now = new Date();
|
|
1160
|
+
const stamp = [
|
|
1161
|
+
now.getUTCFullYear(),
|
|
1162
|
+
String(now.getUTCMonth() + 1).padStart(2, '0'),
|
|
1163
|
+
String(now.getUTCDate()).padStart(2, '0'),
|
|
1164
|
+
'-',
|
|
1165
|
+
String(now.getUTCHours()).padStart(2, '0'),
|
|
1166
|
+
String(now.getUTCMinutes()).padStart(2, '0'),
|
|
1167
|
+
String(now.getUTCSeconds()).padStart(2, '0'),
|
|
1168
|
+
'-',
|
|
1169
|
+
String(now.getUTCMilliseconds()).padStart(3, '0'),
|
|
1170
|
+
].join('');
|
|
1171
|
+
const safeKind = String(kind || 'manual').replace(/[^a-z0-9_-]/gi, '').slice(0, 24) || 'manual';
|
|
1172
|
+
const id = `${stamp}-${safeKind}-${normTarget}`;
|
|
1173
|
+
const snapDir = path.join(getSnapshotsRoot(dshHome), id);
|
|
1174
|
+
fs.mkdirSync(snapDir, { recursive: true });
|
|
314
1175
|
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
1176
|
+
const candidates = collectSnapshotCandidates(dshHome, normTarget);
|
|
1177
|
+
const items = [];
|
|
1178
|
+
|
|
1179
|
+
for (const cand of candidates) {
|
|
1180
|
+
if (CRED_SKIP_RE.test(cand.relPath) || !SNAPSHOT_SAFE_EXT_RE.test(cand.relPath)) continue;
|
|
1181
|
+
if (!fs.existsSync(cand.absPath)) continue;
|
|
1182
|
+
const raw = fs.readFileSync(cand.absPath);
|
|
1183
|
+
const dest = path.join(snapDir, cand.snapFile);
|
|
1184
|
+
fs.writeFileSync(dest, raw);
|
|
1185
|
+
items.push({
|
|
1186
|
+
relPath: cand.relPath,
|
|
1187
|
+
snapFile: cand.snapFile,
|
|
1188
|
+
sha256: crypto.createHash('sha256').update(raw).digest('hex'),
|
|
1189
|
+
size: raw.length,
|
|
1190
|
+
});
|
|
318
1191
|
}
|
|
319
|
-
|
|
320
|
-
|
|
1192
|
+
|
|
1193
|
+
const manifest = {
|
|
1194
|
+
id,
|
|
1195
|
+
source: 'plugin',
|
|
1196
|
+
target: normTarget,
|
|
1197
|
+
kind: safeKind,
|
|
1198
|
+
reason: String(reason || (safeKind === 'manual' ? '手动配置快照' : safeKind)),
|
|
1199
|
+
createdAt: now.toISOString(),
|
|
1200
|
+
pinned: false,
|
|
1201
|
+
pinLabel: '',
|
|
1202
|
+
itemCount: items.length,
|
|
1203
|
+
items,
|
|
1204
|
+
};
|
|
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
|
+
});
|
|
321
1216
|
}
|
|
1217
|
+
return { ok: true, snapshot: manifest, dir: snapDir };
|
|
1218
|
+
}
|
|
322
1219
|
|
|
323
|
-
|
|
324
|
-
const
|
|
325
|
-
|
|
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
|
+
}
|
|
326
1225
|
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
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)' };
|
|
330
1230
|
}
|
|
331
1231
|
|
|
332
|
-
const
|
|
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
|
+
});
|
|
333
1250
|
|
|
334
1251
|
return {
|
|
335
|
-
|
|
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
|
+
}
|
|
1264
|
+
const entryId = String(id || '').trim();
|
|
1265
|
+
if (!entryId) return { ok: false, error: '缺少条目 ID' };
|
|
1266
|
+
if (SELF_LOADER_IDS.has(entryId)) {
|
|
1267
|
+
return { ok: false, error: '不能通过伴生插件禁用当前正在运行的 @gluztm/dsh-guard 自身' };
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
const ext = inspectExtensions(dshHome, profileName, guard);
|
|
1271
|
+
const matchedPlugin = ext.plugins.find((p) => p.loaderIds.includes(entryId) || p.name === entryId);
|
|
1272
|
+
if (matchedPlugin && matchedPlugin.isCore) {
|
|
1273
|
+
return { ok: false, error: `核心组件 ${matchedPlugin.name} 受保护,请保持启用` };
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
const patchPath = path.join(dshHome, 'profiles', profileName, 'cordis.patch.yml');
|
|
1277
|
+
const existingText = safeReadText(patchPath) ?? '';
|
|
1278
|
+
const targetId = matchedPlugin ? matchedPlugin.primaryId : entryId;
|
|
1279
|
+
const wantDisabled = Boolean(disabled);
|
|
1280
|
+
|
|
1281
|
+
const preSnap = createSnapshot(
|
|
336
1282
|
dshHome,
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
1283
|
+
profileName,
|
|
1284
|
+
'auto-toggle',
|
|
1285
|
+
`${wantDisabled ? '禁用' : '启用'} ${targetId} 前自动快照`,
|
|
1286
|
+
);
|
|
1287
|
+
|
|
1288
|
+
const rawLines = existingText ? existingText.replace(/\r\n/g, '\n').split('\n') : [];
|
|
1289
|
+
const parsedNodes = collectPatchNodes(parseYamlStructure(existingText));
|
|
1290
|
+
const idsToMatch = matchedPlugin ? new Set(matchedPlugin.loaderIds) : new Set([targetId]);
|
|
1291
|
+
|
|
1292
|
+
const overrideBlocks = parsedNodes.filter(
|
|
1293
|
+
(n) => n.kind === 'override' && n.id && idsToMatch.has(n.id) && Array.isArray(n.lineRange),
|
|
1294
|
+
);
|
|
1295
|
+
const insertBlocks = parsedNodes.filter(
|
|
1296
|
+
(n) => n.kind === 'insert' && n.id && idsToMatch.has(n.id) && Array.isArray(n.lineRange),
|
|
1297
|
+
);
|
|
1298
|
+
|
|
1299
|
+
const linesToRemove = new Set();
|
|
1300
|
+
let updatedOverrideInPlace = false;
|
|
1301
|
+
|
|
1302
|
+
if (!wantDisabled) {
|
|
1303
|
+
for (const blk of overrideBlocks) {
|
|
1304
|
+
const [s, e] = blk.lineRange;
|
|
1305
|
+
const nonControlKeys = blk.keys.filter((k) => k !== 'id' && k !== 'disabled');
|
|
1306
|
+
if (nonControlKeys.length === 0) {
|
|
1307
|
+
for (let i = s; i <= e; i += 1) linesToRemove.add(i);
|
|
1308
|
+
} else {
|
|
1309
|
+
for (let i = s; i <= e; i += 1) {
|
|
1310
|
+
if (/^\s+disabled:\s*/.test(rawLines[i])) linesToRemove.add(i);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
for (const blk of insertBlocks) {
|
|
1315
|
+
const [s, e] = blk.lineRange;
|
|
1316
|
+
for (let i = s; i <= e; i += 1) {
|
|
1317
|
+
if (/^\s+disabled:\s*true\b/.test(rawLines[i])) linesToRemove.add(i);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
} else {
|
|
1321
|
+
for (const blk of overrideBlocks) {
|
|
1322
|
+
const [s, e] = blk.lineRange;
|
|
1323
|
+
let hadDisabledLine = false;
|
|
1324
|
+
for (let i = s; i <= e; i += 1) {
|
|
1325
|
+
if (/^\s+disabled:\s*/.test(rawLines[i])) {
|
|
1326
|
+
rawLines[i] = rawLines[i].replace(/(^\s+disabled:\s*).*/, '$1true');
|
|
1327
|
+
hadDisabledLine = true;
|
|
1328
|
+
updatedOverrideInPlace = true;
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
if (!hadDisabledLine) {
|
|
1332
|
+
rawLines.splice(e + 1, 0, ' disabled: true');
|
|
1333
|
+
updatedOverrideInPlace = true;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
344
1336
|
}
|
|
1337
|
+
|
|
1338
|
+
let nextLines = rawLines.filter((_, idx) => !linesToRemove.has(idx));
|
|
1339
|
+
if (wantDisabled && !updatedOverrideInPlace) {
|
|
1340
|
+
while (nextLines.length > 0 && !nextLines[nextLines.length - 1].trim()) nextLines.pop();
|
|
1341
|
+
nextLines.push(`- id: ${quoteYamlId(targetId)}`, ' disabled: true');
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
const finalBody = nextLines.length > 0 ? `${nextLines.join('\n').replace(/\n+$/, '')}\n` : '';
|
|
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
|
+
});
|
|
1353
|
+
|
|
1354
|
+
return {
|
|
1355
|
+
ok: true,
|
|
1356
|
+
target: profileName,
|
|
1357
|
+
id: targetId,
|
|
1358
|
+
enabled: !wantDisabled,
|
|
1359
|
+
disabled: wantDisabled,
|
|
1360
|
+
preSnapshotId: preSnap.snapshot.id,
|
|
1361
|
+
patchPath,
|
|
1362
|
+
restartHint: profileName === 'web'
|
|
1363
|
+
? '已写入 Web 配置文件,重载 DSH 服务后生效(已在变更前自动保存快照)'
|
|
1364
|
+
: `已写入 ${profileName} 配置文件,重启对应 DSH 端后生效(已在变更前自动保存快照)`,
|
|
1365
|
+
};
|
|
345
1366
|
}
|
|
346
1367
|
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
+
}
|
|
352
1389
|
|
|
353
|
-
const
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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;
|
|
361
1431
|
}
|
|
362
|
-
if (typeof res.data.reason === 'string') reason = res.data.reason
|
|
363
|
-
if (typeof res.data.createdAt === 'string') createdAt = res.data.createdAt
|
|
364
|
-
if (Array.isArray(res.data.files)) itemCount = res.data.files.length
|
|
365
1432
|
}
|
|
366
1433
|
}
|
|
367
1434
|
|
|
368
|
-
|
|
369
|
-
|
|
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
|
+
}
|
|
370
1449
|
}
|
|
371
1450
|
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
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
|
+
}
|
|
376
1483
|
}
|
|
377
|
-
|
|
378
|
-
|
|
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}`);
|
|
379
1494
|
}
|
|
380
|
-
}
|
|
381
|
-
|
|
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
|
+
);
|
|
382
1506
|
}
|
|
383
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
|
+
|
|
384
1519
|
return {
|
|
385
|
-
|
|
386
|
-
target,
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
1520
|
+
ok: true,
|
|
1521
|
+
target: profileName,
|
|
1522
|
+
id: entryId,
|
|
1523
|
+
toolCallTimeoutMs: ms,
|
|
1524
|
+
preSnapshotId: preSnap.snapshot.id,
|
|
1525
|
+
patchPath,
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
function readSnapshotRecordsFromDir(rootDir, sourceKind, dshHome) {
|
|
1530
|
+
if (!rootDir || !fs.existsSync(rootDir)) return [];
|
|
1531
|
+
let dirs = [];
|
|
1532
|
+
try {
|
|
1533
|
+
dirs = fs.readdirSync(rootDir, { withFileTypes: true }).filter((d) => d.isDirectory());
|
|
1534
|
+
} catch {
|
|
1535
|
+
return [];
|
|
390
1536
|
}
|
|
1537
|
+
|
|
1538
|
+
const records = [];
|
|
1539
|
+
for (const d of dirs) {
|
|
1540
|
+
const full = path.join(rootDir, d.name);
|
|
1541
|
+
const manifest = safeReadJson(path.join(full, 'manifest.json'));
|
|
1542
|
+
let createdAt = manifest?.createdAt || manifest?.CreatedAt || null;
|
|
1543
|
+
if (!createdAt) {
|
|
1544
|
+
try {
|
|
1545
|
+
createdAt = fs.statSync(full).mtime.toISOString();
|
|
1546
|
+
} catch {
|
|
1547
|
+
createdAt = null;
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
const rawItems = Array.isArray(manifest?.items)
|
|
1552
|
+
? manifest.items
|
|
1553
|
+
: Array.isArray(manifest?.Items)
|
|
1554
|
+
? manifest.Items
|
|
1555
|
+
: null;
|
|
1556
|
+
|
|
1557
|
+
let files = [];
|
|
1558
|
+
if (rawItems) {
|
|
1559
|
+
files = rawItems
|
|
1560
|
+
.map((it) => {
|
|
1561
|
+
const relPath = String(it.relPath || it.RelPath || '').replace(/\\/g, '/');
|
|
1562
|
+
const snapFile = String(it.snapFile || it.SnapFile || path.basename(relPath));
|
|
1563
|
+
if (!snapFile || CRED_SKIP_RE.test(snapFile) || CRED_SKIP_RE.test(relPath)) return null;
|
|
1564
|
+
const snapSha = it.sha256 || it.Sha256 || sha256File(path.join(full, snapFile));
|
|
1565
|
+
let status = 'unknown';
|
|
1566
|
+
if (relPath) {
|
|
1567
|
+
const livePath = path.join(dshHome, ...relPath.split('/'));
|
|
1568
|
+
if (!fs.existsSync(livePath)) {
|
|
1569
|
+
status = 'missing_now';
|
|
1570
|
+
} else {
|
|
1571
|
+
const liveSha = sha256File(livePath);
|
|
1572
|
+
status = liveSha && snapSha ? (liveSha === snapSha ? 'same' : 'modified') : 'unknown';
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
return {
|
|
1576
|
+
name: snapFile,
|
|
1577
|
+
relPath: relPath || snapFile,
|
|
1578
|
+
size: Number(it.size || it.Size || 0),
|
|
1579
|
+
sha256: snapSha,
|
|
1580
|
+
status,
|
|
1581
|
+
restorableInPlugin: RESTORABLE_REL_RE.test(relPath) && SNAPSHOT_SAFE_EXT_RE.test(snapFile),
|
|
1582
|
+
};
|
|
1583
|
+
})
|
|
1584
|
+
.filter(Boolean);
|
|
1585
|
+
} else if (Array.isArray(manifest?.files)) {
|
|
1586
|
+
files = manifest.files
|
|
1587
|
+
.filter((f) => typeof f === 'string' && !CRED_SKIP_RE.test(f))
|
|
1588
|
+
.map((f) => ({
|
|
1589
|
+
name: f,
|
|
1590
|
+
relPath: f,
|
|
1591
|
+
size: 0,
|
|
1592
|
+
sha256: null,
|
|
1593
|
+
status: 'unknown',
|
|
1594
|
+
restorableInPlugin: false,
|
|
1595
|
+
}));
|
|
1596
|
+
} else {
|
|
1597
|
+
try {
|
|
1598
|
+
const listed = fs.readdirSync(full, { withFileTypes: true }).filter((f) => f.isFile() && f.name !== 'manifest.json');
|
|
1599
|
+
files = listed
|
|
1600
|
+
.filter((f) => !CRED_SKIP_RE.test(f.name))
|
|
1601
|
+
.map((f) => {
|
|
1602
|
+
const p = path.join(full, f.name);
|
|
1603
|
+
let size = 0;
|
|
1604
|
+
try {
|
|
1605
|
+
size = fs.statSync(p).size;
|
|
1606
|
+
} catch {
|
|
1607
|
+
size = 0;
|
|
1608
|
+
}
|
|
1609
|
+
return {
|
|
1610
|
+
name: f.name,
|
|
1611
|
+
relPath: f.name,
|
|
1612
|
+
size,
|
|
1613
|
+
sha256: sha256File(p),
|
|
1614
|
+
status: 'unknown',
|
|
1615
|
+
restorableInPlugin: false,
|
|
1616
|
+
};
|
|
1617
|
+
});
|
|
1618
|
+
} catch {
|
|
1619
|
+
files = [];
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
const changedCount = files.filter((f) => f.status === 'modified' || f.status === 'missing_now').length;
|
|
1624
|
+
records.push({
|
|
1625
|
+
id: String(manifest?.id || manifest?.Id || d.name),
|
|
1626
|
+
source: manifest?.source || sourceKind,
|
|
1627
|
+
dir: full,
|
|
1628
|
+
target: manifest?.target || manifest?.Target || (d.name.includes('desktop') ? 'desktop' : 'web'),
|
|
1629
|
+
kind: manifest?.kind || manifest?.Kind || 'snapshot',
|
|
1630
|
+
reason: manifest?.reason || manifest?.Reason || '',
|
|
1631
|
+
createdAt,
|
|
1632
|
+
pinned: Boolean(manifest?.pinned ?? manifest?.Pinned),
|
|
1633
|
+
pinLabel: String(manifest?.pinLabel ?? manifest?.PinLabel ?? ''),
|
|
1634
|
+
itemCount: Number(manifest?.itemCount || manifest?.ItemCount || files.length),
|
|
1635
|
+
changedCount,
|
|
1636
|
+
restorableCount: files.filter((f) => f.restorableInPlugin).length,
|
|
1637
|
+
files,
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
return records;
|
|
391
1641
|
}
|
|
392
1642
|
|
|
393
|
-
/**
|
|
394
|
-
* List saved DSHGuard snapshots (strictly read-only).
|
|
395
|
-
*/
|
|
396
1643
|
export function inspectSnapshots(options = {}) {
|
|
397
|
-
const
|
|
398
|
-
const
|
|
399
|
-
const
|
|
400
|
-
|
|
401
|
-
|
|
1644
|
+
const dshHome = resolveDshHome(options.dshHome);
|
|
1645
|
+
const guard = options.guard || locateGuardInstallation(options);
|
|
1646
|
+
const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(50, options.limit)) : 10;
|
|
1647
|
+
const targetFilter = options.target && options.target !== 'all'
|
|
1648
|
+
? (normalizeProfileTarget(String(options.target)) || 'all')
|
|
1649
|
+
: 'all';
|
|
1650
|
+
|
|
1651
|
+
const isolateGuardOnly = Boolean(options.guardHome && !options.dshHome && !process.env.DSH_HOME);
|
|
1652
|
+
const pluginRoot = getSnapshotsRoot(dshHome);
|
|
1653
|
+
const pluginRecs = isolateGuardOnly ? [] : readSnapshotRecordsFromDir(pluginRoot, 'plugin', dshHome);
|
|
1654
|
+
const desktopRecs = guard.snapshotsDir && path.resolve(guard.snapshotsDir) !== path.resolve(pluginRoot)
|
|
1655
|
+
? readSnapshotRecordsFromDir(guard.snapshotsDir, 'desktop', dshHome)
|
|
1656
|
+
: [];
|
|
1657
|
+
|
|
1658
|
+
const merged = new Map();
|
|
1659
|
+
for (const r of [...pluginRecs, ...desktopRecs]) {
|
|
1660
|
+
if (!merged.has(r.id)) merged.set(r.id, r);
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
let snapshots = Array.from(merged.values()).sort((a, b) => {
|
|
1664
|
+
const ta = a.createdAt ? Date.parse(a.createdAt) : 0;
|
|
1665
|
+
const tb = b.createdAt ? Date.parse(b.createdAt) : 0;
|
|
1666
|
+
return tb - ta || b.id.localeCompare(a.id);
|
|
1667
|
+
});
|
|
1668
|
+
|
|
1669
|
+
if (targetFilter !== 'all') {
|
|
1670
|
+
snapshots = snapshots.filter((s) => s.target === targetFilter || s.target === 'all');
|
|
1671
|
+
}
|
|
402
1672
|
|
|
403
|
-
|
|
1673
|
+
return {
|
|
1674
|
+
available: snapshots.length > 0 || fs.existsSync(pluginRoot) || Boolean(guard.snapshotsDir && fs.existsSync(guard.snapshotsDir)),
|
|
1675
|
+
guardInstalled: Boolean(guard.installed),
|
|
1676
|
+
releaseUrl: RELEASE_URL,
|
|
1677
|
+
pluginSnapshotsDir: pluginRoot,
|
|
1678
|
+
snapshotsDir: guard.snapshotsDir || pluginRoot,
|
|
1679
|
+
total: snapshots.length,
|
|
1680
|
+
snapshots: snapshots.slice(0, limit),
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
export function restoreSnapshotConfig(dshHome, guard, snapshotId) {
|
|
1685
|
+
const id = String(snapshotId || '').trim();
|
|
1686
|
+
if (!id || /[\\/]|\.\./.test(id)) {
|
|
1687
|
+
return { ok: false, error: '无效的快照 ID' };
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
const listed = inspectSnapshots({ dshHome, guard, limit: 50 });
|
|
1691
|
+
const snap = listed.snapshots.find((s) => s.id === id);
|
|
1692
|
+
if (!snap) {
|
|
1693
|
+
return { ok: false, error: `未找到快照 ${id}` };
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
const restorable = snap.files.filter((f) => f.restorableInPlugin);
|
|
1697
|
+
if (restorable.length === 0) {
|
|
404
1698
|
return {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
snapshots: [],
|
|
409
|
-
releaseUrl: RELEASE_URL,
|
|
410
|
-
installerUrl: INSTALLER_URL,
|
|
411
|
-
repoUrl: REPO_URL,
|
|
412
|
-
}
|
|
1699
|
+
ok: false,
|
|
1700
|
+
error: '该快照仅包含桌面端级产物(如二进制包、注册表或非 YAML 档案),请在插件边界说明中使用原生桌面端还原',
|
|
1701
|
+
};
|
|
413
1702
|
}
|
|
414
1703
|
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
1704
|
+
const preSnapTarget = snap.target === 'all' ? 'all' : (resolveTargetProfile(snap.target) || 'web');
|
|
1705
|
+
const preSnap = createSnapshot(
|
|
1706
|
+
dshHome,
|
|
1707
|
+
preSnapTarget,
|
|
1708
|
+
'pre-restore',
|
|
1709
|
+
`恢复快照 ${id} 前自动备份`,
|
|
1710
|
+
);
|
|
1711
|
+
|
|
1712
|
+
const restoredFiles = [];
|
|
1713
|
+
const skippedFiles = [];
|
|
1714
|
+
const resolvedHome = path.resolve(dshHome);
|
|
1715
|
+
|
|
1716
|
+
for (const f of snap.files) {
|
|
1717
|
+
if (!f.restorableInPlugin) {
|
|
1718
|
+
skippedFiles.push({ relPath: f.relPath, reason: '超出伴生插件白名单范围' });
|
|
1719
|
+
continue;
|
|
425
1720
|
}
|
|
426
|
-
|
|
427
|
-
|
|
1721
|
+
const snapFile = String(f.snapFile || f.name || '').trim();
|
|
1722
|
+
if (!snapFile || CRED_SKIP_RE.test(snapFile) || CRED_SKIP_RE.test(f.relPath) || /[\\/]|\.\./.test(snapFile)) {
|
|
1723
|
+
skippedFiles.push({ relPath: f.relPath, reason: '安全跳过' });
|
|
1724
|
+
continue;
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
const srcFile = path.join(snap.dir, snapFile);
|
|
1728
|
+
const destFile = path.resolve(resolvedHome, ...f.relPath.split('/'));
|
|
1729
|
+
if (!destFile.startsWith(`${resolvedHome}${path.sep}`)) {
|
|
1730
|
+
skippedFiles.push({ relPath: f.relPath, reason: '路径越界保护' });
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
if (!fs.existsSync(srcFile)) {
|
|
1734
|
+
skippedFiles.push({ relPath: f.relPath, reason: '快照文件缺失' });
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
const content = fs.readFileSync(srcFile, 'utf8');
|
|
1739
|
+
atomicWriteText(destFile, content);
|
|
1740
|
+
restoredFiles.push(f.relPath);
|
|
428
1741
|
}
|
|
429
1742
|
|
|
430
|
-
|
|
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
|
+
});
|
|
431
1750
|
|
|
432
1751
|
return {
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
1752
|
+
ok: restoredFiles.length > 0,
|
|
1753
|
+
snapshotId: id,
|
|
1754
|
+
preRestoreId: preSnap.snapshot.id,
|
|
1755
|
+
restoredFiles,
|
|
1756
|
+
skippedFiles,
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
export function inspectHealth(options = {}) {
|
|
1761
|
+
const dshHome = resolveDshHome(options.dshHome);
|
|
1762
|
+
const guard = locateGuardInstallation(options);
|
|
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
|
+
|
|
1773
|
+
const credentials = inspectCredentialKeysMasked(dshHome);
|
|
1774
|
+
const providers = inspectProviders(dshHome, activeProfile);
|
|
1775
|
+
const snapshots = inspectSnapshots({ dshHome, guard, target: activeProfile, limit: 15 });
|
|
1776
|
+
|
|
1777
|
+
const readyKeySet = new Set(credentials.keys.filter((k) => k.present || k.envSet).map((k) => k.key));
|
|
1778
|
+
const missingReferencedKeys = Array.from(referencedEnvSet).filter((k) => !readyKeySet.has(k));
|
|
1779
|
+
credentials.missingReferencedKeys = missingReferencedKeys;
|
|
1780
|
+
|
|
1781
|
+
const trackTitle = activeProfile === 'desktop' ? '桌面端' : 'Web 端';
|
|
1782
|
+
const issues = [];
|
|
1783
|
+
if (!fs.existsSync(dshHome)) {
|
|
1784
|
+
issues.push(`未找到 DSH 目录: ${dshHome}`);
|
|
1785
|
+
}
|
|
1786
|
+
if (!profile.exists) {
|
|
1787
|
+
issues.push(`未找到 ${trackTitle} (${activeProfile}) 运行档案目录`);
|
|
1788
|
+
}
|
|
1789
|
+
if (profile.missingBundles && profile.missingBundles.length > 0) {
|
|
1790
|
+
issues.push(`${trackTitle}存在未在 dependencies 注册的 bundle: ${profile.missingBundles.join(', ')}`);
|
|
440
1791
|
}
|
|
1792
|
+
if (profile.brokenLinkCount > 0) {
|
|
1793
|
+
issues.push(`${trackTitle}存在 ${profile.brokenLinkCount} 个断裂依赖软链接`);
|
|
1794
|
+
}
|
|
1795
|
+
if (!credentials.present) {
|
|
1796
|
+
issues.push('.credentials.yaml 尚未初始化');
|
|
1797
|
+
}
|
|
1798
|
+
if (missingReferencedKeys.length > 0) {
|
|
1799
|
+
issues.push(`配置中引用的凭据键缺失: ${missingReferencedKeys.join(', ')}`);
|
|
1800
|
+
}
|
|
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
|
+
|
|
1810
|
+
return {
|
|
1811
|
+
companionVersion: PACKAGE_VERSION,
|
|
1812
|
+
checkedAt: new Date().toISOString(),
|
|
1813
|
+
platform: process.platform,
|
|
1814
|
+
dshHome,
|
|
1815
|
+
dshHomeExists: fs.existsSync(dshHome),
|
|
1816
|
+
activeProfile,
|
|
1817
|
+
profileNames: [activeProfile],
|
|
1818
|
+
profile,
|
|
1819
|
+
healthy: issues.length === 0,
|
|
1820
|
+
issuesCount: issues.length,
|
|
1821
|
+
issues,
|
|
1822
|
+
driftWarnings: issues,
|
|
1823
|
+
guard,
|
|
1824
|
+
profiles,
|
|
1825
|
+
credentials,
|
|
1826
|
+
providers,
|
|
1827
|
+
extensions,
|
|
1828
|
+
contextAudit,
|
|
1829
|
+
auditLog,
|
|
1830
|
+
snapshots,
|
|
1831
|
+
};
|
|
441
1832
|
}
|
|
442
1833
|
|
|
443
|
-
/**
|
|
444
|
-
* Locate or optionally launch the local Windows DSHGuard desktop supervisor.
|
|
445
|
-
*/
|
|
446
1834
|
export function openGuard(options = {}) {
|
|
447
|
-
const guard = locateGuardInstallation(options)
|
|
1835
|
+
const guard = locateGuardInstallation(options);
|
|
1836
|
+
if (process.platform !== 'win32') {
|
|
1837
|
+
return {
|
|
1838
|
+
ok: false,
|
|
1839
|
+
installed: false,
|
|
1840
|
+
launched: false,
|
|
1841
|
+
reason: 'non-windows',
|
|
1842
|
+
message: `当前系统为 ${process.platform};原版 DSHGuard 桌面应用目前仅提供 Windows 安装包(伴生插件本身的插件/凭据/快照功能已在当前平台完整可用)。`,
|
|
1843
|
+
releaseUrl: RELEASE_URL,
|
|
1844
|
+
installerUrl: INSTALLER_URL,
|
|
1845
|
+
installUrl: INSTALLER_URL,
|
|
1846
|
+
};
|
|
1847
|
+
}
|
|
448
1848
|
if (!guard.installed || !guard.exePath) {
|
|
449
1849
|
return {
|
|
1850
|
+
ok: false,
|
|
450
1851
|
installed: false,
|
|
451
1852
|
launched: false,
|
|
452
|
-
|
|
453
|
-
|
|
1853
|
+
reason: 'not-installed',
|
|
1854
|
+
message: '未在本机检测到 DSHGuard.exe(伴生插件本身已内置插件开关、凭据写入与配置快照);如需跨进程托管或硬件加密隔离,可安装 Windows 桌面端。',
|
|
454
1855
|
releaseUrl: RELEASE_URL,
|
|
455
1856
|
installerUrl: INSTALLER_URL,
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
}
|
|
1857
|
+
installUrl: INSTALLER_URL,
|
|
1858
|
+
};
|
|
459
1859
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
try {
|
|
475
|
-
const child = spawn(guard.exePath, [], {
|
|
476
|
-
detached: true,
|
|
477
|
-
stdio: 'ignore',
|
|
478
|
-
windowsHide: false,
|
|
479
|
-
})
|
|
480
|
-
if (typeof child.on === 'function') {
|
|
481
|
-
child.on('error', () => {})
|
|
482
|
-
}
|
|
483
|
-
child.unref()
|
|
484
|
-
return {
|
|
485
|
-
installed: true,
|
|
486
|
-
launched: true,
|
|
487
|
-
exePath: guard.exePath,
|
|
488
|
-
guardHome: guard.guardHome,
|
|
489
|
-
releaseUrl: RELEASE_URL,
|
|
490
|
-
installerUrl: INSTALLER_URL,
|
|
491
|
-
repoUrl: REPO_URL,
|
|
492
|
-
message: `已在桌面拉起 DSHGuard 守护壳(${basename(guard.exePath)})。`,
|
|
493
|
-
}
|
|
494
|
-
} catch (err) {
|
|
495
|
-
return {
|
|
496
|
-
installed: true,
|
|
497
|
-
launched: false,
|
|
498
|
-
exePath: guard.exePath,
|
|
499
|
-
guardHome: guard.guardHome,
|
|
500
|
-
releaseUrl: RELEASE_URL,
|
|
501
|
-
installerUrl: INSTALLER_URL,
|
|
502
|
-
repoUrl: REPO_URL,
|
|
503
|
-
message: `拉起 DSHGuard 守护壳失败:${err && err.message ? err.message : String(err)}`,
|
|
504
|
-
}
|
|
505
|
-
}
|
|
1860
|
+
if (!options.launch || options.dryRun) {
|
|
1861
|
+
return {
|
|
1862
|
+
ok: true,
|
|
1863
|
+
installed: true,
|
|
1864
|
+
launched: Boolean(options.dryRun && options.launch),
|
|
1865
|
+
dryRun: Boolean(options.dryRun),
|
|
1866
|
+
exePath: guard.exePath,
|
|
1867
|
+
message: `已定位到桌面端:${guard.exePath}${options.launch ? '(未拉起进程)' : ''}`,
|
|
1868
|
+
releaseUrl: RELEASE_URL,
|
|
1869
|
+
installerUrl: INSTALLER_URL,
|
|
1870
|
+
installUrl: INSTALLER_URL,
|
|
1871
|
+
};
|
|
506
1872
|
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
1873
|
+
try {
|
|
1874
|
+
const child = spawn(guard.exePath, [], {
|
|
1875
|
+
detached: true,
|
|
1876
|
+
stdio: 'ignore',
|
|
1877
|
+
windowsHide: false,
|
|
1878
|
+
});
|
|
1879
|
+
child.unref();
|
|
1880
|
+
return {
|
|
1881
|
+
ok: true,
|
|
1882
|
+
installed: true,
|
|
1883
|
+
launched: true,
|
|
1884
|
+
exePath: guard.exePath,
|
|
1885
|
+
pid: child.pid || null,
|
|
1886
|
+
message: `已启动桌面端:${guard.exePath}`,
|
|
1887
|
+
releaseUrl: RELEASE_URL,
|
|
1888
|
+
installerUrl: INSTALLER_URL,
|
|
1889
|
+
installUrl: INSTALLER_URL,
|
|
1890
|
+
};
|
|
1891
|
+
} catch (err) {
|
|
1892
|
+
return {
|
|
1893
|
+
ok: false,
|
|
1894
|
+
installed: true,
|
|
1895
|
+
launched: false,
|
|
1896
|
+
reason: 'spawn-error',
|
|
1897
|
+
exePath: guard.exePath,
|
|
1898
|
+
message: `启动失败:${err instanceof Error ? err.message : String(err)}`,
|
|
1899
|
+
releaseUrl: RELEASE_URL,
|
|
1900
|
+
installerUrl: INSTALLER_URL,
|
|
1901
|
+
installUrl: INSTALLER_URL,
|
|
1902
|
+
};
|
|
517
1903
|
}
|
|
518
1904
|
}
|
|
519
1905
|
|
|
520
1906
|
export function formatHealthText(report) {
|
|
521
|
-
const
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
+ (p.unregisteredDeps.length ? ` | 未登记: ${p.unregisteredDeps.join(', ')}` : '')
|
|
535
|
-
)
|
|
536
|
-
}
|
|
537
|
-
const cred = report.credentials
|
|
538
|
-
const refTotal = cred.referencedKeys.length
|
|
539
|
-
const refReady = cred.referencedKeys.filter((r) => r.ready).length
|
|
540
|
-
lines.push(
|
|
541
|
-
`- [凭据脱敏对账] .credentials.yaml ${cred.fileExists ? `已存在(非空键 ${cred.nonEmptyKeysCount}/${cred.totalKeysCount})` : '未创建'}`
|
|
542
|
-
+ (refTotal > 0 ? ` | patch 引用键就绪 ${refReady}/${refTotal}` : '')
|
|
543
|
-
+ (cred.missingReferencedKeys.length ? ` | 缺失: ${cred.missingReferencedKeys.join(', ')}` : '')
|
|
544
|
-
)
|
|
1907
|
+
const cred = report.credentials;
|
|
1908
|
+
const provCount = Array.isArray(report.providers) ? report.providers.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;
|
|
1912
|
+
const lines = [
|
|
1913
|
+
`[dsh-guard v${report.companionVersion}] DSH Home: ${report.dshHome} (${report.dshHomeExists ? '已找到' : '未找到'})`,
|
|
1914
|
+
`桌面端: ${report.guard.installed ? `已安装 (${report.guard.exePath})` : report.platform === 'win32' ? '未检测到本地 DSHGuard.exe(非必需,插件功能可独立运行)' : `${report.platform}(原生桌面端仅限 Windows)`}`,
|
|
1915
|
+
`当前运行端 (${activeName}): ${p?.exists ? `${p.totalDependencies} 依赖(第三方 ${p.thirdPartyCount}),MCP ${mcpCount},断链 ${p.brokenLinkCount},patch=${p.patchHash || '无'}` : '未找到'}`,
|
|
1916
|
+
];
|
|
1917
|
+
const ctxSummary = report.contextAudit
|
|
1918
|
+
? ` · 技能 ${report.contextAudit.skills?.modelVisibleCount || 0}/${report.contextAudit.skills?.total || 0}(模型可见)`
|
|
1919
|
+
: '';
|
|
545
1920
|
lines.push(
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
)
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
lines.push(` ! ${issue}`)
|
|
554
|
-
}
|
|
1921
|
+
`凭据与模型: ${cred.present ? `${cred.count} 个密钥引用(含 ${cred.protectedCount} 保护账号)` : '未找到 .credentials.yaml'} · ${provCount} 个模型提供商${ctxSummary}`,
|
|
1922
|
+
);
|
|
1923
|
+
lines.push(`快照: 共 ${report.snapshots.total} 份`);
|
|
1924
|
+
if (report.driftWarnings.length > 0) {
|
|
1925
|
+
lines.push(`提示: ${report.driftWarnings.join(';')}`);
|
|
1926
|
+
} else {
|
|
1927
|
+
lines.push(`状态: ${activeName} 档案结构健康且无断链。`);
|
|
555
1928
|
}
|
|
556
|
-
return lines.join('\n')
|
|
1929
|
+
return lines.join('\n');
|
|
557
1930
|
}
|
|
558
1931
|
|
|
559
|
-
export function formatSnapshotsText(
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
1932
|
+
export function formatSnapshotsText(snapReport) {
|
|
1933
|
+
const lines = [
|
|
1934
|
+
`[dsh-guard] 快照目录: ${snapReport.pluginSnapshotsDir}`,
|
|
1935
|
+
`累计快照: ${snapReport.total} 份(展示最近 ${snapReport.snapshots.length} 份)`,
|
|
1936
|
+
];
|
|
1937
|
+
if (snapReport.snapshots.length === 0) {
|
|
1938
|
+
lines.push('暂无快照。在插件 UI 快照页签或运行 /guard backup 即可生成本地配置快照。');
|
|
1939
|
+
return lines.join('\n');
|
|
564
1940
|
}
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
const
|
|
568
|
-
|
|
1941
|
+
for (const s of snapReport.snapshots) {
|
|
1942
|
+
const srcTag = s.source === 'desktop' ? '桌面端' : '插件';
|
|
1943
|
+
const pinTag = s.pinned ? '📌 ' : '';
|
|
1944
|
+
const diffTag = s.changedCount > 0 ? ` · 与磁盘有 ${s.changedCount} 处差异` : '';
|
|
1945
|
+
lines.push(`- ${pinTag}${s.id} [${srcTag}/${s.target}/${s.kind}]${s.reason ? ` (${s.reason})` : ''} · ${s.itemCount} 文件${diffTag}`);
|
|
569
1946
|
}
|
|
570
|
-
return lines.join('\n')
|
|
1947
|
+
return lines.join('\n');
|
|
571
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
|
+
};
|