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/routes.js ADDED
@@ -0,0 +1,493 @@
1
+ /**
2
+ * The four /api/plugin-slim/* payload handlers (handoff spec §3, the SSOT).
3
+ *
4
+ * Handlers never throw for an expected business failure: they resolve to
5
+ * { status, json } and let lib/http.js serialize. Error codes and statuses are
6
+ * exactly the contract:
7
+ * - 400 INVALID_INPUT / INVALID_SNAPSHOT_ID
8
+ * - 403 PROTECTED_ENTRY
9
+ * - 404 ENTRY_NOT_FOUND / SNAPSHOT_NOT_FOUND
10
+ * - 409 PATCH_BLOCKED
11
+ * - 500 PATCH_WRITE_FAILED / 503 PATCH_UNAVAILABLE
12
+ *
13
+ * Security invariant: toggle and sleep-idle re-read host.listEntries() before
14
+ * writing and validate isProtectedEntry + canToggle against that live state;
15
+ * the browser's view of a plugin is never authoritative. sleep-idle validates
16
+ * every entry before touching the patch file, so one bad id rejects the whole
17
+ * batch without a partial write, and writes one snapshot + one atomic patch
18
+ * update that undo can reverse in a single step.
19
+ *
20
+ * Absolute route paths are mounted on the host origin; the browser half calls
21
+ * them document-relative (api/plugin-slim/...) so a sub-path deployment works.
22
+ *
23
+ * @module dsh-plugin-slim/routes
24
+ */
25
+ import { buildCheckupReport } from './checkup.js'
26
+ import { describeError, isProtectedEntry, protectReasonFor } from './host.js'
27
+ import { editPatchContent, validatePatchYaml } from './patch.js'
28
+ import { summarizeUsage } from './usage.js'
29
+
30
+ /** Route paths shared by the mount code, the tests and the client contract. */
31
+ export const ROUTE_PATHS = Object.freeze({
32
+ report: '/api/plugin-slim/report',
33
+ toggle: '/api/plugin-slim/toggle',
34
+ sleepIdle: '/api/plugin-slim/sleep-idle',
35
+ undo: '/api/plugin-slim/undo',
36
+ })
37
+
38
+ /** Rolling usage window; must match lib/usage.js DEFAULT_WINDOW_DAYS. */
39
+ const USAGE_WINDOW_DAYS = 30
40
+
41
+ /** Snapshot ids double as file names: reject traversal before any read. */
42
+ const SNAPSHOT_ID_PATTERN = new RegExp('^[A-Za-z0-9_-]+$')
43
+
44
+ const HOT_RELOAD_HINT_SINGLE = '已写入补丁配置;若宿主启用了热重载(HMR)将自动生效,否则重启 DSH 后生效。'
45
+ const HOT_RELOAD_HINT_BATCH = '已批量写入补丁并自动备份;若宿主启用了热重载将自动生效,否则重启 DSH 后生效。'
46
+ const HOT_RELOAD_HINT_UNDO = '已恢复修改前的配置;若未自动热生效,重启 DSH 即可。'
47
+
48
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
49
+ function isRecord(value) {
50
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
51
+ }
52
+
53
+ /** Normalize a clock dependency (Date | number | string | function) to a Date. */
54
+ function resolveNow(value) {
55
+ const candidate = typeof value === 'function' ? value() : value
56
+ if (candidate instanceof Date && Number.isFinite(candidate.getTime())) return candidate
57
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) return new Date(candidate)
58
+ if (typeof candidate === 'string' && candidate !== '') {
59
+ const time = Date.parse(candidate)
60
+ if (!Number.isNaN(time)) return new Date(time)
61
+ }
62
+ return new Date()
63
+ }
64
+
65
+ /** A 200 success envelope. @param {unknown} json */
66
+ function ok(json) {
67
+ return { status: 200, json }
68
+ }
69
+
70
+ /** A contract error envelope. @param {number} status @param {string} code @param {string} message */
71
+ function fail(status, code, message) {
72
+ return { status, json: { ok: false, code, error: message } }
73
+ }
74
+
75
+ /** Stable entry id of one host row ('' when absent). */
76
+ function entryIdOf(entry) {
77
+ if (!isRecord(entry)) return ''
78
+ if (typeof entry.entryId === 'string' && entry.entryId !== '') return entry.entryId
79
+ if (typeof entry.id === 'string' && entry.id !== '') return entry.id
80
+ return ''
81
+ }
82
+
83
+ /** Display name of one host row. */
84
+ function nameOf(entry) {
85
+ if (isRecord(entry) && typeof entry.name === 'string' && entry.name !== '') return entry.name
86
+ return entryIdOf(entry)
87
+ }
88
+
89
+ /**
90
+ * Build the four panel routes.
91
+ *
92
+ * @param {{
93
+ * host?: object,
94
+ * patchStore?: object,
95
+ * now?: Date | number | string | (() => unknown),
96
+ * }} [input]
97
+ * @returns {{ method: 'GET' | 'POST', path: string, handler: (payload?: unknown) => Promise<object> }[]}
98
+ */
99
+ export function createRoutes(input = {}) {
100
+ const options = isRecord(input) ? input : {}
101
+ const host = isRecord(options.host) ? options.host : {}
102
+ const patchStore = isRecord(options.patchStore) ? options.patchStore : null
103
+ const clock = options.now
104
+
105
+ const nowDate = () => resolveNow(clock)
106
+
107
+ /** Read one optional host capability, degrading to an empty value. */
108
+ async function callHost(method, fallback) {
109
+ if (typeof host[method] !== 'function') return fallback
110
+ try {
111
+ return await host[method]()
112
+ } catch (error) {
113
+ return { __error: describeError(error) }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Collect the live facts one report needs. Live means re-read per request:
119
+ * the write handlers must validate against host.listEntries(), never against
120
+ * a value the client sent.
121
+ */
122
+ async function collectState() {
123
+ /** @type {string[]} */
124
+ const warnings = []
125
+
126
+ let entries = []
127
+ const entryResult = await callHost('listEntries', { entries: [], warnings: [] })
128
+ if (isRecord(entryResult) && typeof entryResult.__error === 'string') {
129
+ warnings.push('读取插件列表失败:' + entryResult.__error)
130
+ } else if (isRecord(entryResult)) {
131
+ if (Array.isArray(entryResult.entries)) entries = entryResult.entries
132
+ if (Array.isArray(entryResult.warnings)) warnings.push(...entryResult.warnings)
133
+ }
134
+
135
+ let tools = []
136
+ const toolResult = await callHost('listTools', { tools: [], warnings: [] })
137
+ if (isRecord(toolResult) && typeof toolResult.__error === 'string') {
138
+ warnings.push('读取工具清单失败:' + toolResult.__error)
139
+ } else if (isRecord(toolResult)) {
140
+ if (Array.isArray(toolResult.tools)) tools = toolResult.tools
141
+ if (Array.isArray(toolResult.warnings)) warnings.push(...toolResult.warnings)
142
+ }
143
+
144
+ let usage
145
+ try {
146
+ const events = typeof host.sessionEvents === 'function' ? await host.sessionEvents() : null
147
+ usage = await summarizeUsage({ events, now: nowDate(), windowDays: USAGE_WINDOW_DAYS })
148
+ } catch (error) {
149
+ warnings.push('读取用量失败:' + describeError(error))
150
+ usage = { byTool: new Map(), unknown: true }
151
+ }
152
+
153
+ // Surface adapter degradation warnings (usage read failures included) in the
154
+ // report instead of dropping them silently.
155
+ try {
156
+ if (typeof host.takeWarnings === 'function') {
157
+ const drained = host.takeWarnings()
158
+ if (Array.isArray(drained)) warnings.push(...drained)
159
+ } else if (Array.isArray(host.warnings)) {
160
+ warnings.push(...host.warnings)
161
+ }
162
+ } catch {
163
+ // Warning collection must never fail a report.
164
+ }
165
+
166
+ let patchPath = null
167
+ if (typeof host.patchPath === 'function') {
168
+ try {
169
+ const value = host.patchPath()
170
+ if (typeof value === 'string' && value !== '') patchPath = value
171
+ } catch {
172
+ patchPath = null
173
+ }
174
+ }
175
+
176
+ let patchWritable = false
177
+ if (patchStore !== null && patchPath !== null && typeof patchStore.isWritable === 'function') {
178
+ try {
179
+ patchWritable = (await patchStore.isWritable(patchPath)) === true
180
+ } catch {
181
+ patchWritable = false
182
+ }
183
+ }
184
+
185
+ let latestSnapshot = null
186
+ if (patchStore !== null && typeof patchStore.latestSnapshot === 'function') {
187
+ try {
188
+ latestSnapshot = await patchStore.latestSnapshot()
189
+ } catch {
190
+ latestSnapshot = null
191
+ }
192
+ }
193
+
194
+ let profilePath = ''
195
+ if (typeof host.profilePath === 'function') {
196
+ try {
197
+ const value = host.profilePath()
198
+ if (typeof value === 'string') profilePath = value
199
+ } catch {
200
+ profilePath = ''
201
+ }
202
+ }
203
+
204
+ return { entries, tools, usage, patchPath, patchWritable, latestSnapshot, warnings, profilePath }
205
+ }
206
+
207
+ /** Merge one collected state into the shared Report object. */
208
+ async function buildReport(state) {
209
+ return buildCheckupReport({
210
+ entries: state.entries,
211
+ tools: state.tools,
212
+ usage: state.usage,
213
+ patchPath: state.patchPath,
214
+ patchWritable: state.patchWritable,
215
+ latestSnapshot: state.latestSnapshot,
216
+ warnings: state.warnings,
217
+ now: nowDate(),
218
+ profilePath: state.profilePath,
219
+ })
220
+ }
221
+
222
+ /** Find one live entry by entry id. */
223
+ function findEntry(entries, entryId) {
224
+ for (const entry of Array.isArray(entries) ? entries : []) {
225
+ if (entryIdOf(entry) === entryId) return entry
226
+ }
227
+ return null
228
+ }
229
+
230
+ /**
231
+ * Protection guard against the live host row. Returns a readable reason, or
232
+ * null when the entry may be toggled.
233
+ */
234
+ function guardEntry(entry) {
235
+ const reason = protectReasonFor(entry)
236
+ if (reason !== null) return reason
237
+ if (isProtectedEntry(entry)) return '该插件受保护,禁止休眠或唤醒'
238
+ if (isRecord(entry) && entry.protected === true) return '该插件受保护,禁止休眠或唤醒'
239
+ if (isRecord(entry) && entry.canToggle === false) return '该插件当前不可切换'
240
+ return null
241
+ }
242
+
243
+ /**
244
+ * Resolve the patch write target and current bytes. Returns a contract error
245
+ * response (status/code) when the file cannot be located or written.
246
+ */
247
+ async function prepareWrite(state) {
248
+ const patchPath = typeof state.patchPath === 'string' && state.patchPath !== '' ? state.patchPath : ''
249
+ if (patchPath === '' || patchStore === null) {
250
+ return fail(503, 'PATCH_UNAVAILABLE', '无法定位补丁文件 cordis.patch.yml,已拒绝写入')
251
+ }
252
+ if (state.patchWritable !== true) {
253
+ return fail(503, 'PATCH_UNAVAILABLE', '补丁文件不可写:' + patchPath)
254
+ }
255
+ let read
256
+ try {
257
+ read = await patchStore.readPatch(patchPath)
258
+ } catch (error) {
259
+ return fail(503, 'PATCH_UNAVAILABLE', '读取补丁文件失败:' + describeError(error))
260
+ }
261
+ if (isRecord(read) && read.error) {
262
+ return fail(503, 'PATCH_UNAVAILABLE', '读取补丁文件失败:' + String(read.error))
263
+ }
264
+ return {
265
+ patchPath,
266
+ content: isRecord(read) && typeof read.content === 'string' ? read.content : '',
267
+ existedBefore: isRecord(read) && read.existed === true,
268
+ }
269
+ }
270
+
271
+ /** Map a blocked surgical edit to the 409 contract error. */
272
+ function patchBlocked(edit) {
273
+ const message =
274
+ isRecord(edit) && typeof edit.message === 'string' && edit.message !== '' ? edit.message : '补丁文件存在无法安全识别的行块,已拒绝写入'
275
+ return fail(409, 'PATCH_BLOCKED', message)
276
+ }
277
+
278
+ /** Validate the edited document; undefined when it is writable, else 409. */
279
+ function validateEdit(content) {
280
+ try {
281
+ validatePatchYaml(content)
282
+ return undefined
283
+ } catch (error) {
284
+ return fail(409, 'PATCH_BLOCKED', describeError(error))
285
+ }
286
+ }
287
+
288
+ /** GET /api/plugin-slim/report */
289
+ async function handleReport() {
290
+ const state = await collectState()
291
+ return ok(await buildReport(state))
292
+ }
293
+
294
+ /** POST /api/plugin-slim/toggle */
295
+ async function handleToggle(payload) {
296
+ if (!isRecord(payload)) return fail(400, 'INVALID_INPUT', '请求体必须是 JSON 对象')
297
+ const entryId = typeof payload.entryId === 'string' ? payload.entryId.trim() : ''
298
+ if (entryId === '') return fail(400, 'INVALID_INPUT', '缺少非空字符串 entryId')
299
+ if (typeof payload.disabled !== 'boolean') return fail(400, 'INVALID_INPUT', 'disabled 必须是布尔值')
300
+
301
+ // Live authority: never trust the client's view of a plugin.
302
+ const state = await collectState()
303
+ const entry = findEntry(state.entries, entryId)
304
+ if (entry === null) return fail(404, 'ENTRY_NOT_FOUND', '未找到插件:' + entryId)
305
+ const guard = guardEntry(entry)
306
+ if (guard !== null) return fail(403, 'PROTECTED_ENTRY', guard)
307
+
308
+ const prepared = await prepareWrite(state)
309
+ if (isRecord(prepared) && typeof prepared.status === 'number') return prepared
310
+
311
+ const disabled = payload.disabled
312
+ const edit = editPatchContent(prepared.content, [{ entryId, disabled }])
313
+ if (edit.ok !== true) return patchBlocked(edit)
314
+ const invalid = validateEdit(edit.content)
315
+ if (invalid !== undefined) return invalid
316
+
317
+ let snapshotId = null
318
+ if (edit.changed === true) {
319
+ try {
320
+ snapshotId = await patchStore.writePatch({
321
+ patchPath: prepared.patchPath,
322
+ nextContent: edit.content,
323
+ previousContent: prepared.content,
324
+ existedBefore: prepared.existedBefore,
325
+ changes: [{ entryId, name: nameOf(entry), disabled, changed: true }],
326
+ summary: (disabled ? '休眠 ' : '唤醒 ') + nameOf(entry),
327
+ now: nowDate(),
328
+ })
329
+ } catch (error) {
330
+ return fail(500, 'PATCH_WRITE_FAILED', '写入补丁失败:' + describeError(error))
331
+ }
332
+ }
333
+
334
+ const nextState = await collectState()
335
+ return ok({
336
+ ok: true,
337
+ snapshotId,
338
+ applied: { entryId, name: nameOf(entry), disabled },
339
+ changed: edit.changed === true,
340
+ hotReloadHint: HOT_RELOAD_HINT_SINGLE,
341
+ report: await buildReport(nextState),
342
+ })
343
+ }
344
+
345
+ /** POST /api/plugin-slim/sleep-idle */
346
+ async function handleSleepIdle(payload) {
347
+ if (!isRecord(payload) || !Array.isArray(payload.entryIds) || payload.entryIds.length === 0) {
348
+ return fail(400, 'INVALID_INPUT', 'entryIds 必须是非空字符串数组')
349
+ }
350
+ const entryIds = []
351
+ const seen = new Set()
352
+ for (const value of payload.entryIds) {
353
+ if (typeof value !== 'string' || value.trim() === '') {
354
+ return fail(400, 'INVALID_INPUT', 'entryIds 必须是非空字符串数组')
355
+ }
356
+ const entryId = value.trim()
357
+ if (seen.has(entryId)) continue
358
+ seen.add(entryId)
359
+ entryIds.push(entryId)
360
+ }
361
+
362
+ // Validate every entry against the live host state before any write:
363
+ // one protected/missing entry rejects the whole batch (no partial write).
364
+ const state = await collectState()
365
+ const targets = []
366
+ for (const entryId of entryIds) {
367
+ const entry = findEntry(state.entries, entryId)
368
+ if (entry === null) return fail(404, 'ENTRY_NOT_FOUND', '未找到插件:' + entryId + '(整批未写入)')
369
+ const guard = guardEntry(entry)
370
+ if (guard !== null) return fail(403, 'PROTECTED_ENTRY', guard + '(整批未写入)')
371
+ targets.push(entry)
372
+ }
373
+
374
+ const prepared = await prepareWrite(state)
375
+ if (isRecord(prepared) && typeof prepared.status === 'number') return prepared
376
+
377
+ const changes = targets.map((entry) => ({ entryId: entryIdOf(entry), disabled: true }))
378
+ const edit = editPatchContent(prepared.content, changes)
379
+ if (edit.ok !== true) return patchBlocked(edit)
380
+ const invalid = validateEdit(edit.content)
381
+ if (invalid !== undefined) return invalid
382
+
383
+ const appliedRows = Array.isArray(edit.applied) ? edit.applied : []
384
+ const changedIds = new Set(appliedRows.filter((row) => isRecord(row) && row.changed === true).map((row) => row.entryId))
385
+ const changedTargets = targets.filter((entry) => changedIds.has(entryIdOf(entry)))
386
+
387
+ let snapshotId = null
388
+ if (edit.changed === true) {
389
+ try {
390
+ snapshotId = await patchStore.writePatch({
391
+ patchPath: prepared.patchPath,
392
+ nextContent: edit.content,
393
+ previousContent: prepared.content,
394
+ existedBefore: prepared.existedBefore,
395
+ changes: changedTargets.map((entry) => ({
396
+ entryId: entryIdOf(entry),
397
+ name: nameOf(entry),
398
+ disabled: true,
399
+ changed: true,
400
+ })),
401
+ summary: '批量休眠 ' + changedTargets.length + ' 个插件',
402
+ now: nowDate(),
403
+ })
404
+ } catch (error) {
405
+ return fail(500, 'PATCH_WRITE_FAILED', '写入补丁失败:' + describeError(error))
406
+ }
407
+ }
408
+
409
+ const nextState = await collectState()
410
+ return ok({
411
+ ok: true,
412
+ snapshotId,
413
+ count: changedTargets.length,
414
+ applied: changedTargets.map((entry) => ({ entryId: entryIdOf(entry), name: nameOf(entry), disabled: true })),
415
+ changed: edit.changed === true,
416
+ hotReloadHint: HOT_RELOAD_HINT_BATCH,
417
+ report: await buildReport(nextState),
418
+ })
419
+ }
420
+
421
+ /** POST /api/plugin-slim/undo */
422
+ async function handleUndo(payload) {
423
+ const body = isRecord(payload) ? payload : {}
424
+ let snapshotId
425
+ if (body.snapshotId !== undefined && body.snapshotId !== null) {
426
+ if (typeof body.snapshotId !== 'string' || !SNAPSHOT_ID_PATTERN.test(body.snapshotId)) {
427
+ return fail(400, 'INVALID_SNAPSHOT_ID', '非法的 snapshotId 格式(仅允许 A-Z a-z 0-9 _ -)')
428
+ }
429
+ snapshotId = body.snapshotId
430
+ }
431
+
432
+ if (patchStore === null) {
433
+ const state = await collectState()
434
+ return ok({
435
+ ok: true,
436
+ restored: false,
437
+ alreadyRestored: false,
438
+ snapshotId: null,
439
+ message: '当前没有可撤销的操作快照',
440
+ hotReloadHint: HOT_RELOAD_HINT_UNDO,
441
+ report: await buildReport(state),
442
+ })
443
+ }
444
+
445
+ let result
446
+ try {
447
+ result = await patchStore.restoreSnapshot(snapshotId)
448
+ } catch (error) {
449
+ return fail(500, 'PATCH_WRITE_FAILED', '恢复快照失败:' + describeError(error))
450
+ }
451
+ if (isRecord(result) && result.error === 'invalid-id') {
452
+ return fail(400, 'INVALID_SNAPSHOT_ID', '非法的 snapshotId 格式(仅允许 A-Z a-z 0-9 _ -)')
453
+ }
454
+ if (isRecord(result) && result.error === 'not-found') {
455
+ return fail(404, 'SNAPSHOT_NOT_FOUND', '未找到操作快照:' + String(snapshotId ?? ''))
456
+ }
457
+
458
+ const state = await collectState()
459
+ const report = await buildReport(state)
460
+ if (!isRecord(result) || !isRecord(result.snapshot)) {
461
+ return ok({
462
+ ok: true,
463
+ restored: false,
464
+ alreadyRestored: false,
465
+ snapshotId: null,
466
+ message: '当前没有可撤销的操作快照',
467
+ hotReloadHint: HOT_RELOAD_HINT_UNDO,
468
+ report,
469
+ })
470
+ }
471
+ const snapshot = result.snapshot
472
+ const summary =
473
+ typeof snapshot.summary === 'string' && snapshot.summary !== '' ? snapshot.summary : '上次操作'
474
+ const alreadyRestored = result.alreadyRestored === true
475
+ return ok({
476
+ ok: true,
477
+ restored: true,
478
+ alreadyRestored,
479
+ snapshotId: typeof snapshot.id === 'string' ? snapshot.id : null,
480
+ message: alreadyRestored ? '快照「' + summary + '」此前已恢复,无需重复撤销' : '已撤销「' + summary + '」',
481
+ hotReloadHint: HOT_RELOAD_HINT_UNDO,
482
+ report,
483
+ })
484
+ }
485
+
486
+ return [
487
+ { method: 'GET', path: ROUTE_PATHS.report, handler: handleReport },
488
+ { method: 'POST', path: ROUTE_PATHS.toggle, handler: handleToggle },
489
+ { method: 'POST', path: ROUTE_PATHS.sleepIdle, handler: handleSleepIdle },
490
+ { method: 'POST', path: ROUTE_PATHS.undo, handler: handleUndo },
491
+ ]
492
+ }
493
+
package/lib/usage.js ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Usage facts: summarize local session tool/call events into per-tool call
3
+ * counts and last-used timestamps for a rolling window.
4
+ *
5
+ * Strict degradation rule: when the event source is unavailable or fails
6
+ * mid-stream, the summary is `{ unknown: true }` with an empty Map — never
7
+ * coerced to "zero calls", so newcomer recommendations never falsely accuse
8
+ * active plugins of sitting idle.
9
+ *
10
+ * @module dsh-plugin-slim/usage
11
+ */
12
+
13
+ const MS_PER_DAY = 24 * 60 * 60 * 1000
14
+ const DEFAULT_WINDOW_DAYS = 30
15
+
16
+ /**
17
+ * @typedef {object} ToolUsage
18
+ * @property {number} count
19
+ * @property {string | null} lastUsedAt
20
+ */
21
+
22
+ /**
23
+ * @typedef {object} UsageSummary
24
+ * @property {Map<string, ToolUsage>} byTool
25
+ * @property {boolean} unknown
26
+ */
27
+
28
+ /** @returns {UsageSummary} */
29
+ function unknownSummary() {
30
+ return { byTool: new Map(), unknown: true }
31
+ }
32
+
33
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
34
+ function isRecord(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
36
+ }
37
+
38
+ /** @param {unknown} value @returns {number | null} */
39
+ function parseTime(value) {
40
+ if (value instanceof Date) {
41
+ const time = value.getTime()
42
+ return Number.isFinite(time) ? time : null
43
+ }
44
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
45
+ if (typeof value === 'string' && value !== '') {
46
+ const time = Date.parse(value)
47
+ return Number.isNaN(time) ? null : time
48
+ }
49
+ return null
50
+ }
51
+
52
+ /** @param {unknown} windowDays @returns {number} */
53
+ function normalizeWindowDays(windowDays) {
54
+ return Number.isFinite(windowDays) && windowDays >= 0 ? windowDays : DEFAULT_WINDOW_DAYS
55
+ }
56
+
57
+ /** @param {unknown} row @returns {{ tool: string, time: number } | null} */
58
+ function readEvent(row) {
59
+ let event = row
60
+ if (typeof event === 'string') {
61
+ try {
62
+ event = JSON.parse(event)
63
+ } catch {
64
+ return null
65
+ }
66
+ }
67
+ if (!isRecord(event)) return null
68
+ if (typeof event.tool !== 'string' || event.tool === '') return null
69
+ const time = parseTime(event.at)
70
+ if (time === null) return null
71
+ return { tool: event.tool, time }
72
+ }
73
+
74
+ /**
75
+ * Summarize tool usage from a session event iterable.
76
+ * @param {{
77
+ * events?: (Iterable<unknown> & object) | AsyncIterable<unknown> | null,
78
+ * now?: Date | string | number,
79
+ * windowDays?: number,
80
+ * }} [input]
81
+ * @returns {Promise<UsageSummary>}
82
+ */
83
+ export async function summarizeUsage({ events, now, windowDays = DEFAULT_WINDOW_DAYS } = {}) {
84
+ const nowMs = parseTime(now)
85
+ if (nowMs === null) return unknownSummary()
86
+ if (events === null || events === undefined || typeof events !== 'object') return unknownSummary()
87
+ const iterable = typeof events[Symbol.asyncIterator] === 'function' || typeof events[Symbol.iterator] === 'function'
88
+ if (!iterable) return unknownSummary()
89
+
90
+ const cutoff = nowMs - normalizeWindowDays(windowDays) * MS_PER_DAY
91
+ /** @type {Map<string, { count: number, latest: number }>} */
92
+ const collected = new Map()
93
+ try {
94
+ for await (const row of events) {
95
+ const event = readEvent(row)
96
+ if (event === null) continue
97
+ if (event.time < cutoff || event.time > nowMs) continue
98
+ const entry = collected.get(event.tool)
99
+ if (entry === undefined) {
100
+ collected.set(event.tool, { count: 1, latest: event.time })
101
+ } else {
102
+ entry.count += 1
103
+ if (event.time > entry.latest) entry.latest = event.time
104
+ }
105
+ }
106
+ } catch {
107
+ return unknownSummary()
108
+ }
109
+
110
+ /** @type {Map<string, ToolUsage>} */
111
+ const byTool = new Map()
112
+ for (const [tool, entry] of collected) {
113
+ byTool.set(tool, { count: entry.count, lastUsedAt: new Date(entry.latest).toISOString() })
114
+ }
115
+ return { byTool, unknown: false }
116
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "dsh-plugin-slim",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "轻装(Plugin Slim):一眼揪出吃灰又占上下文的 DSH 插件,一键休眠瘦身、随时恢复,0 Agent 工具零负担。",
5
+ "license": "MIT",
6
+ "author": "fanyingnie",
7
+ "type": "module",
8
+ "main": "./lib/index.js",
9
+ "exports": {
10
+ ".": "./lib/index.js",
11
+ "./client": "./client.js",
12
+ "./icon": "./icon.svg",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "lib",
17
+ "client.js",
18
+ "icon.svg",
19
+ "cordis.patch.yml",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "scripts": {
24
+ "dev": "node scripts/dev.cjs",
25
+ "test": "node --test test/*.test.js",
26
+ "verify": "node scripts/verify.cjs",
27
+ "verify:coverage": "node scripts/verify.cjs --coverage"
28
+ },
29
+ "keywords": [
30
+ "deepseek-harness",
31
+ "dsh",
32
+ "dsh-plugin",
33
+ "plugin-slim",
34
+ "context-slim",
35
+ "token-saving",
36
+ "cordis",
37
+ "qingzhuang"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/fanyingnie2163663/dsh-plugin-slim.git"
42
+ },
43
+ "homepage": "https://github.com/fanyingnie2163663/dsh-plugin-slim#readme",
44
+ "bugs": {
45
+ "url": "https://github.com/fanyingnie2163663/dsh-plugin-slim/issues"
46
+ },
47
+ "dependencies": {
48
+ "yaml": "^2.5.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=20.0.0",
52
+ "dsh": ">=0.1.5-alpha.1 <0.2.0 || >=0.1.6-0 <0.2.0 || >=0.1.7-0 <0.2.0 || >=0.2.0-0 <0.3.0 || >=0.2.1-0 <0.3.0 || >=0.2.2-0 <0.3.0 || >=0.3.0-0 <0.4.0"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "dsh": {
58
+ "manifestVersion": 1,
59
+ "kind": "plugin",
60
+ "bundle": {
61
+ "patch": "./cordis.patch.yml"
62
+ },
63
+ "client": {
64
+ "platform": "web",
65
+ "inject": []
66
+ },
67
+ "capabilities": [
68
+ "fs:read",
69
+ "fs:write",
70
+ "network:ingress",
71
+ "sessions:read"
72
+ ],
73
+ "labels": []
74
+ }
75
+ }