dsh-agent-control-center 0.1.0 → 0.3.0

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/README.md +217 -83
  3. package/README.zh.md +159 -58
  4. package/client.js +7660 -2005
  5. package/cordis.patch.yml +5 -0
  6. package/docs/01-CONTRACT.md +3 -2
  7. package/docs/05-ACCEPTANCE-EVIDENCE.md +81 -0
  8. package/docs/06-UX-OPTIMIZATION.md +57 -0
  9. package/docs/07-GUIDE.md +327 -0
  10. package/docs/08-COMPATIBILITY.md +202 -0
  11. package/docs/09-ARCHITECTURE.md +333 -0
  12. package/docs/ROADMAP.md +448 -0
  13. package/index.js +67 -2
  14. package/lib/core/cache.js +277 -0
  15. package/lib/core/compat.js +877 -0
  16. package/lib/core/errors.js +14 -1
  17. package/lib/core/http.js +22 -0
  18. package/lib/core/index.js +53 -2
  19. package/lib/core/paths.js +6 -0
  20. package/lib/core/registry.js +21 -5
  21. package/lib/core/util.js +4 -1
  22. package/lib/modules/a-agents.js +104 -4
  23. package/lib/modules/b-tools.js +169 -26
  24. package/lib/modules/f-diagnostics.js +109 -17
  25. package/lib/modules/g-templates.js +18 -0
  26. package/lib/modules/i-recovery.js +84 -23
  27. package/lib/modules/j-instruction.js +624 -0
  28. package/lib/modules/k-export.js +540 -0
  29. package/package.json +1 -1
  30. package/scripts/release.mjs +81 -0
  31. package/scripts/verify.mjs +12 -0
  32. package/src/client/app.js +684 -118
  33. package/src/client/i18n/agents.js +96 -0
  34. package/src/client/i18n/common.js +36 -0
  35. package/src/client/i18n/diagnostics.js +52 -0
  36. package/src/client/i18n/export.js +174 -0
  37. package/src/client/i18n/instruction.js +236 -0
  38. package/src/client/i18n/meta.js +72 -0
  39. package/src/client/i18n/overview.js +38 -0
  40. package/src/client/i18n/recovery.js +66 -0
  41. package/src/client/i18n/sessions.js +64 -0
  42. package/src/client/i18n/templates.js +88 -0
  43. package/src/client/i18n/tools.js +96 -0
  44. package/src/client/i18n/usage.js +42 -0
  45. package/src/client/kernel.js +327 -40
  46. package/src/client/pages/agents.js +637 -354
  47. package/src/client/pages/diagnostics.js +526 -177
  48. package/src/client/pages/export.js +664 -0
  49. package/src/client/pages/instruction.js +648 -0
  50. package/src/client/pages/meta.js +553 -193
  51. package/src/client/pages/overview.js +255 -34
  52. package/src/client/pages/recovery.js +332 -131
  53. package/src/client/pages/sessions.js +470 -307
  54. package/src/client/pages/templates.js +691 -381
  55. package/src/client/pages/tools.js +559 -206
  56. package/src/client/pages/usage.js +235 -57
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import path from 'node:path'
13
13
  import { listDirSafe, readJsonSafe, readTextSafe, removeFileSafe, statSafe, writeFileAtomic } from '../core/atomic.js'
14
+ import { createCache, resolveCacheTtlMs, scheduleWarmup, withCacheMeta } from '../core/cache.js'
14
15
  import { notFound, unsupported, forbidden, badRequest } from '../core/errors.js'
15
16
  import { formatBytes, nowIso, redact, strParam } from '../core/util.js'
16
17
 
@@ -22,6 +23,10 @@ const AUDIT_MAX_BYTES = 4 * 1024 * 1024
22
23
  const TMP_STALE_MS = 60_000
23
24
  /** Diagnostics result cache lifetime for `diagnostics.summary` (overview page). */
24
25
  const SUMMARY_TTL_MS = 5 * 60_000
26
+ /** Default lifetime of a full pass; `config.cacheTtlMs` overrides it. */
27
+ const CACHE_TTL_MS = 30_000
28
+ /** One full pass per group (plus the all-groups key); never unbounded. */
29
+ const CACHE_MAX_ENTRIES = 8
25
30
  /** Capability names whose absence means the product cannot work at all. */
26
31
  const CRITICAL_CAPABILITIES = Object.freeze(['webServer', 'connection', 'fs', 'storage'])
27
32
  /** Ordering used to compare two statuses. */
@@ -32,8 +37,45 @@ const RANK = Object.freeze({ ok: 0, unknown: 1, warn: 2, error: 3 })
32
37
  */
33
38
  export default function createModule(core) {
34
39
  const { util, storage } = core
35
- /** @type {{ report: Record<string, any> | null, at: number }} */
36
- const cache = { report: null, at: 0 }
40
+ // A full pass re-probes every subsystem, including sibling modules, so the
41
+ // document is borrowed for one short TTL; the derived overview counts live
42
+ // longer because the overview renders on every navigation.
43
+ const reportTtlMs = resolveCacheTtlMs(core.config, 'diagnostics', CACHE_TTL_MS)
44
+ const summaryTtlMs = resolveCacheTtlMs(core.config, 'diagnosticsSummary', SUMMARY_TTL_MS)
45
+ const reportCache = createCache({
46
+ ttlMs: reportTtlMs,
47
+ maxEntries: CACHE_MAX_ENTRIES,
48
+ label: 'diagnostics:report',
49
+ })
50
+ const summaryCache = createCache({ ttlMs: summaryTtlMs, maxEntries: 4, label: 'diagnostics:summary' })
51
+
52
+ /**
53
+ * Cache-key fingerprint of the process-wide inputs a report depends on. The
54
+ * wall clock is absent on purpose: two passes one second apart are one entry.
55
+ * @param {string | undefined} group
56
+ * @returns {string}
57
+ */
58
+ function reportKey(group) {
59
+ return JSON.stringify([
60
+ 'diagnostics.run',
61
+ group ?? '*',
62
+ process.cwd(),
63
+ process.env.DSH_HOME ?? null,
64
+ process.env.DSH_INSTALL_DIR ?? null,
65
+ process.env.DSH_PROFILE ?? null,
66
+ typeof core.config.dshHome === 'string' ? core.config.dshHome : null,
67
+ core.version,
68
+ ])
69
+ }
70
+
71
+ /**
72
+ * The four counters that make cache behaviour observable from the API.
73
+ * @returns {{ entries: number, hits: number, misses: number, inflight: number }}
74
+ */
75
+ function cacheStats() {
76
+ const stats = reportCache.stats()
77
+ return { entries: stats.entries, hits: stats.hits, misses: stats.misses, inflight: stats.inflight }
78
+ }
37
79
 
38
80
  /** @param {string} name @returns {any} */
39
81
  function service(name) {
@@ -1174,22 +1216,54 @@ export default function createModule(core) {
1174
1216
  }
1175
1217
  }
1176
1218
 
1177
- /** @param {{ group?: string }} filter */
1219
+ /**
1220
+ * One fresh pass. The cache decision lives in {@link reportFor}; repairs and
1221
+ * exports call this directly so they always observe the current state.
1222
+ * @param {{ group?: string }} filter
1223
+ */
1178
1224
  async function runAll(filter = {}) {
1179
1225
  const specs = filter.group === undefined ? CHECKS : CHECKS.filter((spec) => spec.group === filter.group)
1180
1226
  const items = []
1181
1227
  for (const spec of specs) items.push(await runProbe(spec))
1182
- const report = {
1228
+ return {
1183
1229
  generatedAt: nowIso(),
1184
1230
  environment: await environment(),
1185
1231
  summary: summarize(items),
1186
1232
  items,
1187
1233
  }
1188
- cache.report = report
1189
- cache.at = Date.now()
1234
+ }
1235
+
1236
+ /**
1237
+ * Cached full pass. A hit returns the stored document decorated with
1238
+ * `cached`/`cacheAgeMs` plus the cache counters; `refresh:true` recomputes.
1239
+ * @param {{ group?: string }} filter
1240
+ * @param {boolean} refresh
1241
+ */
1242
+ async function reportFor(filter, refresh) {
1243
+ const resolved = await reportCache.resolve(reportKey(filter.group), () => runAll(filter), { force: refresh })
1244
+ const report = withCacheMeta(resolved)
1245
+ report.cache = cacheStats()
1190
1246
  return report
1191
1247
  }
1192
1248
 
1249
+ /**
1250
+ * Overview counts, derived from a cached pass and kept for five minutes.
1251
+ * @param {boolean} refresh
1252
+ */
1253
+ async function summaryValue(refresh) {
1254
+ const resolved = await summaryCache.resolve('diagnostics.summary', async () => {
1255
+ const report = await reportCache.resolve(reportKey(undefined), () => runAll({}), { force: refresh })
1256
+ return { summary: report.value.summary, generatedAt: report.value.generatedAt }
1257
+ }, { force: refresh })
1258
+ const value = resolved.value
1259
+ return {
1260
+ ...value.summary,
1261
+ generatedAt: value.generatedAt,
1262
+ cached: resolved.cached === true,
1263
+ cacheAgeMs: Math.max(0, Math.trunc(resolved.ageMs)),
1264
+ }
1265
+ }
1266
+
1193
1267
  /** @param {{ group?: string }} [filter] */
1194
1268
  function runFilter(params) {
1195
1269
  const group = typeof params?.group === 'string' && params.group.length > 0 ? params.group : undefined
@@ -1266,28 +1340,42 @@ export default function createModule(core) {
1266
1340
  title: 'nav.diagnostics',
1267
1341
  order: 70,
1268
1342
  requires: [],
1343
+ /** Module defaults; a numeric `config.cacheTtlMs` overrides the pass lifetime. */
1344
+ cacheDefaults: Object.freeze({ cacheTtlMs: CACHE_TTL_MS, cacheSummaryTtlMs: SUMMARY_TTL_MS, cacheMaxEntries: CACHE_MAX_ENTRIES }),
1345
+ /** Cache instances, exposed for the performance tests and operator probes. */
1346
+ caches: { report: reportCache, summary: summaryCache },
1269
1347
  async init() {
1270
1348
  // Probe only; nothing is written before the user asks for a repair.
1271
1349
  await environment()
1350
+ if (reportTtlMs <= 0 && summaryTtlMs <= 0) return
1351
+ // Warm the full pass after activation so the first page view is a cache
1352
+ // hit instead of a multi-second probe sweep. Failures only log.
1353
+ scheduleWarmup(async () => {
1354
+ try {
1355
+ await reportFor({}, false)
1356
+ await summaryValue(false)
1357
+ } catch (error) {
1358
+ try {
1359
+ core.log?.warn?.(`diagnostics prewarm failed: ${describeError(error)}`)
1360
+ } catch {
1361
+ // A logger failure must not turn into an unhandled rejection.
1362
+ }
1363
+ }
1364
+ })
1272
1365
  },
1273
1366
  probe: () => ({ state: 'FULL', detail: '' }),
1274
1367
  methods: {
1275
1368
  /** Full diagnostic pass. `group` narrows it to one group. */
1276
1369
  'diagnostics.run': async (params) => {
1277
- const filter = runFilter(util.paramsObject(params))
1278
- return runAll(filter)
1370
+ const p = util.paramsObject(params)
1371
+ const filter = runFilter(p)
1372
+ return reportFor(filter, util.boolParam(p, 'refresh', false))
1279
1373
  },
1280
1374
  /**
1281
- * Counts for the overview page. Reuses the last pass while it is fresh so
1282
- * the overview does not scan sessions on every render.
1375
+ * Counts for the overview page. Reuses a recent pass and keeps its own
1376
+ * derived copy for five minutes so the overview does not probe on render.
1283
1377
  */
1284
- 'diagnostics.summary': async () => {
1285
- if (cache.report !== null && Date.now() - cache.at < SUMMARY_TTL_MS) {
1286
- return { ...cache.report.summary, generatedAt: cache.report.generatedAt, cached: true }
1287
- }
1288
- const report = await runAll({})
1289
- return { ...report.summary, generatedAt: report.generatedAt, cached: false }
1290
- },
1378
+ 'diagnostics.summary': async (params) => summaryValue(util.boolParam(util.paramsObject(params), 'refresh', false)),
1291
1379
  /** Export the complete report as Markdown text or a structured JSON document. */
1292
1380
  'diagnostics.export': async (params) => {
1293
1381
  const p = util.paramsObject(params)
@@ -1348,6 +1436,10 @@ export default function createModule(core) {
1348
1436
  throw error
1349
1437
  }
1350
1438
  const after = await runProbe(spec)
1439
+ // A repair invalidates both cached documents, so the next run observes
1440
+ // the post-fix state instead of serving the pre-fix counts for the TTL.
1441
+ reportCache.clear()
1442
+ summaryCache.clear()
1351
1443
  const improved = RANK[after.status] < RANK[before.status]
1352
1444
  try {
1353
1445
  await storage.audit({ op: 'diagnostics.fix', target: id, result: improved ? 'ok' : 'partial', detail: `${before.status}->${after.status}` })
@@ -489,11 +489,29 @@ export default function createModule(core) {
489
489
  * @param {string} target
490
490
  * @returns {Promise<{ absolute: string, exists: boolean, text: string, bytes: number, mtimeMs: number | null, hash: string }>}
491
491
  */
492
+ /**
493
+ * Instruction file names a template is allowed to touch. Templates edit
494
+ * instructions, never arbitrary files: without this check the diff preview
495
+ * would be a file-read primitive for anything inside the read roots.
496
+ * @param {string} name
497
+ * @returns {boolean}
498
+ */
499
+ function isInstructionName(name) {
500
+ return name === 'AGENTS.md' || name === 'CLAUDE.md' || name === 'AGENTS.local.md' || name === 'CLAUDE.local.md'
501
+ }
502
+
492
503
  async function readTarget(target) {
493
504
  if (typeof target !== 'string' || target.length === 0) throw badRequest('缺少参数:path')
494
505
  if (target.length > 4096) throw badRequest('path 超长(>4096)')
495
506
  if (target.includes('\0')) throw badRequest('path 含非法字符')
507
+ const requestedName = path.basename(path.resolve(target))
508
+ if (!isInstructionName(requestedName)) {
509
+ throw forbidden('模板只能写入指令文件(AGENTS.md / CLAUDE.md / *.local.md)', { hint: `拒绝非指令文件:${requestedName.slice(0, 80)}` })
510
+ }
496
511
  const resolved = await paths.resolveRead(target)
512
+ if (path.basename(resolved.absolute) !== requestedName) {
513
+ throw forbidden('目标文件是符号链接,且指向另一个文件名', { hint: '只允许真实指令文件' })
514
+ }
497
515
  const read = await readTextSafe(resolved.absolute)
498
516
  if (!read.exists) {
499
517
  return { absolute: resolved.absolute, exists: false, text: '', bytes: 0, mtimeMs: null, hash: sha256Hex('') }
@@ -10,6 +10,7 @@
10
10
  * @module dsh-agent-control-center/modules/recovery
11
11
  */
12
12
  import { readFile } from 'node:fs/promises'
13
+ import { createCache, resolveCacheTtlMs, scheduleWarmup, withCacheMeta } from '../core/cache.js'
13
14
 
14
15
  /** Synthetic result codes produced only by `@deepseek-ai/dsh-session/repair`. */
15
16
  const RECOVERY_CODES = new Set(['TOOL_OUTCOME_UNKNOWN', 'TOOL_NOT_STARTED'])
@@ -19,6 +20,10 @@ const DEFAULT_LIMIT = 30
19
20
  const MAX_LIMIT = 100
20
21
  const SUMMARY_SCAN_LIMIT = 10
21
22
  const SUMMARY_CACHE_MS = 60_000
23
+ /** Default lifetime of one scan; `config.cacheTtlMs` overrides it. */
24
+ const SCAN_TTL_MS = 30_000
25
+ /** One entry per scan limit; the page and the summary use two of them. */
26
+ const CACHE_MAX_ENTRIES = 8
22
27
  const MAX_EVIDENCE = 12
23
28
  const MAX_TOTAL_EVENTS = 200_000
24
29
  const SUMMARY_TEXT_MAX = 200
@@ -522,10 +527,30 @@ export default function createModule(core) {
522
527
  return { session: inspected?.session ?? null, events: Array.isArray(inspected?.events) ? inspected.events : [] }
523
528
  }
524
529
 
525
- /** @type {{ at: number, result: Record<string, any> } | null} */
526
- let scanCache = null
527
- /** @type {Promise<Record<string, any>> | null} */
528
- let inflight = null
530
+ const scanTtlMs = resolveCacheTtlMs(core.config, 'recovery', SCAN_TTL_MS)
531
+ // The summary is derived from a scan of its own limit, so it keeps its own
532
+ // (longer) lifetime; a configured `recovery` value tunes both.
533
+ const summaryTtlMs = resolveCacheTtlMs(core.config, 'recovery', SUMMARY_CACHE_MS)
534
+ const scanCache = createCache({ ttlMs: scanTtlMs, maxEntries: CACHE_MAX_ENTRIES, label: 'recovery:scan' })
535
+ const summaryCache = createCache({ ttlMs: summaryTtlMs, maxEntries: 4, label: 'recovery:summary' })
536
+
537
+ /**
538
+ * A scan that hit a transient failure (`available:false`) is not stored, so
539
+ * recovering host services are retried instead of pinned for the whole TTL.
540
+ * @param {any} value
541
+ * @returns {boolean}
542
+ */
543
+ function scanCacheable(value) {
544
+ return value !== null && typeof value === 'object' && value.available === true
545
+ }
546
+
547
+ /**
548
+ * @param {number} limit
549
+ * @returns {string}
550
+ */
551
+ function scanKey(limit) {
552
+ return JSON.stringify(['recovery.scan', limit])
553
+ }
529
554
 
530
555
  /**
531
556
  * One bounded, sequential, read-only scan.
@@ -661,7 +686,6 @@ export default function createModule(core) {
661
686
  policy: POLICY,
662
687
  }
663
688
  result.audit = await recordAudit(result)
664
- scanCache = { at: Date.now(), result }
665
689
  return result
666
690
  }
667
691
 
@@ -685,18 +709,36 @@ export default function createModule(core) {
685
709
  }
686
710
  }
687
711
 
688
- /** Reuse a recent summary scan, and never run two scans at once. */
689
- async function summaryScan() {
690
- if (scanCache !== null && Date.now() - scanCache.at < SUMMARY_CACHE_MS) return scanCache.result
691
- if (inflight !== null) return inflight
692
- inflight = (async () => {
693
- try {
694
- return await scanSessions({ limit: SUMMARY_SCAN_LIMIT })
695
- } finally {
696
- inflight = null
697
- }
698
- })()
699
- return inflight
712
+ /**
713
+ * One cached scan. Concurrent callers with the same limit share one scan, so
714
+ * overlapping page loads never read the same session logs twice.
715
+ * @param {number} limit
716
+ * @param {boolean} refresh
717
+ * @returns {Promise<Record<string, any>>}
718
+ */
719
+ async function scanValue(limit, refresh) {
720
+ const resolved = await scanCache.resolve(scanKey(limit), () => scanSessions({ limit }), {
721
+ force: refresh,
722
+ shouldCache: scanCacheable,
723
+ })
724
+ return withCacheMeta(resolved)
725
+ }
726
+
727
+ /**
728
+ * Summary counts derived from a ten-session scan and kept for a minute, so the
729
+ * navigation badge and the overview do not rescan on every render.
730
+ * @param {boolean} refresh
731
+ * @returns {Promise<Record<string, any>>}
732
+ */
733
+ async function summaryValue(refresh) {
734
+ const resolved = await summaryCache.resolve('recovery.summary', async () => {
735
+ const scan = await scanCache.resolve(scanKey(SUMMARY_SCAN_LIMIT), () => scanSessions({ limit: SUMMARY_SCAN_LIMIT }), {
736
+ force: refresh,
737
+ shouldCache: scanCacheable,
738
+ })
739
+ return scan.value
740
+ }, { force: refresh })
741
+ return resolved.value
700
742
  }
701
743
 
702
744
  return {
@@ -704,9 +746,22 @@ export default function createModule(core) {
704
746
  title: 'nav.recovery',
705
747
  order: 90,
706
748
  requires: ['sessionQuery'],
749
+ /** Module defaults; a numeric `config.cacheTtlMs` overrides the scan lifetime. */
750
+ cacheDefaults: Object.freeze({ cacheTtlMs: SCAN_TTL_MS, cacheSummaryTtlMs: SUMMARY_CACHE_MS, cacheMaxEntries: CACHE_MAX_ENTRIES }),
751
+ /** Cache instances, exposed for the performance tests and operator probes. */
752
+ caches: { scan: scanCache, summary: summaryCache },
707
753
  async init() {
708
- // No startup scan: recovering state is read on demand so installing or
709
- // hot-reloading this plugin never reads every session log.
754
+ // Warm the default page scan (the 30-session view) in the background; the
755
+ // log read is bounded by the scan itself. A failed warm-up only logs and
756
+ // the first request computes, so the probe never reports the warm-up.
757
+ if (scanTtlMs <= 0) return
758
+ scheduleWarmup(() => scanValue(DEFAULT_LIMIT, false).catch((error) => {
759
+ try {
760
+ core.log?.warn?.(`recovery prewarm failed: ${util.redact(errorMessage(error), 160)}`)
761
+ } catch {
762
+ // A logger failure must not turn into an unhandled rejection.
763
+ }
764
+ }))
710
765
  },
711
766
  probe: () => {
712
767
  const scan = scanCapability()
@@ -717,10 +772,16 @@ export default function createModule(core) {
717
772
  }
718
773
  },
719
774
  methods: {
720
- /** Read-only interruption scan; every call audits counts, never content. */
721
- 'recovery.scan': async (params) => scanSessions(params),
775
+ /** Read-only interruption scan; every real scan audits counts, never content. */
776
+ 'recovery.scan': async (params) => {
777
+ const p = util.paramsObject(params)
778
+ const limit = Math.trunc(util.numParam(p, 'limit', { min: 1, max: MAX_LIMIT, fallback: DEFAULT_LIMIT }))
779
+ const refresh = util.boolParam(p, 'refresh', false)
780
+ return scanValue(limit, refresh)
781
+ },
722
782
  /** Candidate count plus scan/resume capability for Overview and Diagnostics. */
723
- 'recovery.summary': async () => {
783
+ 'recovery.summary': async (params) => {
784
+ const refresh = util.boolParam(util.paramsObject(params), 'refresh', false)
724
785
  const scan = scanCapability()
725
786
  const resume = resumeCapability()
726
787
  const base = {
@@ -733,7 +794,7 @@ export default function createModule(core) {
733
794
  return { ...base, available: false, candidates: unavailable(scan.reason, scan.hint), lastScan: null }
734
795
  }
735
796
  try {
736
- const result = await summaryScan()
797
+ const result = await summaryValue(refresh)
737
798
  if (result.available !== true) {
738
799
  return { ...base, available: true, candidates: unavailable(result.reason ?? '扫描不可用', result.hint), lastScan: null }
739
800
  }