@cheemsup/dsh-plugin-console 0.0.0-stage → 0.2.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 (101) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +95 -3
  3. package/cordis.patch.yml +5 -0
  4. package/icon.svg +203 -0
  5. package/lib/client.activity.js +222 -0
  6. package/lib/client.apply.js +171 -0
  7. package/lib/client.changes.js +206 -0
  8. package/lib/client.cleanup.js +270 -0
  9. package/lib/client.control.js +247 -0
  10. package/lib/client.dialog.js +77 -0
  11. package/lib/client.disable-preview.js +904 -0
  12. package/lib/client.draft.js +280 -0
  13. package/lib/client.editor-messages.js +421 -0
  14. package/lib/client.editor-store.js +266 -0
  15. package/lib/client.editor.js +433 -0
  16. package/lib/client.effects.js +115 -0
  17. package/lib/client.impact-tree.js +487 -0
  18. package/lib/client.influence.js +361 -0
  19. package/lib/client.js +246 -0
  20. package/lib/client.page.js +646 -0
  21. package/lib/client.plugin-filters.js +62 -0
  22. package/lib/client.plugins.js +506 -0
  23. package/lib/client.preview-messages.js +506 -0
  24. package/lib/client.preview-raw.js +132 -0
  25. package/lib/client.preview-store.js +128 -0
  26. package/lib/client.preview-tools.js +194 -0
  27. package/lib/client.preview.js +448 -0
  28. package/lib/client.relation-graph.js +364 -0
  29. package/lib/client.schema.js +327 -0
  30. package/lib/client.search.js +409 -0
  31. package/lib/client.session-detail.js +503 -0
  32. package/lib/client.sessions.js +495 -0
  33. package/lib/client.shared.js +562 -0
  34. package/lib/client.store.js +452 -0
  35. package/lib/client.styles.js +589 -0
  36. package/lib/client.template-card.js +240 -0
  37. package/lib/client.tools.js +366 -0
  38. package/lib/client.workspace-picker.js +204 -0
  39. package/lib/host/activity.js +252 -0
  40. package/lib/host/assembly-preview.js +244 -0
  41. package/lib/host/attribution.js +341 -0
  42. package/lib/host/catalog.js +133 -0
  43. package/lib/host/categorize.js +40 -0
  44. package/lib/host/config-layers.js +589 -0
  45. package/lib/host/constants.js +69 -0
  46. package/lib/host/control.js +159 -0
  47. package/lib/host/disable-preview.js +651 -0
  48. package/lib/host/entries.js +289 -0
  49. package/lib/host/fiber.js +86 -0
  50. package/lib/host/fs.js +99 -0
  51. package/lib/host/health.js +178 -0
  52. package/lib/host/http.js +65 -0
  53. package/lib/host/impact.js +138 -0
  54. package/lib/host/injection-owners.js +60 -0
  55. package/lib/host/layers.js +132 -0
  56. package/lib/host/masks.js +145 -0
  57. package/lib/host/modes.js +96 -0
  58. package/lib/host/names.js +44 -0
  59. package/lib/host/patch-config.js +554 -0
  60. package/lib/host/patch-scan.js +103 -0
  61. package/lib/host/preview-conditions.js +281 -0
  62. package/lib/host/preview-contexts.js +174 -0
  63. package/lib/host/preview-envelope.js +31 -0
  64. package/lib/host/preview-instructions.js +450 -0
  65. package/lib/host/preview-messages.js +284 -0
  66. package/lib/host/preview-modules.js +233 -0
  67. package/lib/host/preview-skills.js +200 -0
  68. package/lib/host/prompt.js +213 -0
  69. package/lib/host/recipe-overlay.js +209 -0
  70. package/lib/host/request-preview.js +114 -0
  71. package/lib/host/routes/activation.js +96 -0
  72. package/lib/host/routes/activity.js +22 -0
  73. package/lib/host/routes/apply.js +93 -0
  74. package/lib/host/routes/cleanup.js +62 -0
  75. package/lib/host/routes/control.js +22 -0
  76. package/lib/host/routes/disable-preview.js +19 -0
  77. package/lib/host/routes/impact.js +19 -0
  78. package/lib/host/routes/operations.js +22 -0
  79. package/lib/host/routes/preview.js +58 -0
  80. package/lib/host/routes/session-influence.js +23 -0
  81. package/lib/host/routes/snapshot.js +21 -0
  82. package/lib/host/routes/template.js +54 -0
  83. package/lib/host/routes/templates.js +28 -0
  84. package/lib/host/scope-impact.js +125 -0
  85. package/lib/host/session-events.js +39 -0
  86. package/lib/host/session-influence.js +467 -0
  87. package/lib/host/sessions.js +293 -0
  88. package/lib/host/snapshot.js +218 -0
  89. package/lib/host/source-scan.js +225 -0
  90. package/lib/host/templates/cleanup.js +219 -0
  91. package/lib/host/templates/inheritance.js +144 -0
  92. package/lib/host/templates/materialize.js +317 -0
  93. package/lib/host/templates/message-overlay.js +184 -0
  94. package/lib/host/templates/repository.js +323 -0
  95. package/lib/host/templates/store.js +131 -0
  96. package/lib/host/tool-set.js +150 -0
  97. package/lib/host/tools.js +129 -0
  98. package/lib/index.js +106 -0
  99. package/locale/en.json +6 -0
  100. package/locale/zh.json +6 -0
  101. package/package.json +124 -6
@@ -0,0 +1,289 @@
1
+ /**
2
+ * 逐条采集 Loader 行。
3
+ *
4
+ * 这是快照里最重的一段采集:一行的包身份、启用状态、fiber 阶段、服务供需、
5
+ * 副作用、源码注册名、类别都在这里定下来。它只依赖前面几个纯读取模块,
6
+ * 不依赖进程内的任何缓存,所以同一份 ctx 反复调用得到同一份结果。
7
+ * @module dsh-plugin-console/host/entries
8
+ */
9
+
10
+ import { categorize } from './categorize.js'
11
+ import { FIBER_PHASE } from './constants.js'
12
+ import { readDiagnostic, readEffects } from './fiber.js'
13
+ import { barePackageName, fallbackLayer } from './names.js'
14
+ import { scanPackageRegistrations } from './source-scan.js'
15
+
16
+ /**
17
+ * 覆盖者的展示名。
18
+ *
19
+ * bundle 只给包名——`pluginManager.listBundles()` 的 `overrides` 只暴露 id,
20
+ * 不提供改了哪些键;用户层则由扫描器记到层与键,一并显示出来。
21
+ * @param {{layer: string, index?: number, keys: string[]}} info - 一条用户层归因。
22
+ * @returns {string} 用于「覆盖」一栏的文本。
23
+ */
24
+ function overrideLabel(info) {
25
+ const layer = info.layer === 'overlay'
26
+ ? (typeof info.index === 'number' ? `启动覆盖层 ${info.index + 1}` : '启动覆盖层')
27
+ : `profile patch(${info.layer})`
28
+ // 键放进花括号而不是再接一个冒号:外层已经是「覆盖来源:…」,再套冒号会读成两级。
29
+ return info.keys.length > 0 ? `${layer}{${info.keys.join('、')}}` : layer
30
+ }
31
+
32
+ /**
33
+ * @param {object} ctx - host 插件上下文。
34
+ * @param {object} packages - `pluginPackages` 服务(可缺)。
35
+ * @param {Map<string, {bundle: string, version?: string}>} rowOwner - 行 id → 首个插入它的 bundle。
36
+ * @param {Map<string, string[]>} rowOverriders - 行 id → 覆盖它的 bundle 列表。
37
+ * @param {Set<string>} userInserted - 用户 patch 插入的行 id。
38
+ * @param {Map<string, Array<{layer: string, index?: number, keys: string[]}>>} userOverrides - 行 id → 用户层覆盖记录。
39
+ * @returns {Promise<{entries: Array<object>, services: object, stats: object}>} 条目、服务供需与统计。
40
+ */
41
+ export async function collectEntries(ctx, packages, rowOwner, rowOverriders, userInserted, userOverrides) {
42
+ /** @type {Array<object>} */
43
+ const entries = []
44
+ /** @type {Map<string, string[]>} 服务名 → 提供它的运行时条目 id */
45
+ const providers = new Map()
46
+ /** @type {Map<string, string[]>} 服务名 → 需要它的运行时条目 id */
47
+ const consumers = new Map()
48
+
49
+ let loadIndex = 0
50
+ for (const entry of ctx.loader.entries()) {
51
+ const options = entry.options ?? {}
52
+ const fullId = entry.id
53
+ const rowId = fullId.startsWith('include:') ? fullId.slice('include:'.length) : fullId
54
+ const base = entry.parent?.tree?.ctx?.baseUrl
55
+ const moduleName = options.name
56
+
57
+ // 包身份与显示元信息;解析失败不影响行本身
58
+ let pkg
59
+ let meta
60
+ try {
61
+ pkg = base === undefined || !packages ? undefined : packages.packageOf(moduleName, base)
62
+ } catch {
63
+ pkg = undefined
64
+ }
65
+ try {
66
+ meta = base === undefined || !packages ? undefined : packages.metaOf(moduleName, base)
67
+ } catch {
68
+ meta = undefined
69
+ }
70
+
71
+ const manifest = pkg?.manifest
72
+ const clientDecl = manifest?.dsh?.client
73
+ const face = clientDecl?.platform === 'web' ? 'both' : 'host'
74
+
75
+ // 有效启用状态:自身表达式 + 祖先 group 继承
76
+ let ownDisabled = false
77
+ let disabledExpr
78
+ const rawDisabled = options.disabled
79
+ if (rawDisabled && typeof rawDisabled === 'object' && '__jsExpr' in rawDisabled) {
80
+ disabledExpr = rawDisabled.__jsExpr
81
+ try {
82
+ ownDisabled = Boolean(entry.evaluate?.(disabledExpr))
83
+ } catch {
84
+ ownDisabled = false
85
+ }
86
+ } else {
87
+ ownDisabled = Boolean(rawDisabled)
88
+ }
89
+ let effectiveDisabled
90
+ try {
91
+ effectiveDisabled = Boolean(entry.disabled)
92
+ } catch {
93
+ effectiveDisabled = ownDisabled
94
+ }
95
+ const inheritedDisabled = effectiveDisabled && !ownDisabled
96
+
97
+ const fiber = entry.fiber
98
+ const phase = fiber === undefined ? null : (FIBER_PHASE[fiber.state] ?? null)
99
+ const diagnostic = phase === 'failed' ? await readDiagnostic(fiber) : undefined
100
+
101
+ const requires = fiber ? Object.keys(fiber.inject ?? {}) : []
102
+ const provides = fiber
103
+ ? [...(fiber.provisions ?? [])].map((provision) => provision?.name).filter((name) => typeof name === 'string')
104
+ : []
105
+ const effects = readEffects(fiber)
106
+ const registrations = await scanPackageRegistrations(pkg?.dir)
107
+
108
+ // MCP 客户端的 serverName 决定了它注册的工具名前缀 mcp__<server>__*,
109
+ // 读配置就能把工具归属回这一行。
110
+ const mcpServerName = options.config && typeof options.config === 'object'
111
+ ? (typeof options.config.serverName === 'string' ? options.config.serverName : undefined)
112
+ : undefined
113
+
114
+ const configEntries = readConfigEntries(options.config)
115
+
116
+ const segments = fullId.split(':')
117
+ const depth = segments.length - 1
118
+ const entryRow = {
119
+ entryId: fullId,
120
+ rowId,
121
+ /** Loader 里的声明顺序。DSH 没有插件级 order,这就是组合文件的加载链顺序。 */
122
+ loadIndex,
123
+ parentEntryId: segments.length > 1 ? segments.slice(0, -1).join(':') : null,
124
+ depth,
125
+ moduleName,
126
+ packageName: barePackageName(moduleName) ?? null,
127
+ version: typeof pkg?.version === 'string' ? pkg.version : null,
128
+ packageDir: typeof pkg?.dir === 'string' ? pkg.dir : null,
129
+ title: typeof meta?.title === 'string' ? meta.title : undefined,
130
+ description: typeof meta?.description === 'string' ? meta.description : undefined,
131
+ metaError: typeof meta?.error === 'string' ? meta.error : undefined,
132
+ layer: rowOwner.get(rowId)?.bundle ?? fallbackLayer(moduleName, depth),
133
+ layerVersion: rowOwner.get(rowId)?.version ?? null,
134
+ overriddenBy: [
135
+ ...(rowOverriders.get(rowId) ?? []),
136
+ ...(userOverrides.get(rowId) ?? []).map(overrideLabel),
137
+ ],
138
+ userInserted: userInserted.has(rowId),
139
+ face,
140
+ enabled: !effectiveDisabled,
141
+ disabledExpr,
142
+ disabledValue: disabledExpr === undefined ? undefined : ownDisabled,
143
+ inheritedDisabled,
144
+ phase,
145
+ diagnostic,
146
+ requires,
147
+ provides,
148
+ effects,
149
+ registrations,
150
+ category: categorize(moduleName, registrations),
151
+ mcpServerName,
152
+ clientInject: Array.isArray(clientDecl?.inject) ? clientDecl.inject : [],
153
+ clientExternal: Array.isArray(clientDecl?.external) ? clientDecl.external : [],
154
+ configKeys: configEntries.map((row) => row.key),
155
+ configEntries,
156
+ isGroup: Boolean(options.group),
157
+ }
158
+ entries.push(entryRow)
159
+ loadIndex++
160
+
161
+ for (const name of provides) {
162
+ const list = providers.get(name) ?? []
163
+ list.push(fullId)
164
+ providers.set(name, list)
165
+ }
166
+ for (const name of requires) {
167
+ const list = consumers.get(name) ?? []
168
+ list.push(fullId)
169
+ consumers.set(name, list)
170
+ }
171
+ }
172
+
173
+ // —— 汇总:服务名 → 提供者 / 消费者 ——
174
+ const services = {}
175
+ for (const name of new Set([...providers.keys(), ...consumers.keys()])) {
176
+ services[name] = {
177
+ providers: providers.get(name) ?? [],
178
+ consumers: consumers.get(name) ?? [],
179
+ }
180
+ }
181
+
182
+ const pluginEntries = entries.filter((entry) => !entry.moduleName.startsWith('cordis:'))
183
+ const stats = {
184
+ entries: entries.length,
185
+ plugins: pluginEntries.length,
186
+ active: pluginEntries.filter((entry) => entry.phase === 'active').length,
187
+ pending: pluginEntries.filter((entry) => entry.phase === 'pending').length,
188
+ failed: pluginEntries.filter((entry) => entry.phase === 'failed').length,
189
+ disabled: pluginEntries.filter((entry) => !entry.enabled).length,
190
+ dual: pluginEntries.filter((entry) => entry.face === 'both').length,
191
+ thirdParty: pluginEntries.filter((entry) => entry.layer === 'profile' || entry.layer === 'runtime').length,
192
+ services: Object.keys(services).length,
193
+ }
194
+
195
+ return { entries, services, stats }
196
+ }
197
+
198
+ /**
199
+ * 单个配置值在快照里的展示上限。
200
+ *
201
+ * 配置里可能有整份工具 schema,不能无限塞进快照;凭据类字段都很短,
202
+ * 这个上限只截断异常大的对象,并在值末尾写明原始长度。
203
+ */
204
+ const CONFIG_VALUE_LIMIT = 2000
205
+
206
+ /**
207
+ * 把任意配置值转成可 JSON 序列化的文本。
208
+ *
209
+ * 配置由插件作者书写,可能带函数、BigInt、循环引用;直接放进快照会让
210
+ * 整份响应序列化失败,所以逐值归一,读不出来就退化成 `String(value)`。
211
+ * @param {unknown} value - `options.config` 里的一个值。
212
+ * @returns {string} 展示文本。
213
+ */
214
+ export function configText(value) {
215
+ if (typeof value === 'string') return value
216
+ if (value === undefined) return 'undefined'
217
+ if (value === null) return 'null'
218
+ if (typeof value === 'function') return `[function ${value.name || 'anonymous'}]`
219
+ if (typeof value === 'symbol') return String(value)
220
+ if (typeof value === 'bigint') return `${value}n`
221
+ try {
222
+ const text = JSON.stringify(value, replaceNonJson)
223
+ return text === undefined ? String(value) : text
224
+ } catch {
225
+ // 循环引用:正常对象走上面的快路径,只有真的序列化失败才做逐层检测。
226
+ return configTextCircular(value)
227
+ }
228
+ }
229
+
230
+ /** JSON 不认识的配置值:函数、BigInt、Symbol 转成可读文本。 */
231
+ function replaceNonJson(key, item) {
232
+ if (typeof item === 'bigint') return `${item}n`
233
+ if (typeof item === 'function') return `[function ${item.name || 'anonymous'}]`
234
+ if (typeof item === 'symbol') return String(item)
235
+ return item
236
+ }
237
+
238
+ /** 循环引用的退路:重复出现的对象标成 `[circular]`,其余照常序列化。 */
239
+ function configTextCircular(value) {
240
+ const seen = new WeakSet()
241
+ try {
242
+ return JSON.stringify(value, (key, item) => {
243
+ const replaced = replaceNonJson(key, item)
244
+ if (typeof replaced === 'object' && replaced !== null) {
245
+ if (seen.has(replaced)) return '[circular]'
246
+ seen.add(replaced)
247
+ }
248
+ return replaced
249
+ })
250
+ } catch {
251
+ return String(value)
252
+ }
253
+ }
254
+
255
+ /**
256
+ * 把 `options.config` 归一成「字段名 + 生效值」。
257
+ *
258
+ * 快照会原样带上这些值(包括凭据),因为「配置字段有哪些」不足以判断
259
+ * 插件为什么这样行为;值只经由本地面板展示,不写日志、不落盘。
260
+ * @param {unknown} config - Loader 行上的配置对象。
261
+ * @returns {Array<{key: string, value: string}>} 键值对;非对象配置返回空数组。
262
+ */
263
+ function readConfigEntries(config) {
264
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) return []
265
+ return Object.keys(config).map((key) => {
266
+ const text = configText(config[key])
267
+ return {
268
+ key,
269
+ value: text.length > CONFIG_VALUE_LIMIT
270
+ ? `${text.slice(0, CONFIG_VALUE_LIMIT)}…(已截断,共 ${text.length} 字符)`
271
+ : text,
272
+ }
273
+ })
274
+ }
275
+
276
+ /**
277
+ * 条目按模块名索引:preset 行靠它连回全局条目。
278
+ * @param {Array<object>} entries - 已采集条目。
279
+ * @returns {Map<string, Array<object>>} 模块名 → 行摘要列表。
280
+ */
281
+ export function indexRowsByModule(entries) {
282
+ const rowsByModule = new Map()
283
+ for (const entry of entries) {
284
+ const list = rowsByModule.get(entry.moduleName) ?? []
285
+ list.push({ rowId: entry.rowId, layer: entry.layer, phase: entry.phase, enabled: entry.enabled })
286
+ rowsByModule.set(entry.moduleName, list)
287
+ }
288
+ return rowsByModule
289
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * fiber 层的读取:失败诊断、副作用标签树、agent scope 标识。
3
+ *
4
+ * 这三件事都只依赖 Cordis fiber / ctx 的公开面,不依赖任何 registry,
5
+ * 因此单独成一层,供快照与物化共用。
6
+ * @module dsh-plugin-console/host/fiber
7
+ */
8
+
9
+ import { DIAGNOSTIC_TIMEOUT_MS } from './constants.js'
10
+
11
+ /**
12
+ * 读取失败 fiber 的启动诊断,带超时。
13
+ * @param {object} fiber - Cordis fiber。
14
+ * @returns {Promise<string | undefined>} 诊断文本。
15
+ */
16
+ export async function readDiagnostic(fiber) {
17
+ if (!fiber || typeof fiber.await !== 'function') return undefined
18
+ try {
19
+ await Promise.race([
20
+ fiber.await().catch((error) => {
21
+ throw error
22
+ }),
23
+ new Promise((_resolve, reject) => {
24
+ const timer = setTimeout(() => reject(new Error('__timeout__')), DIAGNOSTIC_TIMEOUT_MS)
25
+ // 定时器不阻止进程退出
26
+ if (typeof timer.unref === 'function') timer.unref()
27
+ }),
28
+ ])
29
+ return undefined
30
+ } catch (error) {
31
+ if (error instanceof Error && error.message === '__timeout__') return '诊断读取超时'
32
+ return error instanceof Error ? error.message : String(error)
33
+ }
34
+ }
35
+
36
+ /**
37
+ * 把一个 fiber 已注册的副作用整理成「它做了什么」的清单。
38
+ *
39
+ * Cordis 给每个 `ctx.effect()` 生成一个带 label 的元数据节点,`ctx.on`、`tools.register`、
40
+ * `ctx.provide` 这些公开 API 都会自己起一个有意义的 label,因此这份清单是框架给的,
41
+ * 不需要猜。子级 effect 会被压平成 `父 → 子` 的形式,便于前端直接展示。
42
+ * @param {object | undefined} fiber - Cordis fiber。
43
+ * @returns {Array<{label: string, children: Array<string>}>} 顶层 effect 及其压平后的子标签。
44
+ */
45
+ export function readEffects(fiber) {
46
+ if (fiber === undefined || typeof fiber.getEffects !== 'function') return []
47
+ let metas
48
+ try {
49
+ metas = fiber.getEffects()
50
+ } catch {
51
+ return []
52
+ }
53
+ if (!Array.isArray(metas)) return []
54
+
55
+ /** 递归收集一个元数据节点下的全部子标签。 */
56
+ const flatten = (meta) => {
57
+ const out = []
58
+ for (const child of meta?.children ?? []) {
59
+ const label = typeof child?.label === 'string' ? child.label : undefined
60
+ if (label !== undefined && label !== 'anonymous') out.push(label)
61
+ out.push(...flatten(child))
62
+ }
63
+ return out
64
+ }
65
+
66
+ return metas
67
+ .map((meta) => (typeof meta?.label === 'string' ? { label: meta.label, children: flatten(meta) } : undefined))
68
+ .filter((effect) => effect !== undefined)
69
+ }
70
+
71
+ /**
72
+ * 从 Agent 上下文里取出它的 scope 标识。
73
+ *
74
+ * `tools.view(scope)` 的 `scope` 参数是 `createScope` 写下的那个 symbol 的**值**,
75
+ * 不是 ctx 本身;直接把 ctx 传进去只会落到全局层。dsh-scope 没有把符号注册到
76
+ * `Symbol.for`,只能按描述找——这是唯一可用的公开路径。
77
+ * @param {object} ctx - 可能带 scope 标签的上下文。
78
+ * @returns {symbol | undefined} scope 标识。
79
+ */
80
+ export function scopeKeyOf(ctx) {
81
+ if (ctx === undefined || ctx === null) return undefined
82
+ for (const symbol of Object.getOwnPropertySymbols(ctx)) {
83
+ if (symbol.description === 'dsh.scope') return ctx[symbol]
84
+ }
85
+ return undefined
86
+ }
package/lib/host/fs.js ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * 只读文件访问。
3
+ *
4
+ * 快照里的每一次文件读取都是**可选的**:读不到就降级,不让整份快照失败。
5
+ * 因此这里的函数全部返回 `null` 而不是抛错。文件读取只在快照时发生,
6
+ * 不参与模块加载期。
7
+ * @module dsh-plugin-console/host/fs
8
+ */
9
+
10
+ /**
11
+ * 读一个文本文件;任何失败都返回 null。
12
+ * @param {string} file - 绝对路径。
13
+ * @returns {Promise<string | null>} 文件内容或 null。
14
+ */
15
+ export async function readTextFile(file) {
16
+ try {
17
+ const { readFile } = await import('node:fs/promises')
18
+ return await readFile(file, 'utf8')
19
+ } catch {
20
+ return null
21
+ }
22
+ }
23
+
24
+ /**
25
+ * 读一个 JSON 文件;解析失败同样返回 null。
26
+ * @param {string} file - 绝对路径。
27
+ * @returns {Promise<any | null>} 解析结果或 null。
28
+ */
29
+ export async function readJsonFile(file) {
30
+ const text = await readTextFile(file)
31
+ if (text === null) return null
32
+ try {
33
+ return JSON.parse(text)
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 列一个目录的文件名;失败返回空数组。
41
+ * @param {string} dir - 绝对路径。
42
+ * @returns {Promise<string[]>} 文件名列表。
43
+ */
44
+ export async function listDir(dir) {
45
+ try {
46
+ const { readdir } = await import('node:fs/promises')
47
+ return await readdir(dir)
48
+ } catch {
49
+ return []
50
+ }
51
+ }
52
+
53
+ /**
54
+ * 列一个目录的条目(带类型);失败返回空数组。
55
+ * @param {string} dir - 绝对路径。
56
+ * @returns {Promise<Array<{name: string, isDirectory: boolean, isFile: boolean}>>} 条目列表。
57
+ */
58
+ export async function listDirDetailed(dir) {
59
+ try {
60
+ const { readdir } = await import('node:fs/promises')
61
+ const entries = await readdir(dir, { withFileTypes: true })
62
+ return entries.map((entry) => ({
63
+ name: entry.name,
64
+ isDirectory: entry.isDirectory(),
65
+ isFile: entry.isFile(),
66
+ }))
67
+ } catch {
68
+ return []
69
+ }
70
+ }
71
+
72
+ /**
73
+ * 判断一个路径是不是目录;任何失败都返回 false。
74
+ * @param {string} dir - 绝对路径。
75
+ * @returns {Promise<boolean>} 是否是目录。
76
+ */
77
+ export async function isDirectory(dir) {
78
+ try {
79
+ const { stat } = await import('node:fs/promises')
80
+ return (await stat(dir)).isDirectory()
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 读一个文件的元信息;失败返回 null。
88
+ * @param {string} file - 绝对路径。
89
+ * @returns {Promise<{mtimeMs: number, size: number} | null>} 元信息或 null。
90
+ */
91
+ export async function statFile(file) {
92
+ try {
93
+ const { stat } = await import('node:fs/promises')
94
+ const value = await stat(file)
95
+ return { mtimeMs: value.mtimeMs, size: value.size }
96
+ } catch {
97
+ return null
98
+ }
99
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * 健康摘要与「需要关注」列表。
3
+ *
4
+ * 这一层不读新的数据源,只把快照里已经采到的事实压成两个用户问题:
5
+ * 1. 现在有多少东西不正常?(summary)
6
+ * 2. 具体是哪几项,按什么顺序看?(attention)
7
+ *
8
+ * 判断只依赖运行时事实与已有的归属索引,因此同一个快照反复计算得到同一份结果。
9
+ * 活动、错误率、延迟等需要读 session log 的指标留给后续阶段,不在这里推断。
10
+ * @module dsh-plugin-console/host/health
11
+ */
12
+
13
+ /** 严重度排序:数字越小越靠前。 */
14
+ const SEVERITY_RANK = { critical: 0, warning: 1, info: 2 }
15
+
16
+ /** 同类问题的展示顺序:先故障,再缺依赖,最后是归属。 */
17
+ const KIND_RANK = {
18
+ failed: 0,
19
+ 'missing-service': 1,
20
+ 'unattributed-tools': 2,
21
+ 'unattributed-sections': 3,
22
+ }
23
+
24
+ /** 单次最多返回多少条关注项;summary 仍保留全量计数。 */
25
+ const MAX_ATTENTION = 40
26
+
27
+ /** 结构行(cordis:include 等)不是插件,不参与健康统计。 */
28
+ function isStructural(entry) {
29
+ return typeof entry?.moduleName === 'string' && entry.moduleName.startsWith('cordis:')
30
+ }
31
+
32
+ /** 插件在界面上的名字:本地化标题优先,其次包名,最后模块名。 */
33
+ function displayName(entry) {
34
+ if (typeof entry?.title === 'string' && entry.title.length > 0) return entry.title
35
+ if (typeof entry?.packageName === 'string' && entry.packageName.length > 0) return entry.packageName
36
+ if (typeof entry?.moduleName === 'string' && entry.moduleName.length > 0) return entry.moduleName
37
+ return entry?.entryId ?? '未知插件'
38
+ }
39
+
40
+ /**
41
+ * 一个条目缺了哪些必需服务。
42
+ * @param {object} entry - 已采集的 Loader 条目。
43
+ * @param {object} services - 服务名 → `{ providers, consumers }`。
44
+ * @returns {string[]} 没有提供者的服务名。
45
+ */
46
+ function missingServicesOf(entry, services) {
47
+ return (entry?.requires ?? []).filter((name) => (services?.[name]?.providers ?? []).length === 0)
48
+ }
49
+
50
+ /** 把名字列表压成一句短摘要,避免关注项被长列表撑开。 */
51
+ function sampleNames(names, limit = 5) {
52
+ if (names.length === 0) return '(无)'
53
+ const head = names.slice(0, limit).join('、')
54
+ return names.length > limit ? `${head} 等 ${names.length} 个` : head
55
+ }
56
+
57
+ /**
58
+ * 计算健康摘要与关注项。
59
+ * @param {object} input - 快照里的相关事实。
60
+ * @param {Array<object>} [input.entries] - 全部条目(含结构行与模式合成条目)。
61
+ * @param {object} [input.services] - 服务名 → 提供者/消费者。
62
+ * @param {object} [input.tools] - 至少包含 `attributed`。
63
+ * @param {object} [input.prompt] - 至少包含 `sections` / `contexts`。
64
+ * @returns {{summary: object, attention: Array<object>}} 摘要与按严重度排序的关注项。
65
+ */
66
+ export function computeHealth(input = {}) {
67
+ const entries = Array.isArray(input.entries) ? input.entries : []
68
+ const services = input.services ?? {}
69
+ const attributedTools = Array.isArray(input.tools?.attributed) ? input.tools.attributed : []
70
+ const promptSections = Array.isArray(input.prompt?.sections) ? input.prompt.sections : []
71
+ const promptContexts = Array.isArray(input.prompt?.contexts) ? input.prompt.contexts : []
72
+ const plugins = entries.filter((entry) => !isStructural(entry))
73
+
74
+ const attention = []
75
+ let conditional = 0
76
+ let overridden = 0
77
+ let missingServices = 0
78
+
79
+ for (const entry of plugins) {
80
+ if (entry.phase === 'failed') {
81
+ attention.push({
82
+ id: 'failed:' + entry.entryId,
83
+ severity: 'critical',
84
+ kind: 'failed',
85
+ title: displayName(entry) + ' 启动失败',
86
+ detail: typeof entry.diagnostic === 'string' && entry.diagnostic.length > 0
87
+ ? entry.diagnostic
88
+ : 'fiber 阶段为 failed;诊断未返回。',
89
+ entryId: entry.entryId,
90
+ rowId: entry.rowId,
91
+ moduleName: entry.moduleName,
92
+ })
93
+ }
94
+
95
+ const missing = entry.enabled === true ? missingServicesOf(entry, services) : []
96
+ if (missing.length > 0) {
97
+ missingServices++
98
+ attention.push({
99
+ id: 'missing-service:' + entry.entryId,
100
+ severity: 'warning',
101
+ kind: 'missing-service',
102
+ title: displayName(entry) + ' 缺少服务',
103
+ detail: '没有提供者:' + missing.join('、'),
104
+ entryId: entry.entryId,
105
+ rowId: entry.rowId,
106
+ moduleName: entry.moduleName,
107
+ services: missing,
108
+ })
109
+ }
110
+
111
+ if (entry.disabledExpr !== undefined && entry.enabled !== true) {
112
+ // 条件禁用是声明语义,不一定是问题;只进 summary,不占用关注项。
113
+ conditional++
114
+ }
115
+
116
+ if ((entry.overriddenBy ?? []).length > 0) overridden++
117
+ }
118
+
119
+ const unattributedTools = attributedTools
120
+ .filter((tool) => (tool.owners ?? []).length === 0)
121
+ .map((tool) => tool.name)
122
+ const unattributedSections = [...promptSections, ...promptContexts]
123
+ .filter((row) => (row.owners ?? []).length === 0)
124
+ .map((row) => row.name)
125
+
126
+ if (unattributedTools.length > 0) {
127
+ attention.push({
128
+ id: 'unattributed-tools',
129
+ severity: 'info',
130
+ kind: 'unattributed-tools',
131
+ title: `${unattributedTools.length} 个工具没有归属`,
132
+ detail: '无法从源码字面量或 MCP 规则确定注册者:' + sampleNames(unattributedTools),
133
+ names: unattributedTools,
134
+ })
135
+ }
136
+
137
+ if (unattributedSections.length > 0) {
138
+ attention.push({
139
+ id: 'unattributed-sections',
140
+ severity: 'info',
141
+ kind: 'unattributed-sections',
142
+ title: `${unattributedSections.length} 个提示词段没有归属`,
143
+ detail: '无法从源码字面量确定注册者:' + sampleNames(unattributedSections),
144
+ names: unattributedSections,
145
+ })
146
+ }
147
+
148
+ attention.sort((left, right) => {
149
+ const severity = (SEVERITY_RANK[left.severity] ?? 9) - (SEVERITY_RANK[right.severity] ?? 9)
150
+ if (severity !== 0) return severity
151
+ const kind = (KIND_RANK[left.kind] ?? 9) - (KIND_RANK[right.kind] ?? 9)
152
+ if (kind !== 0) return kind
153
+ return String(left.title).localeCompare(String(right.title))
154
+ })
155
+
156
+ const countBySeverity = (severity) => attention.filter((item) => item.severity === severity).length
157
+ const summary = {
158
+ entries: plugins.length,
159
+ active: plugins.filter((entry) => entry.phase === 'active').length,
160
+ pending: plugins.filter((entry) => entry.phase === 'pending').length,
161
+ failed: plugins.filter((entry) => entry.phase === 'failed').length,
162
+ disabled: plugins.filter((entry) => entry.enabled !== true).length,
163
+ conditional,
164
+ missingServices,
165
+ overridden,
166
+ modeOnly: plugins.filter((entry) => entry.modeOnly === true).length,
167
+ unattributedTools: unattributedTools.length,
168
+ unattributedSections: unattributedSections.length,
169
+ totalTools: attributedTools.length,
170
+ totalSections: promptSections.length + promptContexts.length,
171
+ attention: attention.length,
172
+ critical: countBySeverity('critical'),
173
+ warning: countBySeverity('warning'),
174
+ info: countBySeverity('info'),
175
+ }
176
+
177
+ return { summary, attention: attention.slice(0, MAX_ATTENTION) }
178
+ }