@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
|
@@ -0,0 +1,994 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
export const STANDARD_PROFILES = new Set(['web', 'desktop']);
|
|
8
|
+
export const PROFILE_NAME_RE = /^(?:web|desktop)$/i;
|
|
9
|
+
|
|
10
|
+
const PROFILE_DIR_HINT_RE = /[\\/]profiles[\\/](desktop|web)(?:[\\/]|$)/i;
|
|
11
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
|
|
12
|
+
const SCRIPT_EXT_RE = /\.(?:m?[jt]s|cjs|py|sh|ps1)$/i;
|
|
13
|
+
const URL_LIKE_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
14
|
+
const CRED_NAME_SKIP_RE = /(?:cred|secret|token|auth|\.pem$|\.key$)/i;
|
|
15
|
+
const PRESET_SKIP_DIRS = new Set(['.system', 'node_modules']);
|
|
16
|
+
const AUDIT_REL_DIR = 'guard-state';
|
|
17
|
+
const AUDIT_FILE_NAME = 'audit.jsonl';
|
|
18
|
+
const AUDIT_MAX_LINES = 500;
|
|
19
|
+
const AUDIT_KEEP_LINES = 300;
|
|
20
|
+
const SKILL_DESC_LIMIT = 140;
|
|
21
|
+
|
|
22
|
+
export function atomicWriteText(filePath, content, secureMode = false) {
|
|
23
|
+
const dir = path.dirname(filePath);
|
|
24
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
25
|
+
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
|
26
|
+
const opts = secureMode && process.platform !== 'win32' ? { encoding: 'utf8', mode: 0o600 } : 'utf8';
|
|
27
|
+
fs.writeFileSync(tmpPath, content, opts);
|
|
28
|
+
fs.renameSync(tmpPath, filePath);
|
|
29
|
+
if (secureMode && process.platform !== 'win32') {
|
|
30
|
+
try {
|
|
31
|
+
fs.chmodSync(filePath, 0o600);
|
|
32
|
+
} catch {
|
|
33
|
+
// Ignore chmod failures on restricted filesystems.
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function sha256Text(text) {
|
|
39
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function estimateTokensFromBytes(bytes) {
|
|
43
|
+
const n = Number(bytes) || 0;
|
|
44
|
+
if (n <= 0) return 0;
|
|
45
|
+
return Math.ceil(n / 3);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Normalize a requested DSH profile target strictly to official 'web' or 'desktop'.
|
|
50
|
+
* Custom/private or unrecognized profile names are intentionally ignored.
|
|
51
|
+
*/
|
|
52
|
+
export function normalizeProfileTarget(target, fallback = null) {
|
|
53
|
+
if (typeof target !== 'string') return fallback;
|
|
54
|
+
const trimmed = target.trim().toLowerCase();
|
|
55
|
+
if (trimmed === 'web' || trimmed === 'desktop') return trimmed;
|
|
56
|
+
return fallback;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Strict profile validator: companion management scopes strictly to standard 'web' or 'desktop'.
|
|
61
|
+
*/
|
|
62
|
+
export function validateProfileName(name) {
|
|
63
|
+
return normalizeProfileTarget(name, null);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function collectCtxPathHints(ctx) {
|
|
67
|
+
const hints = [];
|
|
68
|
+
if (!ctx || typeof ctx !== 'object') return hints;
|
|
69
|
+
const push = (fn) => {
|
|
70
|
+
try {
|
|
71
|
+
const val = fn();
|
|
72
|
+
if (typeof val === 'string' && val) hints.push(val);
|
|
73
|
+
} catch {
|
|
74
|
+
// Cordis strict service Proxy throws on undeclared properties/services.
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
if (typeof ctx.get === 'function') {
|
|
78
|
+
push(() => ctx.get('loader')?.baseDir);
|
|
79
|
+
push(() => ctx.get('root')?.baseDir);
|
|
80
|
+
}
|
|
81
|
+
push(() => ctx.baseDir);
|
|
82
|
+
push(() => ctx.root?.baseDir);
|
|
83
|
+
push(() => ctx.loader?.baseDir);
|
|
84
|
+
return hints;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Automatically detect whether the current plugin runtime lives inside DSH Desktop or DSH Web.
|
|
89
|
+
*/
|
|
90
|
+
export function detectActiveProfile(options = {}) {
|
|
91
|
+
const explicit = normalizeProfileTarget(options.target || options.activeProfile);
|
|
92
|
+
if (explicit) return explicit;
|
|
93
|
+
|
|
94
|
+
const env = options.env || process.env || {};
|
|
95
|
+
const fromEnv = normalizeProfileTarget(env.DSH_PROFILE);
|
|
96
|
+
if (fromEnv) return fromEnv;
|
|
97
|
+
|
|
98
|
+
const ctx = options.ctx || null;
|
|
99
|
+
const pathHints = [
|
|
100
|
+
...collectCtxPathHints(ctx),
|
|
101
|
+
env.DSH_PROFILE_DIR,
|
|
102
|
+
];
|
|
103
|
+
for (const hint of pathHints) {
|
|
104
|
+
if (typeof hint === 'string' && hint) {
|
|
105
|
+
const m = PROFILE_DIR_HINT_RE.exec(hint);
|
|
106
|
+
if (m && m[1]) return m[1].toLowerCase();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const argv = Array.isArray(options.argv) ? options.argv : process.argv;
|
|
111
|
+
if (Array.isArray(argv)) {
|
|
112
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
113
|
+
const arg = String(argv[i] || '');
|
|
114
|
+
if (arg === '--profile' && i + 1 < argv.length) {
|
|
115
|
+
const val = normalizeProfileTarget(argv[i + 1]);
|
|
116
|
+
if (val) return val;
|
|
117
|
+
} else if (arg.startsWith('--profile=')) {
|
|
118
|
+
const val = normalizeProfileTarget(arg.slice('--profile='.length));
|
|
119
|
+
if (val) return val;
|
|
120
|
+
}
|
|
121
|
+
if (/dsh-desktop-host/i.test(arg)) return 'desktop';
|
|
122
|
+
const dirMatch = PROFILE_DIR_HINT_RE.exec(arg);
|
|
123
|
+
if (dirMatch && dirMatch[1]) return dirMatch[1].toLowerCase();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const cwd = typeof options.cwd === 'string' ? options.cwd : process.cwd();
|
|
128
|
+
if (cwd) {
|
|
129
|
+
const cwdMatch = PROFILE_DIR_HINT_RE.exec(cwd);
|
|
130
|
+
if (cwdMatch && cwdMatch[1]) return cwdMatch[1].toLowerCase();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const versions = options.versions || process.versions || {};
|
|
134
|
+
if (versions.electron) return 'desktop';
|
|
135
|
+
|
|
136
|
+
if (options.preferExistingOnCli && options.dshHome) {
|
|
137
|
+
const hasPkg = (p) => {
|
|
138
|
+
try {
|
|
139
|
+
const raw = fs.readFileSync(path.join(options.dshHome, 'profiles', p, 'package.json'), 'utf8');
|
|
140
|
+
const pkg = JSON.parse(raw);
|
|
141
|
+
return pkg?.dependencies && Object.keys(pkg.dependencies).length > 0;
|
|
142
|
+
} catch {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
if (!hasPkg('web') && hasPkg('desktop')) return 'desktop';
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return 'web';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Probe only official standard DSH profiles ('web' / 'desktop') that exist on disk.
|
|
154
|
+
* Never scans custom/headless/private profile directories.
|
|
155
|
+
*/
|
|
156
|
+
export function discoverProfiles(dshHome) {
|
|
157
|
+
const found = [];
|
|
158
|
+
for (const name of ['web', 'desktop']) {
|
|
159
|
+
const dir = path.join(dshHome, 'profiles', name);
|
|
160
|
+
const hasMarker =
|
|
161
|
+
fs.existsSync(path.join(dir, 'package.json')) ||
|
|
162
|
+
fs.existsSync(path.join(dir, 'cordis.patch.yml')) ||
|
|
163
|
+
fs.existsSync(path.join(dir, 'cordis.yml'));
|
|
164
|
+
if (hasMarker) found.push(name);
|
|
165
|
+
}
|
|
166
|
+
return found;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function getAuditFilePath(dshHome) {
|
|
170
|
+
return path.join(dshHome, AUDIT_REL_DIR, AUDIT_FILE_NAME);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function sanitizeAuditField(val, maxLen = 160) {
|
|
174
|
+
return String(val ?? '')
|
|
175
|
+
.replace(/[\r\n\t]+/g, ' ')
|
|
176
|
+
.trim()
|
|
177
|
+
.slice(0, maxLen);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Append a redacted configuration mutation audit entry into `<dshHome>/guard-state/audit.jsonl`.
|
|
182
|
+
* Accepts ONLY allowlisted structural fields (never stores secrets or raw payloads).
|
|
183
|
+
*/
|
|
184
|
+
export function appendAuditEntry(dshHome, entry = {}) {
|
|
185
|
+
if (!dshHome) return null;
|
|
186
|
+
try {
|
|
187
|
+
const filePath = getAuditFilePath(dshHome);
|
|
188
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
189
|
+
const record = {
|
|
190
|
+
ts: new Date().toISOString(),
|
|
191
|
+
action: sanitizeAuditField(entry.action || 'unknown', 48),
|
|
192
|
+
target: sanitizeAuditField(entry.target || 'global', 64),
|
|
193
|
+
summary: sanitizeAuditField(entry.summary || '', 220),
|
|
194
|
+
snapshotId: sanitizeAuditField(entry.snapshotId || '', 96),
|
|
195
|
+
ok: entry.ok !== false,
|
|
196
|
+
};
|
|
197
|
+
fs.appendFileSync(filePath, `${JSON.stringify(record)}\n`, 'utf8');
|
|
198
|
+
|
|
199
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
200
|
+
const lines = raw.split('\n').filter((line) => line.trim());
|
|
201
|
+
if (lines.length > AUDIT_MAX_LINES) {
|
|
202
|
+
const trimmed = `${lines.slice(-AUDIT_KEEP_LINES).join('\n')}\n`;
|
|
203
|
+
atomicWriteText(filePath, trimmed);
|
|
204
|
+
}
|
|
205
|
+
return record;
|
|
206
|
+
} catch {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Read the most recent redacted change audit entries in reverse chronological order.
|
|
213
|
+
*/
|
|
214
|
+
export function readAuditLog(dshHome, limit = 25) {
|
|
215
|
+
const max = Number.isFinite(Number(limit)) ? Math.max(1, Math.min(100, Number(limit))) : 25;
|
|
216
|
+
const filePath = getAuditFilePath(dshHome);
|
|
217
|
+
if (!fs.existsSync(filePath)) return [];
|
|
218
|
+
try {
|
|
219
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
220
|
+
const lines = raw.split('\n').filter((line) => line.trim());
|
|
221
|
+
const recent = lines.slice(-max).reverse();
|
|
222
|
+
const records = [];
|
|
223
|
+
for (const line of recent) {
|
|
224
|
+
try {
|
|
225
|
+
const parsed = JSON.parse(line);
|
|
226
|
+
if (parsed && typeof parsed === 'object') {
|
|
227
|
+
records.push({
|
|
228
|
+
ts: String(parsed.ts || ''),
|
|
229
|
+
action: String(parsed.action || ''),
|
|
230
|
+
target: String(parsed.target || ''),
|
|
231
|
+
summary: String(parsed.summary || ''),
|
|
232
|
+
snapshotId: String(parsed.snapshotId || ''),
|
|
233
|
+
ok: parsed.ok !== false,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
} catch {
|
|
237
|
+
// Ignore malformed single lines cleanly.
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return records;
|
|
241
|
+
} catch {
|
|
242
|
+
return [];
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function commandExistsInPath(cmd) {
|
|
247
|
+
const raw = String(cmd || '').trim();
|
|
248
|
+
if (!raw) return false;
|
|
249
|
+
if (raw.includes('/') || raw.includes('\\') || path.isAbsolute(raw)) {
|
|
250
|
+
if (fs.existsSync(raw)) return true;
|
|
251
|
+
if (process.platform === 'win32' && !path.extname(raw)) {
|
|
252
|
+
const exts = (process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean);
|
|
253
|
+
return exts.some((ext) => fs.existsSync(`${raw}${ext.toLowerCase()}`) || fs.existsSync(`${raw}${ext.toUpperCase()}`));
|
|
254
|
+
}
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const pathEnv = process.env.PATH || process.env.Path || '';
|
|
259
|
+
const dirs = pathEnv.split(path.delimiter).filter(Boolean);
|
|
260
|
+
const exts = process.platform === 'win32'
|
|
261
|
+
? (path.extname(raw) ? [''] : (process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean))
|
|
262
|
+
: [''];
|
|
263
|
+
|
|
264
|
+
for (const dir of dirs) {
|
|
265
|
+
for (const ext of exts) {
|
|
266
|
+
const candidate = path.join(dir, `${raw}${ext}`);
|
|
267
|
+
try {
|
|
268
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
} catch {
|
|
272
|
+
// Continue scanning PATH entries.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function findFirstScriptArg(args) {
|
|
280
|
+
if (!Array.isArray(args)) return null;
|
|
281
|
+
for (const raw of args) {
|
|
282
|
+
const arg = String(raw || '').trim();
|
|
283
|
+
if (!arg || arg.startsWith('-') || URL_LIKE_RE.test(arg)) continue;
|
|
284
|
+
const looksPath =
|
|
285
|
+
path.isAbsolute(arg) ||
|
|
286
|
+
arg.startsWith('./') ||
|
|
287
|
+
arg.startsWith('.\\') ||
|
|
288
|
+
arg.startsWith('../') ||
|
|
289
|
+
arg.startsWith('..\\') ||
|
|
290
|
+
arg.includes('/') ||
|
|
291
|
+
arg.includes('\\') ||
|
|
292
|
+
SCRIPT_EXT_RE.test(arg);
|
|
293
|
+
if (looksPath) return arg;
|
|
294
|
+
}
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function probeLocalTcpPort(host, port, timeoutMs = 1200) {
|
|
299
|
+
return new Promise((resolve) => {
|
|
300
|
+
const started = Date.now();
|
|
301
|
+
let settled = false;
|
|
302
|
+
const socket = net.createConnection({ host, port });
|
|
303
|
+
|
|
304
|
+
const done = (result) => {
|
|
305
|
+
if (settled) return;
|
|
306
|
+
settled = true;
|
|
307
|
+
try {
|
|
308
|
+
socket.destroy();
|
|
309
|
+
} catch {
|
|
310
|
+
// Ignore socket cleanup errors.
|
|
311
|
+
}
|
|
312
|
+
resolve(result);
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
socket.setTimeout(timeoutMs);
|
|
316
|
+
socket.once('connect', () => {
|
|
317
|
+
done({ status: 'reachable', latencyMs: Math.max(0, Date.now() - started) });
|
|
318
|
+
});
|
|
319
|
+
socket.once('timeout', () => {
|
|
320
|
+
done({ status: 'unreachable', errorCode: 'ETIMEDOUT' });
|
|
321
|
+
});
|
|
322
|
+
socket.once('error', (err) => {
|
|
323
|
+
done({
|
|
324
|
+
status: 'unreachable',
|
|
325
|
+
errorCode: err && err.code ? String(err.code) : 'ERR_CONNECT',
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Safely probe a single MCP server entry without executing third-party code or hitting remote URLs (SSRF-safe).
|
|
333
|
+
*/
|
|
334
|
+
export async function probeMcpServerEntry(entry, options = {}) {
|
|
335
|
+
const timeoutMs = Number.isFinite(Number(options.timeoutMs)) ? Math.max(200, Math.min(5000, Number(options.timeoutMs))) : 1200;
|
|
336
|
+
const profileDir = options.profileDir || '';
|
|
337
|
+
const base = {
|
|
338
|
+
id: String(entry?.id || ''),
|
|
339
|
+
serverName: String(entry?.serverName || entry?.id || ''),
|
|
340
|
+
transport: String(entry?.transport || (entry?.url ? 'sse' : 'stdio')),
|
|
341
|
+
enabled: Boolean(entry?.enabled),
|
|
342
|
+
toolCallTimeoutMs: Number(entry?.toolCallTimeoutMs || 60000),
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
if (entry?.disabled || !entry?.enabled) {
|
|
346
|
+
return { ...base, status: 'disabled', healthy: true, detail: '已禁用,未激活' };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (entry?.url) {
|
|
350
|
+
let parsed;
|
|
351
|
+
try {
|
|
352
|
+
parsed = new URL(String(entry.url));
|
|
353
|
+
} catch {
|
|
354
|
+
return { ...base, status: 'invalid_url', healthy: false, detail: `URL 格式无效: ${entry.url}` };
|
|
355
|
+
}
|
|
356
|
+
const hostLower = parsed.hostname.toLowerCase();
|
|
357
|
+
if (!LOOPBACK_HOSTS.has(hostLower)) {
|
|
358
|
+
return {
|
|
359
|
+
...base,
|
|
360
|
+
status: 'remote_skipped',
|
|
361
|
+
healthy: true,
|
|
362
|
+
detail: `远端地址跳过探测(仅探活本机回环以防 SSRF):${parsed.host}`,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
const port = parsed.port
|
|
366
|
+
? Number(parsed.port)
|
|
367
|
+
: parsed.protocol === 'https:'
|
|
368
|
+
? 443
|
|
369
|
+
: 80;
|
|
370
|
+
const probeHost = hostLower === '[::1]' ? '::1' : hostLower;
|
|
371
|
+
const tcpRes = await probeLocalTcpPort(probeHost, port, timeoutMs);
|
|
372
|
+
if (tcpRes.status === 'reachable') {
|
|
373
|
+
return {
|
|
374
|
+
...base,
|
|
375
|
+
status: 'reachable',
|
|
376
|
+
healthy: true,
|
|
377
|
+
latencyMs: tcpRes.latencyMs,
|
|
378
|
+
detail: `本机端口可达 (${probeHost}:${port} · ${tcpRes.latencyMs}ms)`,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
return {
|
|
382
|
+
...base,
|
|
383
|
+
status: 'unreachable',
|
|
384
|
+
healthy: false,
|
|
385
|
+
errorCode: tcpRes.errorCode,
|
|
386
|
+
detail: `本机端口不可达 (${probeHost}:${port} · ${tcpRes.errorCode})`,
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const command = String(entry?.command || '').trim();
|
|
391
|
+
if (!command) {
|
|
392
|
+
return { ...base, status: 'incomplete', healthy: false, detail: 'stdio 缺少 command 配置' };
|
|
393
|
+
}
|
|
394
|
+
if (!commandExistsInPath(command)) {
|
|
395
|
+
return { ...base, status: 'missing_command', healthy: false, detail: `未找到可执行命令: ${command}` };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const scriptArg = findFirstScriptArg(entry?.args);
|
|
399
|
+
if (scriptArg) {
|
|
400
|
+
const resolvedScript = path.isAbsolute(scriptArg)
|
|
401
|
+
? scriptArg
|
|
402
|
+
: profileDir
|
|
403
|
+
? path.resolve(profileDir, scriptArg)
|
|
404
|
+
: path.resolve(scriptArg);
|
|
405
|
+
if (!fs.existsSync(resolvedScript)) {
|
|
406
|
+
return {
|
|
407
|
+
...base,
|
|
408
|
+
status: 'missing_script',
|
|
409
|
+
healthy: false,
|
|
410
|
+
detail: `命令存在 (${command}),但脚本路径不存在: ${scriptArg}`,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
...base,
|
|
415
|
+
status: 'ok',
|
|
416
|
+
healthy: true,
|
|
417
|
+
detail: `命令与脚本路径均就绪 (${command})`,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
return {
|
|
422
|
+
...base,
|
|
423
|
+
status: 'ok',
|
|
424
|
+
healthy: true,
|
|
425
|
+
detail: `命令可用 (${command})`,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Probe configured MCP servers on the active profile safely without touching foreign profiles.
|
|
431
|
+
*/
|
|
432
|
+
export async function probeMcpServers(dshHome, extensionsByProfile, target = null, options = {}) {
|
|
433
|
+
const availableKeys = Object.keys(extensionsByProfile || {})
|
|
434
|
+
.map((k) => normalizeProfileTarget(k))
|
|
435
|
+
.filter(Boolean);
|
|
436
|
+
const resolvedTarget =
|
|
437
|
+
normalizeProfileTarget(target) ||
|
|
438
|
+
availableKeys[0] ||
|
|
439
|
+
detectActiveProfile(options);
|
|
440
|
+
|
|
441
|
+
const results = [];
|
|
442
|
+
const ext = extensionsByProfile?.[resolvedTarget];
|
|
443
|
+
const mcps = Array.isArray(ext?.mcpServers) ? ext.mcpServers : [];
|
|
444
|
+
const profileDir = path.join(dshHome, 'profiles', resolvedTarget);
|
|
445
|
+
for (const m of mcps) {
|
|
446
|
+
const probed = await probeMcpServerEntry(m, { ...options, profileDir });
|
|
447
|
+
results.push({ profile: resolvedTarget, ...probed });
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const active = results.filter((r) => r.status !== 'disabled');
|
|
451
|
+
const unhealthy = results.filter((r) => !r.healthy);
|
|
452
|
+
return {
|
|
453
|
+
target: resolvedTarget,
|
|
454
|
+
checkedAt: new Date().toISOString(),
|
|
455
|
+
total: results.length,
|
|
456
|
+
activeCount: active.length,
|
|
457
|
+
healthyCount: results.filter((r) => r.healthy && r.status !== 'disabled').length,
|
|
458
|
+
unhealthyCount: unhealthy.length,
|
|
459
|
+
results,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
export function formatMcpProbeText(report) {
|
|
464
|
+
const lines = [
|
|
465
|
+
`[dsh-guard MCP 探活] 当前端=${report.target} · 总计 ${report.total} 个(启用 ${report.activeCount} / 异常 ${report.unhealthyCount})`,
|
|
466
|
+
];
|
|
467
|
+
if (report.results.length === 0) {
|
|
468
|
+
lines.push('当前档案未配置 MCP 服务。');
|
|
469
|
+
return lines.join('\n');
|
|
470
|
+
}
|
|
471
|
+
for (const r of report.results) {
|
|
472
|
+
const flag = r.status === 'disabled' ? 'OFF' : r.healthy ? 'OK' : 'WARN';
|
|
473
|
+
lines.push(`- [${flag}] ${r.serverName} (${r.transport}, ${r.toolCallTimeoutMs}ms): ${r.detail}`);
|
|
474
|
+
}
|
|
475
|
+
return lines.join('\n');
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function unquoteScalar(raw) {
|
|
479
|
+
const s = String(raw || '').trim();
|
|
480
|
+
if (!s) return '';
|
|
481
|
+
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
|
482
|
+
return s.slice(1, -1);
|
|
483
|
+
}
|
|
484
|
+
return s;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function parseMarkdownFrontmatter(rawText) {
|
|
488
|
+
const eol = rawText.includes('\r\n') ? '\r\n' : '\n';
|
|
489
|
+
const hasBom = rawText.startsWith('\uFEFF');
|
|
490
|
+
const clean = hasBom ? rawText.slice(1) : rawText;
|
|
491
|
+
const lines = clean.split(/\r?\n/);
|
|
492
|
+
|
|
493
|
+
if (lines.length < 3 || lines[0].trim() !== '---') {
|
|
494
|
+
return { hasFrontmatter: false, hasBom, eol, fmStart: -1, fmEnd: -1, fields: {} };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
let fmEnd = -1;
|
|
498
|
+
for (let i = 1; i < lines.length; i += 1) {
|
|
499
|
+
if (lines[i].trim() === '---') {
|
|
500
|
+
fmEnd = i;
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (fmEnd === -1) {
|
|
505
|
+
return { hasFrontmatter: false, hasBom, eol, fmStart: -1, fmEnd: -1, fields: {} };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const fields = {};
|
|
509
|
+
for (let i = 1; i < fmEnd; i += 1) {
|
|
510
|
+
const line = lines[i];
|
|
511
|
+
if (!line.trim() || line.trim().startsWith('#') || /^\s/.test(line)) continue;
|
|
512
|
+
const colonIdx = line.indexOf(':');
|
|
513
|
+
if (colonIdx <= 0) continue;
|
|
514
|
+
const key = line.slice(0, colonIdx).trim();
|
|
515
|
+
const val = unquoteScalar(line.slice(colonIdx + 1));
|
|
516
|
+
fields[key] = val;
|
|
517
|
+
}
|
|
518
|
+
return { hasFrontmatter: true, hasBom, eol, fmStart: 0, fmEnd, fields };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function rewriteFrontmatterKeys(rawText, updates) {
|
|
522
|
+
const eol = rawText.includes('\r\n') ? '\r\n' : '\n';
|
|
523
|
+
const hasBom = rawText.startsWith('\uFEFF');
|
|
524
|
+
const clean = hasBom ? rawText.slice(1) : rawText;
|
|
525
|
+
const lines = clean.split(/\r?\n/);
|
|
526
|
+
const fm = parseMarkdownFrontmatter(rawText);
|
|
527
|
+
|
|
528
|
+
if (!fm.hasFrontmatter) {
|
|
529
|
+
const newKeys = [];
|
|
530
|
+
for (const [k, v] of Object.entries(updates)) {
|
|
531
|
+
if (v !== undefined && v !== null) newKeys.push(`${k}: ${v}`);
|
|
532
|
+
}
|
|
533
|
+
if (newKeys.length === 0) return rawText;
|
|
534
|
+
const body = `${hasBom ? '\uFEFF' : ''}---${eol}${newKeys.join(eol)}${eol}---${eol}${clean}`;
|
|
535
|
+
return body;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const fmLines = lines.slice(1, fm.fmEnd);
|
|
539
|
+
const restLines = lines.slice(fm.fmEnd + 1);
|
|
540
|
+
const nextFmLines = [];
|
|
541
|
+
const handled = new Set();
|
|
542
|
+
|
|
543
|
+
for (const line of fmLines) {
|
|
544
|
+
const trimmed = line.trim();
|
|
545
|
+
if (!trimmed || trimmed.startsWith('#') || /^\s/.test(line)) {
|
|
546
|
+
nextFmLines.push(line);
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
const colonIdx = line.indexOf(':');
|
|
550
|
+
if (colonIdx <= 0) {
|
|
551
|
+
nextFmLines.push(line);
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
const key = line.slice(0, colonIdx).trim();
|
|
555
|
+
if (Object.prototype.hasOwnProperty.call(updates, key)) {
|
|
556
|
+
handled.add(key);
|
|
557
|
+
const nextVal = updates[key];
|
|
558
|
+
if (nextVal !== undefined && nextVal !== null) {
|
|
559
|
+
nextFmLines.push(`${key}: ${nextVal}`);
|
|
560
|
+
}
|
|
561
|
+
// If nextVal === null, omit line (delete key cleanly).
|
|
562
|
+
} else {
|
|
563
|
+
nextFmLines.push(line);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
for (const [key, nextVal] of Object.entries(updates)) {
|
|
568
|
+
if (!handled.has(key) && nextVal !== undefined && nextVal !== null) {
|
|
569
|
+
nextFmLines.push(`${key}: ${nextVal}`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const rebuilt = `${hasBom ? '\uFEFF' : ''}---${eol}${nextFmLines.join(eol)}${eol}---${eol}${restLines.join(eol)}`;
|
|
574
|
+
return rebuilt;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function readSkillDescriptor(filePath, opts) {
|
|
578
|
+
let raw;
|
|
579
|
+
try {
|
|
580
|
+
raw = fs.readFileSync(filePath, 'utf8');
|
|
581
|
+
} catch {
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
584
|
+
const fm = parseMarkdownFrontmatter(raw);
|
|
585
|
+
const fields = fm.fields || {};
|
|
586
|
+
const rawName = String(fields.name || opts.fallbackName || path.basename(filePath, '.md')).trim();
|
|
587
|
+
const rawDesc = String(fields.description || '').replace(/\s+/g, ' ').trim();
|
|
588
|
+
const description = rawDesc.length > SKILL_DESC_LIMIT ? `${rawDesc.slice(0, SKILL_DESC_LIMIT - 1)}…` : rawDesc;
|
|
589
|
+
const disableModel = String(fields['disable-model-invocation'] || '').toLowerCase() === 'true';
|
|
590
|
+
const userInvocable = String(fields['user-invocable'] || '').toLowerCase() !== 'false';
|
|
591
|
+
const bytes = Buffer.byteLength(raw, 'utf8');
|
|
592
|
+
|
|
593
|
+
return {
|
|
594
|
+
id: opts.id,
|
|
595
|
+
name: rawName,
|
|
596
|
+
description,
|
|
597
|
+
source: opts.source,
|
|
598
|
+
sourceLabel: opts.sourceLabel,
|
|
599
|
+
packageName: opts.packageName || null,
|
|
600
|
+
filePath,
|
|
601
|
+
writable: Boolean(opts.writable),
|
|
602
|
+
modelVisible: !disableModel,
|
|
603
|
+
userInvocable,
|
|
604
|
+
bytes,
|
|
605
|
+
estTokens: estimateTokensFromBytes(bytes),
|
|
606
|
+
fingerprint: sha256Text(raw),
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function scanUserSkillDir(rootDir, source, sourceLabel, results) {
|
|
611
|
+
if (!rootDir || !fs.existsSync(rootDir)) return;
|
|
612
|
+
let entries = [];
|
|
613
|
+
try {
|
|
614
|
+
entries = fs.readdirSync(rootDir, { withFileTypes: true });
|
|
615
|
+
} catch {
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
for (const d of entries) {
|
|
620
|
+
if (d.name.startsWith('.') || PRESET_SKIP_DIRS.has(d.name)) continue;
|
|
621
|
+
const full = path.join(rootDir, d.name);
|
|
622
|
+
if (d.isDirectory()) {
|
|
623
|
+
const skillFile = path.join(full, 'SKILL.md');
|
|
624
|
+
if (fs.existsSync(skillFile)) {
|
|
625
|
+
const item = readSkillDescriptor(skillFile, {
|
|
626
|
+
id: `${source}:${d.name}`,
|
|
627
|
+
fallbackName: d.name,
|
|
628
|
+
source,
|
|
629
|
+
sourceLabel,
|
|
630
|
+
writable: true,
|
|
631
|
+
});
|
|
632
|
+
if (item) results.push(item);
|
|
633
|
+
}
|
|
634
|
+
} else if (d.isFile() && d.name.toLowerCase().endsWith('.md')) {
|
|
635
|
+
const base = d.name.slice(0, -3);
|
|
636
|
+
const item = readSkillDescriptor(full, {
|
|
637
|
+
id: `${source}:${d.name}`,
|
|
638
|
+
fallbackName: base,
|
|
639
|
+
source,
|
|
640
|
+
sourceLabel,
|
|
641
|
+
writable: true,
|
|
642
|
+
});
|
|
643
|
+
if (item) results.push(item);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function scanPluginSkillsInDir(pkgDir, pkgName, seenPluginSkills, results) {
|
|
649
|
+
const rootSkill = path.join(pkgDir, 'SKILL.md');
|
|
650
|
+
if (fs.existsSync(rootSkill)) {
|
|
651
|
+
const dedupeKey = `${pkgName}::root`;
|
|
652
|
+
if (!seenPluginSkills.has(dedupeKey)) {
|
|
653
|
+
seenPluginSkills.add(dedupeKey);
|
|
654
|
+
const shortPkg = pkgName.includes('/') ? pkgName.split('/').pop() : pkgName;
|
|
655
|
+
const item = readSkillDescriptor(rootSkill, {
|
|
656
|
+
id: `plugin:${pkgName}`,
|
|
657
|
+
fallbackName: shortPkg,
|
|
658
|
+
source: 'plugin',
|
|
659
|
+
sourceLabel: `插件 · ${pkgName}`,
|
|
660
|
+
packageName: pkgName,
|
|
661
|
+
writable: false,
|
|
662
|
+
});
|
|
663
|
+
if (item) results.push(item);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const skillsDir = path.join(pkgDir, 'skills');
|
|
668
|
+
if (!fs.existsSync(skillsDir)) return;
|
|
669
|
+
let subDirs = [];
|
|
670
|
+
try {
|
|
671
|
+
subDirs = fs.readdirSync(skillsDir, { withFileTypes: true });
|
|
672
|
+
} catch {
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
for (const sub of subDirs) {
|
|
677
|
+
if (!sub.isDirectory() || sub.name.startsWith('.')) continue;
|
|
678
|
+
const skillFile = path.join(skillsDir, sub.name, 'SKILL.md');
|
|
679
|
+
if (!fs.existsSync(skillFile)) continue;
|
|
680
|
+
const dedupeKey = `${pkgName}::${sub.name}`;
|
|
681
|
+
if (seenPluginSkills.has(dedupeKey)) continue;
|
|
682
|
+
seenPluginSkills.add(dedupeKey);
|
|
683
|
+
const item = readSkillDescriptor(skillFile, {
|
|
684
|
+
id: `plugin:${pkgName}:${sub.name}`,
|
|
685
|
+
fallbackName: sub.name,
|
|
686
|
+
source: 'plugin',
|
|
687
|
+
sourceLabel: `插件 · ${pkgName}`,
|
|
688
|
+
packageName: pkgName,
|
|
689
|
+
writable: false,
|
|
690
|
+
});
|
|
691
|
+
if (item) results.push(item);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* Scan global user skills (~/.dsh/skills, ~/.agents/skills) and plugin-bundled SKILL.md files.
|
|
697
|
+
* Returns metadata + byte/token estimates without exposing full prompt bodies.
|
|
698
|
+
*/
|
|
699
|
+
export function inspectSkills(dshHome, profileNames = ['web', 'desktop'], options = {}) {
|
|
700
|
+
const skills = [];
|
|
701
|
+
scanUserSkillDir(path.join(dshHome, 'skills'), 'user-dsh', '~/.dsh/skills', skills);
|
|
702
|
+
|
|
703
|
+
const agentsHome = options.agentsHome
|
|
704
|
+
? path.resolve(String(options.agentsHome))
|
|
705
|
+
: path.join(os.homedir(), '.agents');
|
|
706
|
+
scanUserSkillDir(path.join(agentsHome, 'skills'), 'user-agents', '~/.agents/skills', skills);
|
|
707
|
+
|
|
708
|
+
const seenPluginSkills = new Set();
|
|
709
|
+
for (const pName of profileNames || []) {
|
|
710
|
+
const valid = validateProfileName(pName);
|
|
711
|
+
if (!valid) continue;
|
|
712
|
+
const nmDir = path.join(dshHome, 'profiles', valid, 'node_modules');
|
|
713
|
+
if (!fs.existsSync(nmDir)) continue;
|
|
714
|
+
let entries = [];
|
|
715
|
+
try {
|
|
716
|
+
entries = fs.readdirSync(nmDir, { withFileTypes: true });
|
|
717
|
+
} catch {
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
for (const d of entries) {
|
|
721
|
+
if (d.name.startsWith('.')) continue;
|
|
722
|
+
if (d.name.startsWith('@') && d.isDirectory()) {
|
|
723
|
+
try {
|
|
724
|
+
const subs = fs.readdirSync(path.join(nmDir, d.name), { withFileTypes: true });
|
|
725
|
+
for (const sub of subs) {
|
|
726
|
+
if (!sub.isDirectory() && !sub.isSymbolicLink()) continue;
|
|
727
|
+
scanPluginSkillsInDir(path.join(nmDir, d.name, sub.name), `${d.name}/${sub.name}`, seenPluginSkills, skills);
|
|
728
|
+
}
|
|
729
|
+
} catch {
|
|
730
|
+
// Ignore unreadable scoped folder.
|
|
731
|
+
}
|
|
732
|
+
} else if (d.isDirectory() || d.isSymbolicLink()) {
|
|
733
|
+
scanPluginSkillsInDir(path.join(nmDir, d.name), d.name, seenPluginSkills, skills);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
skills.sort((a, b) => {
|
|
739
|
+
if (a.writable !== b.writable) return a.writable ? -1 : 1;
|
|
740
|
+
return a.name.localeCompare(b.name);
|
|
741
|
+
});
|
|
742
|
+
|
|
743
|
+
const modelVisibleCount = skills.filter((s) => s.modelVisible).length;
|
|
744
|
+
const userInvocableCount = skills.filter((s) => s.userInvocable).length;
|
|
745
|
+
const totalBytes = skills.reduce((sum, s) => sum + s.bytes, 0);
|
|
746
|
+
|
|
747
|
+
return {
|
|
748
|
+
total: skills.length,
|
|
749
|
+
writableCount: skills.filter((s) => s.writable).length,
|
|
750
|
+
modelVisibleCount,
|
|
751
|
+
userInvocableCount,
|
|
752
|
+
totalBytes,
|
|
753
|
+
estTokens: estimateTokensFromBytes(totalBytes),
|
|
754
|
+
skills,
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* Toggle disable-model-invocation / user-invocable keys losslessly in a writable user Skill markdown file.
|
|
760
|
+
*/
|
|
761
|
+
export function toggleSkillVisibility(dshHome, skillId, changes = {}, options = {}) {
|
|
762
|
+
const id = String(skillId || '').trim();
|
|
763
|
+
if (!id) return { ok: false, error: '缺少 Skill ID' };
|
|
764
|
+
|
|
765
|
+
const activeProf = normalizeProfileTarget(options.target || options.activeProfile) || detectActiveProfile(options);
|
|
766
|
+
const scanned = inspectSkills(dshHome, options.profileNames || [activeProf], options);
|
|
767
|
+
const skill = scanned.skills.find((s) => s.id === id);
|
|
768
|
+
if (!skill) {
|
|
769
|
+
return { ok: false, error: `未找到技能 ${id}` };
|
|
770
|
+
}
|
|
771
|
+
if (!skill.writable) {
|
|
772
|
+
return { ok: false, error: '插件内置技能为只读,请直接停用对应插件或调整用户技能' };
|
|
773
|
+
}
|
|
774
|
+
if (options.expectedFingerprint && skill.fingerprint !== options.expectedFingerprint) {
|
|
775
|
+
return { ok: false, error: '该技能文件已在磁盘被修改,请刷新后再试' };
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
const raw = fs.readFileSync(skill.filePath, 'utf8');
|
|
779
|
+
const updates = {};
|
|
780
|
+
if (typeof changes.modelVisible === 'boolean') {
|
|
781
|
+
updates['disable-model-invocation'] = changes.modelVisible ? null : 'true';
|
|
782
|
+
}
|
|
783
|
+
if (typeof changes.userInvocable === 'boolean') {
|
|
784
|
+
updates['user-invocable'] = changes.userInvocable ? null : 'false';
|
|
785
|
+
}
|
|
786
|
+
if (Object.keys(updates).length === 0) {
|
|
787
|
+
return { ok: false, error: '未指定需要修改的可见性参数' };
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
const nextContent = rewriteFrontmatterKeys(raw, updates);
|
|
791
|
+
if (nextContent !== raw) {
|
|
792
|
+
atomicWriteText(skill.filePath, nextContent);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const refreshed = readSkillDescriptor(skill.filePath, {
|
|
796
|
+
id: skill.id,
|
|
797
|
+
fallbackName: skill.name,
|
|
798
|
+
source: skill.source,
|
|
799
|
+
sourceLabel: skill.sourceLabel,
|
|
800
|
+
writable: true,
|
|
801
|
+
}) || skill;
|
|
802
|
+
|
|
803
|
+
appendAuditEntry(dshHome, {
|
|
804
|
+
action: 'skill.toggle',
|
|
805
|
+
target: skill.source,
|
|
806
|
+
summary: `${skill.name}: 模型可见=${refreshed.modelVisible ? '开' : '关'}, 命令可见=${refreshed.userInvocable ? '开' : '关'}`,
|
|
807
|
+
ok: true,
|
|
808
|
+
});
|
|
809
|
+
|
|
810
|
+
return {
|
|
811
|
+
ok: true,
|
|
812
|
+
skill: refreshed,
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* Collect metadata (byte sizes and token estimates only; never reads secret values or full content)
|
|
818
|
+
* for permanent DSH prompt files, custom prompt files, and agent presets.
|
|
819
|
+
*/
|
|
820
|
+
export function inspectPromptsMetadata(dshHome, systemPromptChars = 0) {
|
|
821
|
+
const files = [];
|
|
822
|
+
const candidates = [
|
|
823
|
+
{ id: 'prompt-inject', label: 'prompt-inject.md (全局注入)', absPath: path.join(dshHome, 'prompt-inject.md') },
|
|
824
|
+
{ id: 'memory-md', label: 'MEMORY.md (全局长期记忆)', absPath: path.join(dshHome, 'MEMORY.md') },
|
|
825
|
+
];
|
|
826
|
+
|
|
827
|
+
for (const c of candidates) {
|
|
828
|
+
let bytes = 0;
|
|
829
|
+
let exists = false;
|
|
830
|
+
try {
|
|
831
|
+
if (fs.existsSync(c.absPath)) {
|
|
832
|
+
bytes = fs.statSync(c.absPath).size;
|
|
833
|
+
exists = true;
|
|
834
|
+
}
|
|
835
|
+
} catch {
|
|
836
|
+
exists = false;
|
|
837
|
+
}
|
|
838
|
+
files.push({
|
|
839
|
+
id: c.id,
|
|
840
|
+
label: c.label,
|
|
841
|
+
exists,
|
|
842
|
+
bytes,
|
|
843
|
+
estTokens: estimateTokensFromBytes(bytes),
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
const promptsDir = path.join(dshHome, 'prompts');
|
|
848
|
+
let customPromptsCount = 0;
|
|
849
|
+
let customPromptsBytes = 0;
|
|
850
|
+
if (fs.existsSync(promptsDir)) {
|
|
851
|
+
try {
|
|
852
|
+
for (const f of fs.readdirSync(promptsDir, { withFileTypes: true })) {
|
|
853
|
+
if (!f.isFile() || !f.name.toLowerCase().endsWith('.md') || CRED_NAME_SKIP_RE.test(f.name)) continue;
|
|
854
|
+
customPromptsCount += 1;
|
|
855
|
+
customPromptsBytes += fs.statSync(path.join(promptsDir, f.name)).size;
|
|
856
|
+
}
|
|
857
|
+
} catch {
|
|
858
|
+
// Ignore unreadable prompts folder.
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
files.push({
|
|
862
|
+
id: 'custom-prompts',
|
|
863
|
+
label: `prompts/*.md (${customPromptsCount} 个)`,
|
|
864
|
+
exists: customPromptsCount > 0,
|
|
865
|
+
bytes: customPromptsBytes,
|
|
866
|
+
estTokens: estimateTokensFromBytes(customPromptsBytes),
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
const presetsDir = path.join(dshHome, '.agent-presets');
|
|
870
|
+
let presetCount = 0;
|
|
871
|
+
let presetBytes = 0;
|
|
872
|
+
if (fs.existsSync(presetsDir)) {
|
|
873
|
+
try {
|
|
874
|
+
for (const f of fs.readdirSync(presetsDir, { withFileTypes: true })) {
|
|
875
|
+
if (!f.isFile() || CRED_NAME_SKIP_RE.test(f.name)) continue;
|
|
876
|
+
presetCount += 1;
|
|
877
|
+
presetBytes += fs.statSync(path.join(presetsDir, f.name)).size;
|
|
878
|
+
}
|
|
879
|
+
} catch {
|
|
880
|
+
// Ignore unreadable presets folder.
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
if (systemPromptChars > 0) {
|
|
885
|
+
files.push({
|
|
886
|
+
id: 'system-prompt-patch',
|
|
887
|
+
label: 'system-prompt (cordis.patch.yml)',
|
|
888
|
+
exists: true,
|
|
889
|
+
bytes: systemPromptChars,
|
|
890
|
+
estTokens: estimateTokensFromBytes(systemPromptChars),
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const alwaysInjectedBytes = files
|
|
895
|
+
.filter((f) => f.id === 'prompt-inject' || f.id === 'memory-md' || f.id === 'system-prompt-patch')
|
|
896
|
+
.reduce((sum, f) => sum + f.bytes, 0);
|
|
897
|
+
|
|
898
|
+
return {
|
|
899
|
+
files,
|
|
900
|
+
presetCount,
|
|
901
|
+
presetBytes,
|
|
902
|
+
alwaysInjectedBytes,
|
|
903
|
+
alwaysInjectedTokens: estimateTokensFromBytes(alwaysInjectedBytes),
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Audit startup context load strictly for the active profile ('web' or 'desktop').
|
|
909
|
+
*/
|
|
910
|
+
export function inspectContextAudit(dshHome, healthData, target = null, options = {}) {
|
|
911
|
+
const activeProfile =
|
|
912
|
+
normalizeProfileTarget(target) ||
|
|
913
|
+
normalizeProfileTarget(healthData?.activeProfile) ||
|
|
914
|
+
detectActiveProfile(options);
|
|
915
|
+
|
|
916
|
+
const skillsReport = inspectSkills(dshHome, [activeProfile], options);
|
|
917
|
+
const prof = healthData?.profiles?.[activeProfile] || healthData?.profile || {};
|
|
918
|
+
const ext = healthData?.extensions?.[activeProfile] || { plugins: [], mcpServers: [] };
|
|
919
|
+
const plugins = Array.isArray(ext.plugins) ? ext.plugins : [];
|
|
920
|
+
const mcps = Array.isArray(ext.mcpServers) ? ext.mcpServers : [];
|
|
921
|
+
|
|
922
|
+
const enabledPlugins = plugins.filter((p) => p.enabled && !p.isCore).length;
|
|
923
|
+
const totalThirdPartyPlugins = plugins.filter((p) => !p.isCore).length;
|
|
924
|
+
const enabledMcps = mcps.filter((m) => m.enabled).length;
|
|
925
|
+
const promptMeta = inspectPromptsMetadata(dshHome, Number(prof.systemPromptChars || 0));
|
|
926
|
+
|
|
927
|
+
// Heuristic startup footprint estimate: prompt tokens + ~450 tokens per active MCP + ~65 tokens per model-visible skill catalog entry
|
|
928
|
+
const estimatedBaseTokens =
|
|
929
|
+
promptMeta.alwaysInjectedTokens +
|
|
930
|
+
enabledMcps * 450 +
|
|
931
|
+
skillsReport.modelVisibleCount * 65;
|
|
932
|
+
|
|
933
|
+
const level = estimatedBaseTokens >= 8000 || enabledMcps >= 8 || skillsReport.modelVisibleCount >= 40
|
|
934
|
+
? 'heavy'
|
|
935
|
+
: estimatedBaseTokens >= 3500 || enabledMcps >= 4 || skillsReport.modelVisibleCount >= 20
|
|
936
|
+
? 'moderate'
|
|
937
|
+
: 'light';
|
|
938
|
+
|
|
939
|
+
const profileSummary = {
|
|
940
|
+
profile: activeProfile,
|
|
941
|
+
exists: Boolean(prof.exists),
|
|
942
|
+
enabledPlugins,
|
|
943
|
+
totalThirdPartyPlugins,
|
|
944
|
+
enabledMcps,
|
|
945
|
+
totalMcps: mcps.length,
|
|
946
|
+
modelVisibleSkills: skillsReport.modelVisibleCount,
|
|
947
|
+
estimatedBaseTokens,
|
|
948
|
+
level,
|
|
949
|
+
prompts: promptMeta,
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
const recommendations = [];
|
|
953
|
+
if (enabledMcps >= 5) {
|
|
954
|
+
recommendations.push(`当前已启用 ${enabledMcps} 台 MCP 服务;停用低频 MCP 可明显减少每轮工具 schema Token 占用`);
|
|
955
|
+
}
|
|
956
|
+
if (skillsReport.modelVisibleCount >= 25 && skillsReport.writableCount > 0) {
|
|
957
|
+
recommendations.push(`共有 ${skillsReport.modelVisibleCount} 个技能对模型可见;可将低频用户技能切为仅手动 / 斜杠调用`);
|
|
958
|
+
}
|
|
959
|
+
if (promptMeta.alwaysInjectedBytes >= 12000) {
|
|
960
|
+
recommendations.push(`全局常驻注入文件合计 ${Math.round(promptMeta.alwaysInjectedBytes / 1024)} KB;建议精简 prompt-inject.md / MEMORY.md,避免每轮上下文膨胀`);
|
|
961
|
+
}
|
|
962
|
+
if (enabledPlugins >= 15) {
|
|
963
|
+
recommendations.push(`已启用 ${enabledPlugins} 个第三方插件;如感到启动变慢,可停用暂不使用的重型扩展`);
|
|
964
|
+
}
|
|
965
|
+
if (recommendations.length === 0) {
|
|
966
|
+
recommendations.push('当前常驻提示词、MCP 数量与技能可见度处于轻量健康区间');
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
return {
|
|
970
|
+
target: activeProfile,
|
|
971
|
+
activeProfile,
|
|
972
|
+
checkedAt: new Date().toISOString(),
|
|
973
|
+
profile: profileSummary,
|
|
974
|
+
profiles: [profileSummary],
|
|
975
|
+
skills: skillsReport,
|
|
976
|
+
recommendations,
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
export function formatContextAuditText(audit) {
|
|
981
|
+
const p = audit.profile || audit.profiles?.[0];
|
|
982
|
+
const lines = [
|
|
983
|
+
`[dsh-guard 上下文体检] 当前端=${audit.activeProfile || audit.target} · 技能总数 ${audit.skills.total}(模型可见 ${audit.skills.modelVisibleCount} / 可治理用户技能 ${audit.skills.writableCount})`,
|
|
984
|
+
];
|
|
985
|
+
if (p) {
|
|
986
|
+
lines.push(
|
|
987
|
+
`- ${p.profile}: 等级=${p.level} · 估算基线 ~${p.estimatedBaseTokens} tok · 启用插件 ${p.enabledPlugins}/${p.totalThirdPartyPlugins} · 启用 MCP ${p.enabledMcps}/${p.totalMcps} · 常驻注入 ${p.prompts.alwaysInjectedBytes} B`,
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
for (const rec of audit.recommendations) {
|
|
991
|
+
lines.push(` 建议: ${rec}`);
|
|
992
|
+
}
|
|
993
|
+
return lines.join('\n');
|
|
994
|
+
}
|