dsh-macro-memory 0.0.0-stage → 0.4.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 (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +506 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +502 -0
  6. package/lib/macro/brand.js +82 -0
  7. package/lib/macro/bridge.js +158 -0
  8. package/lib/macro/chain.js +206 -0
  9. package/lib/macro/contract.js +471 -0
  10. package/lib/macro/cost.js +164 -0
  11. package/lib/macro/defs/admin.js +442 -0
  12. package/lib/macro/defs/dream.js +24 -0
  13. package/lib/macro/defs/link.js +257 -0
  14. package/lib/macro/defs/project.js +25 -0
  15. package/lib/macro/defs/read.js +160 -0
  16. package/lib/macro/defs/remember.js +411 -0
  17. package/lib/macro/defs/search.js +871 -0
  18. package/lib/macro/defs/update.js +161 -0
  19. package/lib/macro/dreamledger.js +1398 -0
  20. package/lib/macro/facade.js +135 -0
  21. package/lib/macro/fusion.js +182 -0
  22. package/lib/macro/linkflow.js +391 -0
  23. package/lib/macro/links.js +448 -0
  24. package/lib/macro/neighbor.js +209 -0
  25. package/lib/macro/panel.js +96 -0
  26. package/lib/macro/prompt.js +139 -0
  27. package/lib/macro/provenance.js +148 -0
  28. package/lib/macro/render.js +35 -0
  29. package/lib/macro/revisions.js +253 -0
  30. package/lib/macro/shared.js +113 -0
  31. package/lib/macro/store.js +103 -0
  32. package/lib/macro/supersede.js +197 -0
  33. package/lib/macro/tokencost.js +90 -0
  34. package/lib/macro/tools.js +67 -0
  35. package/package.json +54 -4
  36. package/vendor/VENDOR.json +23 -0
  37. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  38. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  39. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  40. package/vendor/dsh-memory-nebula/README.md +253 -0
  41. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  42. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  43. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  44. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  50. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  51. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  52. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  53. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  54. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  55. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  56. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  57. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  58. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  59. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  60. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  61. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  62. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  63. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  64. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  65. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  66. package/vendor/dsh-memory-nebula/lib/host/recall.js +524 -0
  67. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  68. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  69. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  70. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  71. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  72. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  73. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  74. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  75. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  76. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  77. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  78. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  79. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  80. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  81. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  82. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  83. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  84. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  85. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  86. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  87. package/vendor/dsh-memory-nebula/package.json +87 -0
  88. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  89. package/vendor/meow-memory/LICENSE +21 -0
  90. package/vendor/meow-memory/README.en.md +192 -0
  91. package/vendor/meow-memory/README.md +174 -0
  92. package/vendor/meow-memory/README.pt-br.md +180 -0
  93. package/vendor/meow-memory/cordis.patch.yml +7 -0
  94. package/vendor/meow-memory/lib/client.js +3344 -0
  95. package/vendor/meow-memory/lib/client.js.map +7 -0
  96. package/vendor/meow-memory/lib/index.js +9802 -0
  97. package/vendor/meow-memory/lib/index.js.map +7 -0
  98. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  101. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  102. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  103. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  104. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  105. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  106. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  107. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  108. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  109. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  119. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  120. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  123. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  124. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  125. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  126. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  127. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  128. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  129. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  130. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  131. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  132. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,396 @@
1
+ // 会话转写读取:DSH 的 session.v4.jsonl.zstd 是「多帧 zstd 拼接」,
2
+ // node 的 zstdDecompressSync 只解第一帧(198 字节),所以自己按帧头切。
3
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
4
+ import * as zlib from 'node:zlib'
5
+ // node:zlib 的 zstd 解压是 22.15 才有的,而 engines 写着 >=22.13:
6
+ // 写成具名导入的话,老 node 一加载这个模块就报「没有这个导出」,整个插件跟着挂(1.11.41 修)。
7
+ // 改成命名空间导入 + 特性探测:没有 zstd 时只关掉「读会话转写」这一件事。
8
+ const zstdDecompressSync = typeof zlib.zstdDecompressSync === 'function' ? zlib.zstdDecompressSync : null
9
+ import { join } from 'node:path'
10
+ import { dshHome } from './sources.js'
11
+
12
+ const ZSTD_MAGIC = 0xfd2fb528
13
+ const SKIP_MAGIC = 0x184d2a50
14
+ const SKIP_MASK = 0xfffffff0
15
+ const TRANSCRIPT = 'session.v4.jsonl.zstd'
16
+ // 运行时上下文 / 记忆注入块 / 系统提示这类「假用户消息」不算主人说的话
17
+ const FAKE_USER =
18
+ /^(Current runtime context|\[prompt-inject\]|\[本机长期记忆|\[记忆|(本机长期记忆|(现在是|【meow-memory|可能相关的记忆|=+\s*$|<goal_round>|<acp |<system-reminder>|<available_skills>|<|\s*\[bili\])/
19
+ // 长到不像人话的「用户消息」基本都是注入的系统上下文
20
+ const MAX_USER_CHARS = 1500
21
+
22
+ /**
23
+ * 把多帧 zstd 切成单帧。[start,end) 可直接喂给 zstdDecompressSync。
24
+ */
25
+ export function splitZstdFrames(buf) {
26
+ const frames = []
27
+ let o = 0
28
+ while (o + 4 <= buf.length) {
29
+ const magic = buf.readUInt32LE(o)
30
+ if ((magic & SKIP_MASK) === SKIP_MAGIC) {
31
+ if (o + 8 > buf.length) break
32
+ const size = buf.readUInt32LE(o + 4)
33
+ const end = o + 8 + size
34
+ if (end > buf.length) break
35
+ frames.push({ start: o, end, skip: true })
36
+ o = end
37
+ continue
38
+ }
39
+ if (magic !== ZSTD_MAGIC) return { frames, error: `bad magic at ${o}` }
40
+ let p = o + 4
41
+ if (p >= buf.length) break
42
+ const fhd = buf[p]
43
+ p += 1
44
+ const fcsFlag = fhd >> 6
45
+ const singleSegment = (fhd >> 5) & 1
46
+ const hasChecksum = (fhd >> 2) & 1
47
+ const dictFlag = fhd & 3
48
+ if (!singleSegment) p += 1
49
+ p += dictFlag === 0 ? 0 : dictFlag === 1 ? 1 : dictFlag === 2 ? 2 : 4
50
+ if (fcsFlag === 0) p += singleSegment ? 1 : 0
51
+ else p += fcsFlag === 1 ? 2 : fcsFlag === 2 ? 4 : 8
52
+ if (p > buf.length) break
53
+ let last = false
54
+ while (!last) {
55
+ if (p + 3 > buf.length) return { frames, error: `truncated at ${p}` }
56
+ const h = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16)
57
+ p += 3
58
+ last = (h & 1) === 1
59
+ const type = (h >> 1) & 3
60
+ const size = h >> 3
61
+ if (type === 0 || type === 2) p += size
62
+ else if (type === 1) p += 1
63
+ else return { frames, error: `reserved block at ${p}` }
64
+ if (p > buf.length) return { frames, error: `overrun at ${p}` }
65
+ }
66
+ if (hasChecksum) p += 4
67
+ if (p > buf.length) return { frames, error: `overrun after frame at ${p}` }
68
+ frames.push({ start: o, end: p, skip: false })
69
+ o = p
70
+ }
71
+ return { frames }
72
+ }
73
+
74
+ /** 解整个多帧文件为 utf8 文本。 */
75
+ export function decompressTranscript(buf) {
76
+ if (!zstdDecompressSync) return { error: '这个 node 没有 zstd 解码(node:zlib 的 zstd 是 22.15 起才有的)' }
77
+ const { frames, error } = splitZstdFrames(buf)
78
+ if (error) return { error }
79
+ const parts = []
80
+ for (const f of frames) {
81
+ if (f.skip) continue
82
+ try {
83
+ parts.push(zstdDecompressSync(buf.subarray(f.start, f.end)))
84
+ } catch (e) {
85
+ return { error: `frame ${f.start}: ${e.message}` }
86
+ }
87
+ }
88
+ return { text: Buffer.concat(parts).toString('utf8'), frames: frames.length }
89
+ }
90
+
91
+ let transcriptIndex = null
92
+ let transcriptIndexAt = 0
93
+
94
+ /**
95
+ * 索引多久重扫一次。会话是「开着开着就多出来」的东西,
96
+ * 索引建完就冻结的话,新会话永远进不来(来源面板的会话数会停在开机那一刻)。
97
+ * NEBULA_TRANSCRIPT_INDEX_TTL=0 可以强制每次重扫(测试与探针用)。
98
+ */
99
+ const INDEX_TTL_DEFAULT = 30 * 1000
100
+
101
+ function indexTtlMs() {
102
+ const raw = Number(process.env.NEBULA_TRANSCRIPT_INDEX_TTL)
103
+ return Number.isFinite(raw) && raw >= 0 ? raw : INDEX_TTL_DEFAULT
104
+ }
105
+
106
+ /** 丢掉索引缓存(测试用;也可以在改完 sources.json 后手动叫一次)。 */
107
+ export function resetTranscriptIndex() {
108
+ transcriptIndex = null
109
+ transcriptIndexAt = 0
110
+ }
111
+
112
+ /** sessionId → 转写文件路径(带有效期,过期就重扫)。 */
113
+ export function transcriptIndex_() {
114
+ if (transcriptIndex && Date.now() - transcriptIndexAt < indexTtlMs()) return transcriptIndex
115
+ const root = join(dshHome(), 'sessions')
116
+ const map = new Map()
117
+ let dirs = []
118
+ try {
119
+ dirs = readdirSync(root)
120
+ } catch {
121
+ transcriptIndex = map
122
+ transcriptIndexAt = Date.now()
123
+ return map
124
+ }
125
+ for (const d of dirs) {
126
+ const p = join(root, d)
127
+ let st
128
+ try {
129
+ st = statSync(p)
130
+ } catch {
131
+ continue
132
+ }
133
+ if (!st.isDirectory()) continue
134
+ let subs = []
135
+ try {
136
+ subs = readdirSync(p)
137
+ } catch {
138
+ continue
139
+ }
140
+ for (const s of subs) {
141
+ const q = join(p, s)
142
+ let st2
143
+ try {
144
+ st2 = statSync(q)
145
+ } catch {
146
+ continue
147
+ }
148
+ if (st2.isDirectory()) {
149
+ const file = join(q, TRANSCRIPT)
150
+ try {
151
+ const stf = statSync(file)
152
+ const id = s.replace(/^session-/, '')
153
+ map.set(id, { file, mtime: stf.mtimeMs, size: stf.size })
154
+ map.set(s, { file, mtime: stf.mtimeMs, size: stf.size })
155
+ } catch {}
156
+ }
157
+ }
158
+ }
159
+ transcriptIndex = map
160
+ transcriptIndexAt = Date.now()
161
+ return map
162
+ }
163
+
164
+ const userCache = new Map() // file → { mtime, messages }
165
+
166
+ /** 抽出这个会话里「主人真的说过」的话(按时间升序),带 5 分钟内存缓存。 */
167
+ export function readUserMessages(file) {
168
+ let st
169
+ try {
170
+ st = statSync(file)
171
+ } catch {
172
+ return []
173
+ }
174
+ const hit = userCache.get(file)
175
+ if (hit && hit.mtime === st.mtimeMs) return hit.messages
176
+ let buf
177
+ try {
178
+ buf = readFileSync(file)
179
+ } catch {
180
+ return []
181
+ }
182
+ const r = decompressTranscript(buf)
183
+ if (r.error || !r.text) return []
184
+ const messages = []
185
+ for (const line of r.text.split('\n')) {
186
+ if (!line || line[0] !== '{') continue
187
+ let o
188
+ try {
189
+ o = JSON.parse(line)
190
+ } catch {
191
+ continue
192
+ }
193
+ if (o.type !== 'user/message') continue
194
+ const data = o.data || {}
195
+ const kind = data.source && data.source.kind
196
+ if (kind && kind !== 'user') continue
197
+ const parts = Array.isArray(data.content) ? data.content : []
198
+ let text = ''
199
+ for (const part of parts) if (part && part.type === 'text' && part.text) text += part.text
200
+ text = text.trim()
201
+ if (!text || FAKE_USER.test(text) || text.length > MAX_USER_CHARS) continue
202
+ messages.push({ time: o.time || 0, text })
203
+ }
204
+ messages.sort((a, b) => a.time - b.time)
205
+ userCache.set(file, { mtime: st.mtimeMs, messages })
206
+ return messages
207
+ }
208
+
209
+ const originCache = new Map() // sessionId|createdAt → origin
210
+
211
+ /**
212
+ * 这条记忆是在「哪句话」之后写下的?
213
+ * 取该会话里时间上最近的前一条真实用户消息(允许往后找 2 分钟内的)。
214
+ */
215
+ export function originOfMemory({ sessionId, createdAt, maxGapMs = 45 * 60 * 1000 }) {
216
+ if (!sessionId || !createdAt) return null
217
+ const key = `${sessionId}|${createdAt}`
218
+ if (originCache.has(key)) return originCache.get(key)
219
+ const idx = transcriptIndex_()
220
+ const entry = idx.get(sessionId) || idx.get(`session-${sessionId}`)
221
+ if (!entry) {
222
+ // 不缓存 null:会话可能刚刚才有转写,索引下一轮重扫就能找到它
223
+ return null
224
+ }
225
+ let messages
226
+ try {
227
+ messages = readUserMessages(entry.file)
228
+ } catch {
229
+ messages = []
230
+ }
231
+ let best = null
232
+ for (const m of messages) {
233
+ if (m.time <= createdAt + 2000) {
234
+ if (!best || m.time > best.time) best = m
235
+ }
236
+ }
237
+ let origin = null
238
+ if (best && createdAt - best.time <= maxGapMs) {
239
+ origin = {
240
+ text: best.text.length > 600 ? best.text.slice(0, 600) + '…' : best.text,
241
+ time: best.time,
242
+ gapMs: createdAt - best.time,
243
+ sessionId,
244
+ source: 'transcript',
245
+ }
246
+ }
247
+ originCache.set(key, origin)
248
+ return origin
249
+ }
250
+
251
+ /** 会话转写统计:给「来源面板」用。 */
252
+ export function transcriptStats() {
253
+ const idx = transcriptIndex_()
254
+ const files = new Set()
255
+ let bytes = 0
256
+ for (const v of idx.values()) {
257
+ if (files.has(v.file)) continue
258
+ files.add(v.file)
259
+ bytes += v.size
260
+ }
261
+ return { sessions: files.size, bytes }
262
+ }
263
+
264
+ /**
265
+ * 工具调用画像:从转写里的 `tool/call` 事件统计「哪个技能 / 哪个 MCP 真被调用过」。
266
+ *
267
+ * 映射规则(宁少不多):
268
+ * - `name === 'skill'` 且 arguments 里 `{ name }` → 技能名
269
+ * - `name` 形如 `mcp__<server>__<tool>` → MCP 服务器名
270
+ * 别的工具(ops_bash / edit …)只算进总数,不归因到来源。
271
+ *
272
+ * 结果按「索引签名」缓存(文件数 + 总大小 + 最新 mtime),转写有变动才重扫。
273
+ */
274
+ let usageCache = { sig: '', data: null }
275
+
276
+ /**
277
+ * 有些记忆 / 记忆类插件不走 `mcp__` 前缀,而是自己的工具名(`memory_search`…),
278
+ * 这里按前缀归因,仍然是「名字对得上才认」。
279
+ *
280
+ * [macro-fusion 0.2.80] 归因名统一成融合后的插件身份:记忆类与星图类工具都算
281
+ * `plugin:macro-memory`(面板上显示的「工具调用画像」不该把自家工具说成两个插件)。
282
+ */
283
+ const TOOL_OWNER = {
284
+ memory_search: 'plugin:macro-memory',
285
+ memory_remember: 'plugin:macro-memory',
286
+ memory_update: 'plugin:macro-memory',
287
+ memory_read: 'plugin:macro-memory',
288
+ memory_project: 'plugin:macro-memory',
289
+ memory_dream: 'plugin:macro-memory',
290
+ hindsight_search_knowledge_pages: 'plugin:hindsight',
291
+ hindsight_reflect: 'plugin:hindsight',
292
+ hindsight_ingest_document: 'plugin:hindsight',
293
+ nebula_recall: 'plugin:macro-memory',
294
+ nebula_inspect: 'plugin:macro-memory',
295
+ nebula_link: 'plugin:macro-memory',
296
+ nebula_path: 'plugin:macro-memory',
297
+ nebula_stats: 'plugin:macro-memory',
298
+ nebula_sources: 'plugin:macro-memory',
299
+ nebula_ingest: 'plugin:macro-memory',
300
+ nebula_hygiene: 'plugin:macro-memory',
301
+ nebula_bridge: 'plugin:macro-memory',
302
+ }
303
+ const TOOL_PREFIX = [
304
+ ['weknora_', 'weknora'],
305
+ ['bsk_', 'browser-skill'],
306
+ ['ov_', 'openviking'],
307
+ ]
308
+
309
+ function usageSignature(idx) {
310
+ const files = new Set()
311
+ let bytes = 0
312
+ let mtime = 0
313
+ for (const v of idx.values()) {
314
+ if (files.has(v.file)) continue
315
+ files.add(v.file)
316
+ bytes += v.size
317
+ if (v.mtime > mtime) mtime = v.mtime
318
+ }
319
+ return `${files.size}:${bytes}:${Math.round(mtime)}`
320
+ }
321
+
322
+ /** @returns {{bySource: Map<string, {calls:number, sessions:Set<string>, last:number}>, toolCalls:number, scanned:number}} */
323
+ export function usageIndex() {
324
+ const idx = transcriptIndex_()
325
+ const sig = usageSignature(idx)
326
+ if (usageCache.data && usageCache.sig === sig) return usageCache.data
327
+ // 会话一直在写,签名几乎每分钟都变;统计很贵(141 个转写 ≈ 4s),
328
+ // 所以 5 分钟内直接用上次结果,别把每次打开详情都做成全量扫描。
329
+ if (usageCache.data && Date.now() - (usageCache.at || 0) < 5 * 60 * 1000) return usageCache.data
330
+
331
+ const bySource = new Map()
332
+ const seen = new Set()
333
+ let toolCalls = 0
334
+ for (const [key, entry] of idx) {
335
+ if (key.startsWith('session-')) continue // 双键登记,只用裸 id 那一条
336
+ if (seen.has(entry.file)) continue
337
+ seen.add(entry.file)
338
+ let text = ''
339
+ try {
340
+ const res = decompressTranscript(readFileSync(entry.file))
341
+ text = res.text || ''
342
+ } catch {
343
+ continue
344
+ }
345
+ for (const line of text.split('\n')) {
346
+ if (!line.includes('"tool/call"')) continue
347
+ let ev
348
+ try {
349
+ ev = JSON.parse(line)
350
+ } catch {
351
+ continue
352
+ }
353
+ const d = ev?.data || {}
354
+ const name = String(d.name || '')
355
+ if (!name) continue
356
+ toolCalls += 1
357
+ let src = null
358
+ if (name === 'skill') {
359
+ try {
360
+ const args = typeof d.arguments === 'string' ? JSON.parse(d.arguments) : d.arguments || {}
361
+ if (args && args.name) src = 'skill:' + String(args.name).toLowerCase()
362
+ } catch {}
363
+ } else if (name.startsWith('mcp__')) {
364
+ const parts = name.split('__')
365
+ if (parts.length >= 2) src = 'mcp:' + parts[1].toLowerCase()
366
+ } else if (TOOL_OWNER[name] || TOOL_PREFIX.find((p) => name.startsWith(p[0]))) {
367
+ src = TOOL_OWNER[name] || 'plugin:' + TOOL_PREFIX.find((p) => name.startsWith(p[0]))[1]
368
+ }
369
+ if (!src) continue
370
+ let row = bySource.get(src)
371
+ if (!row) {
372
+ row = { calls: 0, sessions: new Set(), last: 0 }
373
+ bySource.set(src, row)
374
+ }
375
+ row.calls += 1
376
+ row.sessions.add(key)
377
+ if (ev.time > row.last) row.last = ev.time
378
+ }
379
+ }
380
+ usageCache = { sig, at: Date.now(), data: { bySource, toolCalls, scanned: seen.size } }
381
+ return usageCache.data
382
+ }
383
+
384
+ /** 某个来源(技能 / MCP / 插件)实际被调用过多少次、分布在几个会话。 */
385
+ export function usageOf(kind, name) {
386
+ if (!name) return null
387
+ const { bySource } = usageIndex()
388
+ const lower = String(name).toLowerCase()
389
+ // 同一个名字可能既是 MCP 又是插件(meow-memory 就是),按 mcp → plugin → skill 依次找
390
+ const kinds = [kind, 'mcp', 'plugin', 'skill'].filter(Boolean)
391
+ for (const k of [...new Set(kinds)]) {
392
+ const row = bySource.get(`${k}:${lower}`)
393
+ if (row) return { calls: row.calls, sessions: row.sessions.size, last: row.last, via: k }
394
+ }
395
+ return { calls: 0, sessions: 0, last: 0 }
396
+ }