dsh-plugin-slim 0.0.0-stage → 0.1.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.
package/lib/host.js ADDED
@@ -0,0 +1,846 @@
1
+ /**
2
+ * Host adapter: the defensive, read-only seam between 轻装 (Plugin Slim) and the
3
+ * DeepSeek Harness services.
4
+ *
5
+ * No service here is mandatory. Every capability probe tries the host contract,
6
+ * and a missing service, a missing method or a throwing call degrades to an
7
+ * empty value plus one warning; nothing in this module throws into the plugin
8
+ * load or a route handler (handoff spec §2.2: DSH 0.1.5+ / 0.2.x / 0.3.x wide
9
+ * compatibility).
10
+ *
11
+ * Cross-version degradation chains implemented here:
12
+ * - patch path: options.patchPath -> profileContext.patchPath ->
13
+ * profileDir/cordis.patch.yml -> dshHome/cordis.patch.yml;
14
+ * - plugin entries: loader.entries() -> pluginInventory.list() -> static read of
15
+ * the profile package.json and profile cordis.patch.yml;
16
+ * - tool rows: tools.view(undefined).visible (Map / Array / plain object);
17
+ * - usage events: sessionQuery.listSessions() + readSession() -> tool/call
18
+ * events, otherwise null (the usage summary then honestly reports unknown).
19
+ *
20
+ * @module dsh-plugin-slim/host
21
+ */
22
+ import { readFile } from 'node:fs/promises'
23
+ import { homedir } from 'node:os'
24
+ import { join, resolve } from 'node:path'
25
+ import { parseDocument } from 'yaml'
26
+ import { packageSegments } from './attribution.js'
27
+
28
+ const PATCH_FILENAME = 'cordis.patch.yml'
29
+ const DATA_DIR_NAME = 'plugin-slim'
30
+
31
+ /** Usage scan bounds: a wide report, not an unbounded record read. */
32
+ const MAX_SESSIONS = 100
33
+ const MAX_EVENTS_PER_SESSION = 20000
34
+ const MAX_TOTAL_EVENTS = 100000
35
+
36
+ /** Rolling usage window; must match lib/usage.js DEFAULT_WINDOW_DAYS. */
37
+ const SESSION_WINDOW_DAYS = 30
38
+ const MS_PER_DAY = 24 * 60 * 60 * 1000
39
+
40
+ /** Extra safety margin before a session is treated as "clearly outside" the window. */
41
+ const SESSION_SKIP_GRACE_MS = MS_PER_DAY
42
+
43
+ /** Warning bounds: one adapter instance never accumulates without limit. */
44
+ const MAX_WARNINGS = 20
45
+ const MAX_WARNING_CHARS = 500
46
+
47
+ /** Preferred Chinese locale files; they override the English package description. */
48
+ const LOCALE_ZH_FILES = Object.freeze(['zh.json', 'zh-CN.json', 'zh-Hans.json'])
49
+ const LOCALIZED_KEY_ORDER = Object.freeze(['zh', 'zh-CN', 'zh-Hans', 'en'])
50
+
51
+ /** Core entry ids that must never be slept (handoff spec §2.4 + 4.1.3). */
52
+ const PROTECTED_ENTRY_IDS = new Set([
53
+ // Panel / UI core bundles.
54
+ 'ui-chat',
55
+ 'ui-settings',
56
+ 'ui-layout',
57
+ 'ui-sidebar',
58
+ 'ui-theme',
59
+ 'ui',
60
+ 'ui-main',
61
+ 'ui-shell',
62
+ // Agent / permission / settings core.
63
+ 'agent-default-model',
64
+ 'agent-preset-registry',
65
+ 'agent',
66
+ 'agent-loop',
67
+ 'permission',
68
+ 'plugin-manager',
69
+ 'settings',
70
+ 'config',
71
+ // Host infrastructure rows (real DSH loader ids included).
72
+ 'web-server',
73
+ 'webserver',
74
+ 'api-server',
75
+ 'host',
76
+ 'core',
77
+ 'loader',
78
+ 'dsh-loader',
79
+ 'hmr',
80
+ 'dsh-hmr',
81
+ 'client',
82
+ 'client-hmr',
83
+ 'timer',
84
+ 'system-prompt',
85
+ 'session',
86
+ 'session-query',
87
+ 'tools',
88
+ 'tool-registry',
89
+ 'daemon',
90
+ 'telemetry',
91
+ 'updater',
92
+ // 轻装 itself.
93
+ 'plugin-slim',
94
+ 'dsh-plugin-slim',
95
+ ])
96
+
97
+ /** Package names that are loader/boot infrastructure rather than plugins. */
98
+ const PROTECTED_PACKAGE_NAMES = new Set(['cordis', 'dsh', 'dsh-hmr', 'dsh-loader', '@deepseek-ai/dsh'])
99
+ const PROTECTED_PACKAGE_PREFIX = '@deepseek-ai/'
100
+
101
+ /** A concrete dependency version; ranges are not versions. */
102
+ const CONCRETE_VERSION = new RegExp('^[0-9]+[.][0-9]+[.][0-9]+(?:[-+][0-9A-Za-z.-]+)?$')
103
+
104
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
105
+ function isRecord(value) {
106
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
107
+ }
108
+
109
+ /** @param {unknown} value @returns {string} trimmed string or '' */
110
+ function textOf(value) {
111
+ return typeof value === 'string' ? value.trim() : ''
112
+ }
113
+
114
+ /** @param {unknown} value @returns {string | undefined} */
115
+ function optionalText(value) {
116
+ const text = textOf(value)
117
+ return text === '' ? undefined : text
118
+ }
119
+
120
+ /** Describe an unknown error without a stack. @param {unknown} error */
121
+ export function describeError(error) {
122
+ if (error instanceof Error && error.message !== '') return error.message
123
+ const text = String(error)
124
+ return text === '' ? 'unknown error' : text
125
+ }
126
+
127
+ /**
128
+ * Read one optional host service without ever throwing. Property access on an
129
+ * un-injected cordis service throws, so use ctx.get and try both the
130
+ * non-strict and the strict form (mirrors the installed plugins).
131
+ * @param {*} ctx @param {string} name
132
+ * @returns {unknown}
133
+ */
134
+ export function tryGet(ctx, name) {
135
+ if (!ctx || typeof ctx.get !== 'function') return undefined
136
+ try {
137
+ const viaNonStrict = ctx.get(name, false)
138
+ if (viaNonStrict !== undefined) return viaNonStrict
139
+ } catch {
140
+ // Fall through to the strict form.
141
+ }
142
+ try {
143
+ return ctx.get(name)
144
+ } catch {
145
+ return undefined
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Resolve the harness home directory: explicit override -> $DSH_HOME ->
151
+ * ~/.dsh (documented default).
152
+ * @param {{ home?: string, env?: Record<string, string | undefined> }} [options]
153
+ * @returns {string}
154
+ */
155
+ export function resolveDshHome(options = {}) {
156
+ const settings = isRecord(options) ? options : {}
157
+ if (typeof settings.home === 'string' && settings.home.trim() !== '') return settings.home
158
+ const env = settings.env ?? process.env
159
+ if (typeof env?.DSH_HOME === 'string' && env.DSH_HOME.trim() !== '') return env.DSH_HOME
160
+ return join(homedir(), '.dsh')
161
+ }
162
+
163
+ /** Read --profile <name> (or --profile=<name>) from a CLI argv. @param {unknown} argv */
164
+ function detectProfileName(argv) {
165
+ const args = Array.isArray(argv) ? argv.map((value) => String(value)) : []
166
+ for (let index = 0; index < args.length; index += 1) {
167
+ const arg = args[index]
168
+ if (arg === '--profile') {
169
+ const next = args[index + 1]
170
+ if (next !== undefined && next !== '' && !next.startsWith('-')) return next
171
+ }
172
+ if (arg.startsWith('--profile=')) {
173
+ const value = arg.slice('--profile='.length)
174
+ if (value !== '') return value
175
+ }
176
+ }
177
+ return ''
178
+ }
179
+
180
+ /**
181
+ * Resolve the profile directory in use. profileContext is authoritative when
182
+ * present; the explicit override and env/argv fallbacks keep the adapter
183
+ * testable off a live host. '' means not resolvable.
184
+ * @param {*} ctx
185
+ * @param {{ profilePath?: string, profileName?: string, env?: Record<string, string | undefined>, argv?: string[], home?: string }} [options]
186
+ * @returns {string}
187
+ */
188
+ export function resolveProfilePath(ctx, options = {}) {
189
+ const settings = isRecord(options) ? options : {}
190
+ if (typeof settings.profilePath === 'string' && settings.profilePath !== '') return settings.profilePath
191
+ const profileContext = tryGet(ctx, 'profileContext')
192
+ if (isRecord(profileContext) && textOf(profileContext.dir) !== '') return profileContext.dir
193
+ const env = settings.env ?? process.env
194
+ let name = textOf(settings.profileName)
195
+ if (name === '') name = textOf(env?.DSH_PROFILE)
196
+ if (name === '') name = detectProfileName(settings.argv ?? process.argv)
197
+ if (name === '') return ''
198
+ return join(resolveDshHome(settings), 'profiles', name)
199
+ }
200
+
201
+ /**
202
+ * Resolve the write target patch file, DSH 0.1.x global layer and 0.2.x+ profile
203
+ * layer included: options.patchPath -> profileContext.patchPath ->
204
+ * profileDir/cordis.patch.yml -> dshHome/cordis.patch.yml.
205
+ * @param {*} ctx
206
+ * @param {{ patchPath?: string, profilePath?: string, home?: string, env?: Record<string, string | undefined>, argv?: string[] }} [options]
207
+ * @returns {string}
208
+ */
209
+ export function resolvePatchPath(ctx, options = {}) {
210
+ const settings = isRecord(options) ? options : {}
211
+ if (typeof settings.patchPath === 'string' && settings.patchPath !== '') return resolve(settings.patchPath)
212
+ const profileContext = tryGet(ctx, 'profileContext')
213
+ if (isRecord(profileContext) && textOf(profileContext.patchPath) !== '') return resolve(profileContext.patchPath)
214
+ const profileDir = resolveProfilePath(ctx, settings)
215
+ if (profileDir !== '') return join(profileDir, PATCH_FILENAME)
216
+ return join(resolveDshHome(settings), PATCH_FILENAME)
217
+ }
218
+
219
+ /**
220
+ * Resolve the plugin data root: dshHomePath('plugin-slim') ->
221
+ * profileContext.home/plugin-slim -> $DSH_HOME/plugin-slim -> ~/.dsh/plugin-slim.
222
+ * @param {*} ctx
223
+ * @param {{ home?: string, env?: Record<string, string | undefined> }} [options]
224
+ * @returns {string}
225
+ */
226
+ export function resolveDataRoot(ctx, options = {}) {
227
+ const settings = isRecord(options) ? options : {}
228
+ const homePath = tryGet(ctx, 'dshHomePath')
229
+ if (typeof homePath === 'function') {
230
+ try {
231
+ const value = homePath(DATA_DIR_NAME)
232
+ if (typeof value === 'string' && value.trim() !== '') return value
233
+ } catch {
234
+ // A throwing host helper degrades to the next source.
235
+ }
236
+ }
237
+ const profileContext = tryGet(ctx, 'profileContext')
238
+ if (isRecord(profileContext) && textOf(profileContext.home) !== '') {
239
+ return join(profileContext.home, DATA_DIR_NAME)
240
+ }
241
+ return join(resolveDshHome(settings), DATA_DIR_NAME)
242
+ }
243
+
244
+ /**
245
+ * Why an entry must not be toggled, or null when it is manageable. Locked
246
+ * families: 轻装 itself, @deepseek-ai/* official core components, cordis /
247
+ * dsh-hmr / dsh-loader infrastructure, the core entry ids, and any row whose
248
+ * disabled value is a !!js expression rather than a boolean.
249
+ * @param {unknown} entry
250
+ * @returns {string | null}
251
+ */
252
+ export function protectReasonFor(entry) {
253
+ if (!isRecord(entry)) return null
254
+ const entryId = textOf(entry.entryId) || textOf(entry.id)
255
+ const name = textOf(entry.name).toLowerCase()
256
+ if (entry.expressionManaged === true) return '该插件行由 !!js 表达式控制,禁止改写'
257
+ // 轻装自身 must be reported as such: check it before the generic core list,
258
+ // which also contains plugin-slim.
259
+ if (name === 'dsh-plugin-slim' || name === 'plugin-slim' || entryId === 'plugin-slim' || entryId === 'dsh-plugin-slim') {
260
+ return '轻装自身,禁止休眠'
261
+ }
262
+ if (entry.unresolvedName === true) return '无法确认所属包的宿主基础行,禁止休眠'
263
+ if (entryId !== '' && PROTECTED_ENTRY_IDS.has(entryId)) return '宿主核心组件,休眠会导致 DSH 功能缺失'
264
+ if (name !== '' && PROTECTED_ENTRY_IDS.has(name)) return '宿主核心组件,休眠会导致 DSH 功能缺失'
265
+ if (name.startsWith(PROTECTED_PACKAGE_PREFIX)) return 'DSH 官方核心组件,禁止休眠'
266
+ if (PROTECTED_PACKAGE_NAMES.has(name)) return 'DSH 加载器/热重载基础设施,禁止休眠'
267
+ return null
268
+ }
269
+
270
+ /**
271
+ * Whether an entry must be locked against sleeping. Accepts either an entry row
272
+ * or a bare package name / entry id string.
273
+ * @param {unknown} entry
274
+ * @returns {boolean}
275
+ */
276
+ export function isProtectedEntry(entry) {
277
+ if (typeof entry === 'string') return protectReasonFor({ name: entry, entryId: entry }) !== null
278
+ return protectReasonFor(entry) !== null
279
+ }
280
+
281
+ /** Resolve a plain string or localized { zh, en } object to a trimmed string. */
282
+ function resolveLocalizedString(value) {
283
+ if (typeof value === 'string') {
284
+ const trimmed = value.trim()
285
+ return trimmed === '' ? undefined : trimmed
286
+ }
287
+ if (!isRecord(value)) return undefined
288
+ const keys = [
289
+ ...LOCALIZED_KEY_ORDER.filter((key) => Object.hasOwn(value, key)),
290
+ ...Object.keys(value).filter((key) => !LOCALIZED_KEY_ORDER.includes(key)),
291
+ ]
292
+ for (const key of keys) {
293
+ const candidate = value[key]
294
+ if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim()
295
+ }
296
+ return undefined
297
+ }
298
+
299
+ /** Read a package's Chinese locale description (locale/zh*.json), if any. */
300
+ async function readLocalizedDescription(packageDir) {
301
+ for (const fileName of LOCALE_ZH_FILES) {
302
+ try {
303
+ const parsed = JSON.parse(await readFile(join(packageDir, 'locale', fileName), 'utf8'))
304
+ const fromMeta = isRecord(parsed) && isRecord(parsed.meta) ? resolveLocalizedString(parsed.meta.description) : undefined
305
+ if (fromMeta !== undefined) return fromMeta
306
+ const direct = isRecord(parsed) ? resolveLocalizedString(parsed.description) : undefined
307
+ if (direct !== undefined) return direct
308
+ } catch {
309
+ // Missing/malformed locale file degrades to package.json description.
310
+ }
311
+ }
312
+ return undefined
313
+ }
314
+
315
+ /** Parse one timestamp-ish value to epoch milliseconds, or null. */
316
+ function timestampOfValue(value) {
317
+ if (typeof value === 'number' && Number.isFinite(value)) return value
318
+ if (typeof value === 'string' && value !== '') {
319
+ const time = Date.parse(value)
320
+ return Number.isNaN(time) ? null : time
321
+ }
322
+ return null
323
+ }
324
+
325
+ /** Header of one listSessions record. */
326
+ function sessionHeaderOf(session) {
327
+ return isRecord(session) && isRecord(session.header) ? session.header : {}
328
+ }
329
+
330
+ /** Latest known activity time of one session (updatedAt/lastEventAt). */
331
+ function sessionActivityTime(session) {
332
+ const header = sessionHeaderOf(session)
333
+ const row = isRecord(session) ? session : {}
334
+ return (
335
+ timestampOfValue(header.updatedAt) ??
336
+ timestampOfValue(header.lastEventAt) ??
337
+ timestampOfValue(row.updatedAt) ??
338
+ timestampOfValue(row.lastEventAt)
339
+ )
340
+ }
341
+
342
+ /** Creation time of one session (used for ordering when no activity time exists). */
343
+ function sessionCreatedTime(session) {
344
+ const header = sessionHeaderOf(session)
345
+ const row = isRecord(session) ? session : {}
346
+ return timestampOfValue(header.createdAt) ?? timestampOfValue(row.createdAt)
347
+ }
348
+
349
+ /** Ordering key: newest activity first, then creation time. */
350
+ function sessionSortTime(session) {
351
+ return sessionActivityTime(session) ?? sessionCreatedTime(session)
352
+ }
353
+
354
+ /** Session id of one listSessions record (real shape: { header: { id } }). */
355
+ function sessionIdOf(session) {
356
+ if (typeof session === 'string') return session === '' ? undefined : session
357
+ if (!isRecord(session)) return undefined
358
+ if (isRecord(session.header)) {
359
+ const fromHeader = optionalText(session.header.id)
360
+ if (fromHeader !== undefined) return fromHeader
361
+ }
362
+ return optionalText(session.id) ?? optionalText(session.sessionId)
363
+ }
364
+
365
+ /**
366
+ * Extract { tool, at } rows from one session event log.
367
+ * Real persisted tool/call events carry the tool name in event.data.name and
368
+ * the timestamp in event.time (ms epoch); older/derived shapes are tolerated.
369
+ * @param {unknown} log
370
+ */
371
+ function extractToolCallEvents(log) {
372
+ const rows = Array.isArray(log) ? log : isRecord(log) && Array.isArray(log.events) ? log.events : []
373
+ const events = []
374
+ for (const row of rows) {
375
+ if (!isRecord(row)) continue
376
+ const type = textOf(row.type) || textOf(row.kind)
377
+ const typeIndicatesToolCall = type === 'tool/call' || type === 'tool_call' || type === 'toolCall'
378
+ const data = isRecord(row.data) ? row.data : isRecord(row.payload) ? row.payload : {}
379
+ const explicitTool = optionalText(row.tool) ?? optionalText(data.tool)
380
+ if (!typeIndicatesToolCall && explicitTool === undefined) continue
381
+ const tool = explicitTool ?? optionalText(data.name)
382
+ if (tool === undefined) continue
383
+ const rawTime = row.time ?? row.at ?? row.timestamp ?? row.createdAt
384
+ let at = rawTime
385
+ if (typeof rawTime === 'number' && Number.isFinite(rawTime)) at = new Date(rawTime).toISOString()
386
+ events.push({ tool, at })
387
+ if (events.length >= MAX_EVENTS_PER_SESSION) break
388
+ }
389
+ return events
390
+ }
391
+
392
+ /**
393
+ * Build the host adapter for one plugin load.
394
+ *
395
+ * Returned adapter (all methods defensive, none throwing):
396
+ * - profilePath(), patchPath(), dataRoot()
397
+ * - listEntries() -> { entries, warnings } with protected/protectReason/canToggle
398
+ * computed locally;
399
+ * - listTools() -> { tools, warnings } rows keeping name/description/parameters/
400
+ * deferLoading/owner;
401
+ * - sessionEvents() -> AsyncIterable | null (null means usage unknown);
402
+ * - warnings getter / takeWarnings().
403
+ *
404
+ * @param {*} ctx
405
+ * @param {{ profilePath?: string, patchPath?: string, home?: string, env?: Record<string, string | undefined>, argv?: string[] }} [options]
406
+ * @returns {object}
407
+ */
408
+ export function createHostAdapter(ctx, options = {}) {
409
+ const settings = isRecord(options) ? options : {}
410
+ /** @type {string[]} */
411
+ const warnings = []
412
+
413
+ const warn = (message) => {
414
+ const text = String(message ?? '')
415
+ const bounded = text.length <= MAX_WARNING_CHARS ? text : text.slice(0, MAX_WARNING_CHARS - 1) + '…'
416
+ if (bounded === '' || warnings.includes(bounded) || warnings.length >= MAX_WARNINGS) return
417
+ warnings.push(bounded)
418
+ }
419
+
420
+ const snapshotWarnings = () => [...warnings]
421
+ const takeWarnings = () => {
422
+ const out = [...warnings]
423
+ warnings.length = 0
424
+ return out
425
+ }
426
+
427
+ const profileDir = () => {
428
+ try {
429
+ return resolveProfilePath(ctx, settings)
430
+ } catch {
431
+ return ''
432
+ }
433
+ }
434
+
435
+ const patchFile = () => {
436
+ try {
437
+ return resolvePatchPath(ctx, settings)
438
+ } catch {
439
+ return ''
440
+ }
441
+ }
442
+
443
+ /** Add protected/protectReason/canToggle to one entry row. */
444
+ const withProtection = (entry) => {
445
+ const protectReason = protectReasonFor(entry)
446
+ return { ...entry, protected: protectReason !== null, protectReason, canToggle: protectReason === null }
447
+ }
448
+
449
+ /** Read installed package metadata (version + Chinese-first description). */
450
+ const readPackageMeta = async (name) => {
451
+ const segments = packageSegments(name)
452
+ const dir = profileDir()
453
+ if (segments === null || dir === '') return undefined
454
+ const packageDir = join(dir, 'node_modules', ...segments)
455
+ let version
456
+ let description
457
+ try {
458
+ const parsed = JSON.parse(await readFile(join(packageDir, 'package.json'), 'utf8'))
459
+ if (isRecord(parsed)) {
460
+ version = optionalText(parsed.version)
461
+ description = resolveLocalizedString(parsed.description)
462
+ }
463
+ } catch {
464
+ // Missing package.json degrades silently; locale/zh*.json may still exist.
465
+ }
466
+ const localized = await readLocalizedDescription(packageDir)
467
+ const finalDescription = localized ?? description
468
+ if (version === undefined && finalDescription === undefined) return undefined
469
+ return { version, description: finalDescription }
470
+ }
471
+
472
+ const enrich = async (entries) => {
473
+ for (const entry of entries) {
474
+ if (entry.version !== undefined && entry.description !== undefined) continue
475
+ const meta = await readPackageMeta(entry.name)
476
+ if (meta === undefined) continue
477
+ if (entry.version === undefined && meta.version !== undefined) entry.version = meta.version
478
+ if (entry.description === undefined && meta.description !== undefined) entry.description = meta.description
479
+ }
480
+ return entries
481
+ }
482
+
483
+ /** Insert one entry, keeping the highest-priority source for a duplicate id. */
484
+ const pushEntry = (entries, entry) => {
485
+ if (!isRecord(entry) || entry.entryId === '') return
486
+ const index = entries.findIndex((existing) => existing.entryId === entry.entryId)
487
+ if (index < 0) {
488
+ entries.push(entry)
489
+ return
490
+ }
491
+ if (entries[index].source !== 'loader' && entry.source === 'loader') entries[index] = entry
492
+ }
493
+
494
+ /**
495
+ * Tier 1 row: loader.entries() item. A cordis loader Entry keeps the patch row
496
+ * in entry.options: the module specifier is entry.options.name, the entry id
497
+ * is entry.id. Groups are skipped. When no module specifier can be resolved
498
+ * the row is flagged unresolvedName so protectReasonFor() locks it as a host
499
+ * base row instead of exposing it as a toggleable plugin.
500
+ */
501
+ const normalizeLoaderEntry = (row) => {
502
+ if (!isRecord(row)) return null
503
+ const rowOptions = isRecord(row.options) ? row.options : {}
504
+ const group = rowOptions.group ?? row.group
505
+ if (group !== undefined && group !== null && group !== false && group !== '' && group !== 0) return null
506
+ const entryId =
507
+ optionalText(row.id) ?? optionalText(row.entryId) ?? optionalText(rowOptions.id) ?? optionalText(row.name) ?? ''
508
+ if (entryId === '') return null
509
+ const packageName =
510
+ optionalText(row.name) ??
511
+ optionalText(rowOptions.name) ??
512
+ optionalText(rowOptions.moduleName) ??
513
+ optionalText(rowOptions.package)
514
+ // The runtime Entry keeps the live switch in entry.disabled; options.disabled
515
+ // is only the patch-row config and can be undefined while the entry is slept.
516
+ const runtimeDisabled = row.disabled
517
+ const optionDisabled = rowOptions.disabled
518
+ const enabled = typeof runtimeDisabled === 'boolean' ? !runtimeDisabled : optionDisabled !== true
519
+ const expressionManaged = optionDisabled !== undefined && optionDisabled !== null && typeof optionDisabled !== 'boolean'
520
+ const meta = isRecord(row.meta) ? row.meta : {}
521
+ return {
522
+ entryId,
523
+ name: packageName ?? entryId,
524
+ version: optionalText(row.version) ?? optionalText(meta.version),
525
+ description: optionalText(row.description) ?? resolveLocalizedString(meta.description),
526
+ enabled,
527
+ expressionManaged,
528
+ source: 'loader',
529
+ unresolvedName: packageName === undefined,
530
+ }
531
+ }
532
+
533
+ /** Read plugin rows declared by a parsed patch document (insert rows included). */
534
+ const patchEntries = (document) => {
535
+ const rows = Array.isArray(document) ? document : isRecord(document) ? [document] : []
536
+ const out = []
537
+ const collect = (item) => {
538
+ if (!isRecord(item)) return
539
+ const packageName = optionalText(item.name)
540
+ const entryId = optionalText(item.id) ?? packageName
541
+ if (entryId === undefined) return
542
+ const disabled = item.disabled
543
+ out.push({
544
+ entryId,
545
+ name: packageName ?? entryId,
546
+ enabled: disabled !== true,
547
+ expressionManaged: disabled !== undefined && disabled !== null && typeof disabled !== 'boolean',
548
+ source: 'patch',
549
+ unresolvedName: packageName === undefined,
550
+ })
551
+ }
552
+ for (const row of rows) {
553
+ if (!isRecord(row)) continue
554
+ if (optionalText(row.name) !== undefined) collect(row)
555
+ if (Array.isArray(row.insert)) for (const inserted of row.insert) collect(inserted)
556
+ }
557
+ return out
558
+ }
559
+
560
+ /**
561
+ * List plugin entries through the cross-version chain:
562
+ * loader.entries() -> pluginInventory.list() -> static profile read.
563
+ * @returns {Promise<{ entries: object[], warnings: string[] }>}
564
+ */
565
+ const listEntries = async () => {
566
+ /** @type {object[]} */
567
+ const entries = []
568
+
569
+ const loader = tryGet(ctx, 'loader')
570
+ if (isRecord(loader)) {
571
+ const read = typeof loader.entries === 'function' ? loader.entries : typeof loader.list === 'function' ? loader.list : null
572
+ if (read !== null) {
573
+ try {
574
+ const rows = await read.call(loader)
575
+ if (Array.isArray(rows)) {
576
+ for (const row of rows) {
577
+ const entry = normalizeLoaderEntry(row)
578
+ if (entry !== null) pushEntry(entries, entry)
579
+ }
580
+ if (entries.length > 0) {
581
+ await enrich(entries)
582
+ return { entries: entries.map(withProtection), warnings: snapshotWarnings() }
583
+ }
584
+ }
585
+ } catch (error) {
586
+ warn('读取 loader 插件表失败:' + describeError(error))
587
+ }
588
+ }
589
+ }
590
+
591
+ const inventory = tryGet(ctx, 'pluginInventory')
592
+ if (isRecord(inventory) && typeof inventory.list === 'function') {
593
+ try {
594
+ const snapshot = await inventory.list()
595
+ // Real shape: { entries: [{ entryId, moduleName, enabled, fiberPhase, meta }] }.
596
+ const rows = Array.isArray(snapshot)
597
+ ? snapshot
598
+ : isRecord(snapshot) && Array.isArray(snapshot.entries)
599
+ ? snapshot.entries
600
+ : null
601
+ if (rows === null) warn('pluginInventory.list() 返回结构无法识别:插件清单按空处理')
602
+ for (const row of rows ?? []) {
603
+ if (!isRecord(row)) continue
604
+ const meta = isRecord(row.meta) ? row.meta : {}
605
+ const packageName = optionalText(row.moduleName) ?? optionalText(row.name)
606
+ const entryId = optionalText(row.entryId) ?? optionalText(row.id) ?? packageName
607
+ if (entryId === undefined) continue
608
+ const disabled = row.disabled
609
+ pushEntry(entries, {
610
+ entryId,
611
+ name: packageName ?? entryId,
612
+ version: optionalText(row.version) ?? optionalText(meta.version),
613
+ description: optionalText(row.description) ?? resolveLocalizedString(meta.description),
614
+ enabled: row.enabled !== false && disabled !== true,
615
+ expressionManaged: disabled !== undefined && disabled !== null && typeof disabled !== 'boolean',
616
+ source: 'inventory',
617
+ unresolvedName: packageName === undefined,
618
+ })
619
+ }
620
+ } catch (error) {
621
+ warn('读取 pluginInventory 插件表失败:' + describeError(error))
622
+ }
623
+ }
624
+
625
+ const dir = profileDir()
626
+ if (dir !== '') {
627
+ /** Installed-package rows by package name, for the patch-row merge. */
628
+ const npmByName = new Map()
629
+ try {
630
+ const parsed = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'))
631
+ const dependencies = isRecord(parsed) && isRecord(parsed.dependencies) ? parsed.dependencies : {}
632
+ const devDependencies = isRecord(parsed) && isRecord(parsed.devDependencies) ? parsed.devDependencies : {}
633
+ for (const [name, spec] of Object.entries({ ...dependencies, ...devDependencies })) {
634
+ if (name === '') continue
635
+ const version = typeof spec === 'string' && CONCRETE_VERSION.test(spec) ? spec : undefined
636
+ const row = { entryId: name, name, version, enabled: true, expressionManaged: false, source: 'npm', unresolvedName: false }
637
+ pushEntry(entries, row)
638
+ npmByName.set(name, row)
639
+ }
640
+ } catch (error) {
641
+ warn('读取 profile package.json 失败:' + describeError(error))
642
+ }
643
+ const file = patchFile()
644
+ if (file !== '') {
645
+ try {
646
+ const content = await readFile(file, 'utf8')
647
+ // parseDocument tolerates unrelated !!js/* tags on other rows exactly
648
+ // like the patch writer does (TAG_RESOLVE_FAILED warnings only, never
649
+ // an error); a real YAML defect skips the patch rows with a warning.
650
+ const parsedDocument = content.trim() === '' ? null : parseDocument(content)
651
+ if (parsedDocument !== null && parsedDocument.errors.length > 0) {
652
+ warn('补丁文件 YAML 无法解析,已跳过补丁行:' + String(parsedDocument.errors[0]?.message ?? '').split('\n')[0])
653
+ } else {
654
+ const document = parsedDocument === null ? [] : parsedDocument.toJSON()
655
+ for (const entry of patchEntries(document)) {
656
+ const installed = npmByName.get(entry.name)
657
+ if (installed !== undefined) {
658
+ // The patch row carries the authoritative runtime state (and its
659
+ // id is the toggle target). Replace the installed-package
660
+ // placeholder, keeping the patch row's enabled/disabled state
661
+ // even when the ids are equal.
662
+ const index = entries.indexOf(installed)
663
+ if (index >= 0) {
664
+ entries[index] =
665
+ installed.entryId === entry.entryId ? { ...installed, ...entry, source: 'patch' } : entry
666
+ }
667
+ npmByName.delete(entry.name)
668
+ continue
669
+ }
670
+ pushEntry(entries, entry)
671
+ }
672
+ }
673
+ } catch (error) {
674
+ warn('读取补丁文件插件行失败:' + describeError(error))
675
+ }
676
+ }
677
+ }
678
+
679
+ await enrich(entries)
680
+ return { entries: entries.map(withProtection), warnings: snapshotWarnings() }
681
+ }
682
+
683
+ /** Normalize one tools.view() row. */
684
+ const normalizeToolRow = (row) => {
685
+ if (!isRecord(row)) return null
686
+ const name = optionalText(row.name)
687
+ if (name === undefined) return null
688
+ const normalized = { name, description: typeof row.description === 'string' ? row.description : '' }
689
+ if (row.parameters !== undefined && row.parameters !== null) normalized.parameters = row.parameters
690
+ if (row.deferLoading === true) normalized.deferLoading = true
691
+ const owner = optionalText(row.owner)
692
+ if (owner !== undefined) normalized.owner = owner
693
+ return normalized
694
+ }
695
+
696
+ /** Flatten a Map / Array / plain object tool collection into rows. */
697
+ const iterateToolRows = (visible) => {
698
+ const out = []
699
+ if (visible === undefined || visible === null) return out
700
+ if (visible instanceof Map) {
701
+ for (const value of visible.values()) out.push(value)
702
+ return out
703
+ }
704
+ if (Array.isArray(visible)) {
705
+ for (const value of visible) out.push(value)
706
+ return out
707
+ }
708
+ if (isRecord(visible)) {
709
+ if (typeof visible.name === 'string') {
710
+ out.push(visible)
711
+ return out
712
+ }
713
+ for (const value of Object.values(visible)) out.push(value)
714
+ }
715
+ return out
716
+ }
717
+
718
+ /**
719
+ * List visible tool rows (name/description/parameters/deferLoading/owner).
720
+ * @returns {Promise<{ tools: object[], warnings: string[] }>}
721
+ */
722
+ const listTools = async () => {
723
+ /** @type {object[]} */
724
+ const tools = []
725
+ const service = tryGet(ctx, 'tools')
726
+ if (!isRecord(service) || typeof service.view !== 'function') {
727
+ warn('tools 服务不可用:工具清单按空处理')
728
+ return { tools, warnings: snapshotWarnings() }
729
+ }
730
+ let result
731
+ try {
732
+ result = await service.view(undefined)
733
+ } catch (error) {
734
+ warn('读取工具清单失败:' + describeError(error))
735
+ return { tools, warnings: snapshotWarnings() }
736
+ }
737
+ const visible = isRecord(result) && result.visible !== undefined ? result.visible : result
738
+ for (const row of iterateToolRows(visible)) {
739
+ const tool = normalizeToolRow(row)
740
+ if (tool !== null) tools.push(tool)
741
+ }
742
+ return { tools, warnings: snapshotWarnings() }
743
+ }
744
+
745
+ /**
746
+ * Yield { tool, at } usage events read from the session corpus, or null when
747
+ * the service is unavailable (which the usage summary reports as unknown).
748
+ *
749
+ * Real host contract (dsh-session-query): listSessions() records look like
750
+ * { header: { id, createdAt }, live, persisted }; readSession(id) resolves to
751
+ * { events } whose tool/call events carry event.data.name and event.time (ms
752
+ * epoch). A degraded read is thrown out of the generator on purpose so
753
+ * summarizeUsage honestly reports { unknown: true } instead of silently
754
+ * counting 0 calls and mislabelling active plugins as idle.
755
+ * @returns {AsyncIterable<{ tool: string, at: unknown }> | null}
756
+ */
757
+ const sessionEvents = () => {
758
+ const service = tryGet(ctx, 'sessionQuery')
759
+ if (!isRecord(service)) {
760
+ warn('sessionQuery 服务不可用:用量统计降级为未知')
761
+ return null
762
+ }
763
+ const list = typeof service.listSessions === 'function' ? service.listSessions : typeof service.list === 'function' ? service.list : null
764
+ const read = typeof service.readSession === 'function' ? service.readSession : null
765
+ if (list === null || read === null) {
766
+ warn('sessionQuery 缺少 listSessions/readSession:用量统计降级为未知')
767
+ return null
768
+ }
769
+ return (async function* sessionEventStream() {
770
+ let sessions
771
+ try {
772
+ sessions = await list.call(service)
773
+ } catch (error) {
774
+ warn('读取会话列表失败:' + describeError(error))
775
+ throw error
776
+ }
777
+ const rows = Array.isArray(sessions) ? sessions : isRecord(sessions) && Array.isArray(sessions.sessions) ? sessions.sessions : null
778
+ if (rows === null) {
779
+ warn('会话列表结构无法识别:用量统计降级为未知')
780
+ throw new Error('会话列表结构无法识别')
781
+ }
782
+ // Hosts may return sessions in any order (old -> new, alphabetical, ...),
783
+ // so sort by recency before capping: truncating first could drop the
784
+ // newest 30-day sessions and mislabel active plugins as idle. Sessions
785
+ // whose latest known activity is clearly outside the window are skipped.
786
+ const nowMs = Date.now()
787
+ const cutoff = nowMs - SESSION_WINDOW_DAYS * MS_PER_DAY - SESSION_SKIP_GRACE_MS
788
+ const ordered = []
789
+ for (let index = 0; index < rows.length; index += 1) {
790
+ const session = rows[index]
791
+ const activity = sessionActivityTime(session)
792
+ if (activity !== null && activity < cutoff) continue
793
+ ordered.push({ session, index, sortTime: sessionSortTime(session) })
794
+ }
795
+ ordered.sort((left, right) => {
796
+ const leftKey = left.sortTime === null ? Number.NEGATIVE_INFINITY : left.sortTime
797
+ const rightKey = right.sortTime === null ? Number.NEGATIVE_INFINITY : right.sortTime
798
+ if (leftKey !== rightKey) return rightKey - leftKey
799
+ return left.index - right.index
800
+ })
801
+ const limited = ordered.slice(0, MAX_SESSIONS)
802
+ if (ordered.length > MAX_SESSIONS) warn('会话数量超过 ' + MAX_SESSIONS + ' 个,仅统计最近的 ' + MAX_SESSIONS + ' 个')
803
+ let yielded = 0
804
+ for (const item of limited) {
805
+ const session = item.session
806
+ if (yielded >= MAX_TOTAL_EVENTS) return
807
+ const id = sessionIdOf(session)
808
+ if (id === undefined) continue
809
+ let log
810
+ try {
811
+ log = await read.call(service, id)
812
+ } catch (error) {
813
+ warn('读取会话事件失败:' + describeError(error))
814
+ throw error
815
+ }
816
+ for (const event of extractToolCallEvents(log)) {
817
+ if (yielded >= MAX_TOTAL_EVENTS) return
818
+ yielded += 1
819
+ yield event
820
+ }
821
+ }
822
+ })()
823
+ }
824
+
825
+ return {
826
+ profilePath: () => profileDir(),
827
+ patchPath: () => patchFile(),
828
+ dataRoot: () => {
829
+ try {
830
+ return resolveDataRoot(ctx, settings)
831
+ } catch {
832
+ return ''
833
+ }
834
+ },
835
+ listEntries,
836
+ listTools,
837
+ sessionEvents,
838
+ get warnings() {
839
+ return snapshotWarnings()
840
+ },
841
+ takeWarnings,
842
+ }
843
+ }
844
+
845
+
846
+