@gluztm/dsh-guard 2.4.2 → 2.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -4,17 +4,30 @@ import {
4
4
  RELEASE_URL,
5
5
  REPO_URL,
6
6
  createSnapshot,
7
+ detectActiveProfile,
8
+ discoverProfiles,
9
+ formatContextAuditText,
7
10
  formatHealthText,
11
+ formatMcpProbeText,
8
12
  formatSnapshotsText,
13
+ inspectContextAudit,
9
14
  inspectHealth,
15
+ inspectSkills,
10
16
  inspectSnapshots,
11
17
  locateGuardInstallation,
18
+ normalizeProfileTarget,
12
19
  openGuard,
20
+ pinSnapshot,
21
+ probeMcpServers,
22
+ readAuditLog,
13
23
  repairBrokenModuleLinks,
14
24
  resolveDshHome,
15
25
  restoreSnapshotConfig,
16
26
  togglePatchEntry,
27
+ toggleSkillVisibility,
28
+ updateMcpTimeout,
17
29
  upsertCredentialKey,
30
+ validateProfileName,
18
31
  } from './inspector.mjs'
19
32
 
20
33
  let defineTool = (def) => def
@@ -144,7 +157,15 @@ function makePostRoute(ctx, routePath, handler) {
144
157
  }
145
158
  }
146
159
 
147
- function buildRouteTable(ctx) {
160
+ function resolveRouteTarget(rawTarget, defaultProfile) {
161
+ if (rawTarget === undefined || rawTarget === null || rawTarget === '' || rawTarget === 'all') {
162
+ return defaultProfile
163
+ }
164
+ return normalizeProfileTarget(String(rawTarget), null)
165
+ }
166
+
167
+ function buildRouteTable(ctx, activeProfile = detectActiveProfile({ ctx })) {
168
+ const hostProfile = normalizeProfileTarget(activeProfile) || 'web'
148
169
  return [
149
170
  {
150
171
  path: `${API_BASE}/overview`,
@@ -157,11 +178,12 @@ function buildRouteTable(ctx) {
157
178
  }
158
179
  try {
159
180
  // Server-side env vars only (DSH_HOME / DSHGUARD_HOME); never accept path params from HTTP requests.
160
- const health = inspectHealth({ target: 'all' })
161
- const snapshots = inspectSnapshots({ target: 'all', limit: 25 })
181
+ const health = inspectHealth({ activeProfile: hostProfile, ctx })
182
+ const snapshots = inspectSnapshots({ target: hostProfile, limit: 25 })
162
183
  sendJson(res, 200, {
163
184
  ok: true,
164
185
  version: PACKAGE_VERSION,
186
+ activeProfile: health.activeProfile,
165
187
  platform: process.platform,
166
188
  installerUrl: INSTALLER_URL,
167
189
  releaseUrl: RELEASE_URL,
@@ -189,7 +211,8 @@ function buildRouteTable(ctx) {
189
211
  }),
190
212
 
191
213
  makePostRoute(ctx, '/snapshots/create', async (body) => {
192
- const target = body.target === 'desktop' || body.target === 'all' ? body.target : 'web'
214
+ const target = resolveRouteTarget(body.target, hostProfile)
215
+ if (!target) return { ok: false, error: '仅支持 web 或 desktop 档案' }
193
216
  const reason = typeof body.reason === 'string' ? body.reason.slice(0, 120) : ''
194
217
  return createSnapshot(resolveDshHome(), target, 'manual', reason)
195
218
  }),
@@ -199,18 +222,50 @@ function buildRouteTable(ctx) {
199
222
  return restoreSnapshotConfig(resolveDshHome(), locateGuardInstallation(), snapshotId)
200
223
  }),
201
224
 
225
+ makePostRoute(ctx, '/snapshots/pin', async (body) => {
226
+ const snapshotId = typeof body.snapshotId === 'string' ? body.snapshotId.trim() : ''
227
+ const pinned = Boolean(body.pinned)
228
+ const pinLabel = typeof body.pinLabel === 'string' ? body.pinLabel : ''
229
+ return pinSnapshot(resolveDshHome(), snapshotId, pinned, pinLabel)
230
+ }),
231
+
202
232
  makePostRoute(ctx, '/toggle-entry', async (body) => {
203
- const target = body.target === 'desktop' ? 'desktop' : 'web'
233
+ const target = resolveRouteTarget(body.target, hostProfile)
234
+ if (!target) return { ok: false, error: '仅支持 web 或 desktop 档案' }
204
235
  const id = typeof body.id === 'string' ? body.id.trim() : ''
205
236
  const disabled = Boolean(body.disabled)
206
237
  return togglePatchEntry(resolveDshHome(), target, id, disabled, locateGuardInstallation())
207
238
  }),
208
239
 
209
240
  makePostRoute(ctx, '/repair-links', async (body) => {
210
- const target = body.target === 'desktop' ? 'desktop' : 'web'
241
+ const target = resolveRouteTarget(body.target, hostProfile)
242
+ if (!target) return { ok: false, error: '仅支持 web 或 desktop 档案' }
211
243
  return repairBrokenModuleLinks(resolveDshHome(), target)
212
244
  }),
213
245
 
246
+ makePostRoute(ctx, '/mcp/probe', async (body) => {
247
+ const target = resolveRouteTarget(body.target, hostProfile)
248
+ if (!target) return { ok: false, error: '仅支持 web 或 desktop 档案' }
249
+ const health = inspectHealth({ activeProfile: target, ctx })
250
+ return await probeMcpServers(resolveDshHome(), health.extensions, target)
251
+ }),
252
+
253
+ makePostRoute(ctx, '/mcp/timeout', async (body) => {
254
+ const target = resolveRouteTarget(body.target, hostProfile)
255
+ if (!target) return { ok: false, error: '仅支持 web 或 desktop 档案' }
256
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
257
+ return updateMcpTimeout(resolveDshHome(), target, id, body.timeoutMs, locateGuardInstallation())
258
+ }),
259
+
260
+ makePostRoute(ctx, '/skills/toggle', async (body) => {
261
+ const skillId = typeof body.skillId === 'string' ? body.skillId.trim() : ''
262
+ const changes = {}
263
+ if (typeof body.modelVisible === 'boolean') changes.modelVisible = body.modelVisible
264
+ if (typeof body.userInvocable === 'boolean') changes.userInvocable = body.userInvocable
265
+ const expectedFingerprint = typeof body.fingerprint === 'string' ? body.fingerprint : undefined
266
+ return toggleSkillVisibility(resolveDshHome(), skillId, changes, { expectedFingerprint, activeProfile: hostProfile })
267
+ }),
268
+
214
269
  makePostRoute(ctx, '/credential-key', async (body) => {
215
270
  const key = typeof body.key === 'string' ? body.key : ''
216
271
  const value = typeof body.value === 'string' ? body.value : ''
@@ -227,19 +282,20 @@ function buildRouteTable(ctx) {
227
282
  ]
228
283
  }
229
284
 
230
- function buildToolDefinitions() {
285
+ function buildToolDefinitions(ctx, activeProfile = detectActiveProfile({ ctx })) {
286
+ const hostProfile = normalizeProfileTarget(activeProfile) || 'web'
231
287
  return [
232
288
  defineTool({
233
289
  name: 'dsh_guard_status',
234
290
  description:
235
- 'Check DSH Web and Desktop profiles in-process: checks package.json dependency drift, broken module links, '
291
+ 'Check the active DSH profile (Desktop or Web) in-process: checks package.json dependency drift, broken module links, '
236
292
  + 'cordis.patch.yml plugins/MCP/llm-pi-ai readiness, masked .credentials.yaml key readiness (never exposes secret values), '
237
- + 'and local snapshot availability.',
293
+ + 'startup context load summary, and local snapshot availability.',
238
294
  parameters: {
239
295
  target: {
240
296
  type: 'string',
241
- enum: ['all', 'web', 'desktop'],
242
- description: 'Which DSH profile track to inspect (default: all).',
297
+ enum: ['web', 'desktop'],
298
+ description: 'Optional profile track override ("web" or "desktop"). Defaults to the active runtime track.',
243
299
  },
244
300
  },
245
301
  output: {
@@ -257,7 +313,8 @@ function buildToolDefinitions() {
257
313
  render: (_args, value) => [{ type: 'text', text: value.summary }],
258
314
  },
259
315
  async execute(args = {}) {
260
- const report = inspectHealth({ target: args.target })
316
+ const t = normalizeProfileTarget(args.target) || hostProfile
317
+ const report = inspectHealth({ activeProfile: t, ctx })
261
318
  return {
262
319
  healthy: report.healthy,
263
320
  issuesCount: report.issuesCount,
@@ -268,15 +325,94 @@ function buildToolDefinitions() {
268
325
  },
269
326
  }),
270
327
 
328
+ defineTool({
329
+ name: 'dsh_guard_context_audit',
330
+ description:
331
+ 'Read-only L0 audit of startup context footprint for the active DSH profile: counts active MCP servers, '
332
+ + 'model-visible Skills (~/.dsh/skills, ~/.agents/skills, plugin skills), and permanent prompt file sizes.',
333
+ parameters: {
334
+ target: {
335
+ type: 'string',
336
+ enum: ['web', 'desktop'],
337
+ description: 'Optional profile override ("web" or "desktop"). Defaults to the active runtime track.',
338
+ },
339
+ },
340
+ output: {
341
+ schema: {
342
+ type: 'object',
343
+ additionalProperties: false,
344
+ properties: {
345
+ level: { type: 'string', required: true },
346
+ estimatedBaseTokens: { type: 'integer', required: true },
347
+ recommendations: { type: 'array', required: true, items: { type: 'string' } },
348
+ summary: { type: 'string', required: true },
349
+ },
350
+ },
351
+ render: (_args, value) => [{ type: 'text', text: value.summary }],
352
+ },
353
+ async execute(args = {}) {
354
+ const dshHome = resolveDshHome()
355
+ const t = normalizeProfileTarget(args.target) || hostProfile
356
+ const health = inspectHealth({ dshHome, activeProfile: t, ctx })
357
+ const audit = inspectContextAudit(dshHome, health, t)
358
+ const p = audit.profile || audit.profiles[0] || { level: 'light', estimatedBaseTokens: 0 }
359
+ return {
360
+ level: p.level,
361
+ estimatedBaseTokens: p.estimatedBaseTokens,
362
+ recommendations: audit.recommendations,
363
+ summary: formatContextAuditText(audit),
364
+ }
365
+ },
366
+ }),
367
+
368
+ defineTool({
369
+ name: 'dsh_guard_mcp_probe',
370
+ description:
371
+ 'Read-only L0 probe for configured MCP servers on the active DSH profile: checks loopback TCP reachability '
372
+ + '(localhost/127.0.0.1/::1 only, SSRF-safe) for HTTP/SSE servers and verifies executable/script paths on disk for stdio servers.',
373
+ parameters: {
374
+ target: {
375
+ type: 'string',
376
+ enum: ['web', 'desktop'],
377
+ description: 'Optional profile override ("web" or "desktop"). Defaults to the active runtime track.',
378
+ },
379
+ },
380
+ output: {
381
+ schema: {
382
+ type: 'object',
383
+ additionalProperties: false,
384
+ properties: {
385
+ total: { type: 'integer', required: true },
386
+ activeCount: { type: 'integer', required: true },
387
+ unhealthyCount: { type: 'integer', required: true },
388
+ summary: { type: 'string', required: true },
389
+ },
390
+ },
391
+ render: (_args, value) => [{ type: 'text', text: value.summary }],
392
+ },
393
+ async execute(args = {}) {
394
+ const dshHome = resolveDshHome()
395
+ const t = normalizeProfileTarget(args.target) || hostProfile
396
+ const health = inspectHealth({ dshHome, activeProfile: t, ctx })
397
+ const probe = await probeMcpServers(dshHome, health.extensions, t)
398
+ return {
399
+ total: probe.total,
400
+ activeCount: probe.activeCount,
401
+ unhealthyCount: probe.unhealthyCount,
402
+ summary: formatMcpProbeText(probe),
403
+ }
404
+ },
405
+ }),
406
+
271
407
  defineTool({
272
408
  name: 'dsh_guard_snapshots',
273
409
  description:
274
- 'List plugin and desktop DSH configuration snapshots stored locally (separated by Web and Desktop tracks, with live file diff status).',
410
+ 'List local DSH configuration snapshots for the active profile track with live diff and pin status.',
275
411
  parameters: {
276
412
  target: {
277
413
  type: 'string',
278
- enum: ['all', 'web', 'desktop'],
279
- description: 'Filter snapshots by track (default: all).',
414
+ enum: ['web', 'desktop'],
415
+ description: 'Optional profile filter ("web" or "desktop"). Defaults to the active runtime track.',
280
416
  },
281
417
  limit: {
282
418
  type: 'integer',
@@ -297,7 +433,8 @@ function buildToolDefinitions() {
297
433
  render: (_args, value) => [{ type: 'text', text: value.summary }],
298
434
  },
299
435
  async execute(args = {}) {
300
- const report = inspectSnapshots({ target: args.target, limit: args.limit })
436
+ const t = normalizeProfileTarget(args.target) || hostProfile
437
+ const report = inspectSnapshots({ target: t, limit: args.limit })
301
438
  return {
302
439
  guardInstalled: report.guardInstalled,
303
440
  total: report.total,
@@ -314,8 +451,8 @@ function buildToolDefinitions() {
314
451
  parameters: {
315
452
  target: {
316
453
  type: 'string',
317
- enum: ['web', 'desktop', 'all'],
318
- description: 'Which profile config files to back up (default: web).',
454
+ enum: ['web', 'desktop'],
455
+ description: 'Which standard profile config files to back up ("web" or "desktop"). Defaults to active runtime track.',
319
456
  },
320
457
  reason: {
321
458
  type: 'string',
@@ -336,13 +473,17 @@ function buildToolDefinitions() {
336
473
  render: (_args, value) => [{ type: 'text', text: value.summary }],
337
474
  },
338
475
  async execute(args = {}) {
339
- const target = args.target === 'desktop' || args.target === 'all' ? args.target : 'web'
476
+ const rawTarget = typeof args.target === 'string' ? args.target.trim() : ''
477
+ const target = rawTarget ? normalizeProfileTarget(rawTarget) : hostProfile
478
+ if (!target) {
479
+ return { ok: false, snapshotId: '', itemCount: 0, summary: '仅支持 web 或 desktop 标准档案,无法创建快照。' }
480
+ }
340
481
  const res = createSnapshot(resolveDshHome(), target, 'manual', args.reason || 'Agent 手动配置备份')
341
482
  return {
342
483
  ok: Boolean(res.ok),
343
484
  snapshotId: res.snapshot.id,
344
485
  itemCount: res.snapshot.itemCount,
345
- summary: `已生成配置快照 ${res.snapshot.id}(包含 ${res.snapshot.itemCount} 个配置文件,已自动排除 .credentials.yaml)。`,
486
+ summary: `已生成配置快照 ${res.snapshot.id}(${res.snapshot.target} · ${res.snapshot.itemCount} 个配置文件,已自动排除 .credentials.yaml)。`,
346
487
  }
347
488
  },
348
489
  }),
@@ -389,8 +530,15 @@ function buildToolDefinitions() {
389
530
  }
390
531
 
391
532
  export function apply(ctx) {
533
+ let activeProfile = 'web'
534
+ try {
535
+ activeProfile = detectActiveProfile({ ctx })
536
+ } catch {
537
+ activeProfile = detectActiveProfile()
538
+ }
539
+
392
540
  ctx.inject(['tools'], (toolsCtx) => {
393
- const definitions = buildToolDefinitions()
541
+ const definitions = buildToolDefinitions(ctx, activeProfile)
394
542
  const disposers = definitions.map((def) => toolsCtx.tools.register(def))
395
543
  toolsCtx.effect(() => () => {
396
544
  for (const dispose of disposers) {
@@ -402,17 +550,30 @@ export function apply(ctx) {
402
550
  ctx.inject(['commands'], (cmdCtx) => {
403
551
  const dispose = cmdCtx.commands.register({
404
552
  name: 'guard',
405
- description: 'DSH 守护伴生命令:/guard [status|snapshots|backup [web|desktop|all]|open]',
406
- input: { hint: '[status|snapshots|backup|open]' },
553
+ description: 'DSH 守护伴生命令:/guard [status|context|mcp|snapshots|backup [web|desktop]|open]',
554
+ input: { hint: '[status|context|mcp|snapshots|backup|open]' },
407
555
  async handler(invocation) {
408
556
  const raw = String((invocation && invocation.rawInput) || '').trim()
409
557
  const parts = raw ? raw.toLowerCase().split(/\s+/) : []
410
558
  const sub = parts[0] || ''
559
+ if (sub === 'context' || sub === 'ctx') {
560
+ const dshHome = resolveDshHome()
561
+ const target = normalizeProfileTarget(parts[1]) || activeProfile
562
+ const health = inspectHealth({ dshHome, activeProfile: target, ctx })
563
+ return { kind: 'success', text: formatContextAuditText(inspectContextAudit(dshHome, health, target)) }
564
+ }
565
+ if (sub === 'mcp' || sub === 'probe') {
566
+ const dshHome = resolveDshHome()
567
+ const target = normalizeProfileTarget(parts[1]) || activeProfile
568
+ const health = inspectHealth({ dshHome, activeProfile: target, ctx })
569
+ const probe = await probeMcpServers(dshHome, health.extensions, target)
570
+ return { kind: 'success', text: formatMcpProbeText(probe) }
571
+ }
411
572
  if (sub === 'snapshots' || sub === 'snap') {
412
- return { kind: 'success', text: formatSnapshotsText(inspectSnapshots({})) }
573
+ return { kind: 'success', text: formatSnapshotsText(inspectSnapshots({ target: activeProfile })) }
413
574
  }
414
575
  if (sub === 'backup') {
415
- const t = parts[1] === 'desktop' || parts[1] === 'all' ? parts[1] : 'web'
576
+ const t = normalizeProfileTarget(parts[1]) || activeProfile
416
577
  const res = createSnapshot(resolveDshHome(), t, 'manual', '命令 /guard backup 创建')
417
578
  return {
418
579
  kind: 'success',
@@ -426,7 +587,7 @@ export function apply(ctx) {
426
587
  text: res.message + (res.installed ? '' : `\n安装包:${res.installerUrl || INSTALLER_URL}\n发布页:${res.releaseUrl}`),
427
588
  }
428
589
  }
429
- return { kind: 'success', text: formatHealthText(inspectHealth({})) }
590
+ return { kind: 'success', text: formatHealthText(inspectHealth({ activeProfile, ctx })) }
430
591
  },
431
592
  })
432
593
  if (typeof cmdCtx.effect === 'function' && typeof dispose === 'function') {
@@ -436,7 +597,7 @@ export function apply(ctx) {
436
597
 
437
598
  ctx.inject(['webServer'], (webCtx) => {
438
599
  if (!webCtx || !webCtx.webServer || typeof webCtx.webServer.register !== 'function') return
439
- for (const route of buildRouteTable(ctx)) {
600
+ for (const route of buildRouteTable(ctx, activeProfile)) {
440
601
  if (typeof webCtx.effect === 'function') {
441
602
  webCtx.effect(() => webCtx.webServer.register(route), `dsh-guard: route ${route.path}`)
442
603
  } else {
@@ -450,14 +611,27 @@ export {
450
611
  apply as default,
451
612
  name,
452
613
  createSnapshot,
614
+ detectActiveProfile,
615
+ discoverProfiles,
616
+ formatContextAuditText,
453
617
  formatHealthText,
618
+ formatMcpProbeText,
454
619
  formatSnapshotsText,
620
+ inspectContextAudit,
455
621
  inspectHealth,
622
+ inspectSkills,
456
623
  inspectSnapshots,
457
624
  locateGuardInstallation,
625
+ normalizeProfileTarget,
458
626
  openGuard,
627
+ pinSnapshot,
628
+ probeMcpServers,
629
+ readAuditLog,
459
630
  repairBrokenModuleLinks,
460
631
  restoreSnapshotConfig,
461
632
  togglePatchEntry,
633
+ toggleSkillVisibility,
634
+ updateMcpTimeout,
462
635
  upsertCredentialKey,
636
+ validateProfileName,
463
637
  }