dsh-macro-memory 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +457 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +469 -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 +439 -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 +145 -0
  16. package/lib/macro/defs/remember.js +213 -0
  17. package/lib/macro/defs/search.js +661 -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/tokencost.js +90 -0
  33. package/lib/macro/tools.js +67 -0
  34. package/package.json +54 -4
  35. package/vendor/VENDOR.json +23 -0
  36. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  37. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  38. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  39. package/vendor/dsh-memory-nebula/README.md +253 -0
  40. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  41. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  42. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  43. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  44. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +317 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  50. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  51. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  52. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  53. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  54. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  55. package/vendor/dsh-memory-nebula/lib/host/graph.js +1663 -0
  56. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +282 -0
  57. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  58. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  59. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  60. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  61. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  62. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  63. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  64. package/vendor/dsh-memory-nebula/lib/host/recall.js +451 -0
  65. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  66. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  67. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  68. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  69. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  70. package/vendor/dsh-memory-nebula/lib/index.js +759 -0
  71. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  72. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  73. package/vendor/dsh-memory-nebula/lib/web/app.js +4159 -0
  74. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  75. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  76. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  77. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  78. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  79. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  80. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  81. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  82. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  83. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  84. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  85. package/vendor/dsh-memory-nebula/package.json +87 -0
  86. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  87. package/vendor/meow-memory/LICENSE +21 -0
  88. package/vendor/meow-memory/README.en.md +192 -0
  89. package/vendor/meow-memory/README.md +174 -0
  90. package/vendor/meow-memory/README.pt-br.md +180 -0
  91. package/vendor/meow-memory/cordis.patch.yml +7 -0
  92. package/vendor/meow-memory/lib/client.js +3344 -0
  93. package/vendor/meow-memory/lib/client.js.map +7 -0
  94. package/vendor/meow-memory/lib/index.js +9567 -0
  95. package/vendor/meow-memory/lib/index.js.map +7 -0
  96. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  97. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  98. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  101. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  102. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  103. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  104. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  105. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  106. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  107. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  108. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  109. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  119. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  120. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  123. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  124. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  125. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  126. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  127. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  128. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  129. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  130. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,351 @@
1
+ /**
2
+ * 注入桥(bridge)—— 「别的记忆插件喂了什么,星图补什么」
3
+ *
4
+ * 这是星图和其他记忆插件协同工作的核心。
5
+ *
6
+ * 场景:meow-memory 本轮注入了 3 条记忆;hindsight 又塞了 2 条知识页。
7
+ * 星图知道这些记忆在图上连着什么,但**不该重复**把已注入的东西再讲一遍。
8
+ * 它该做的是:从那 5 条出发,沿边扩散一跳,挑出 2~4 条「最强、最没被讲过、
9
+ * 又能把这件事补圆」的邻居,作为补充包一起注入。
10
+ *
11
+ * 于是同一个上下文预算里,装载的信息量变大,而不是同一句话说五遍。
12
+ *
13
+ * 打分(score):
14
+ * 扩散能量(seed=1,一跳 × w,二跳 × w₁·w₂)
15
+ * × 重要性系数(1 + imp·0.15)
16
+ * × 热度系数(1 + min(heat,3)·0.08)
17
+ * × 状态系数(active 1,stale 0.7,archived 0)
18
+ * × 同工作区亲和(1.08 / 跨区 1.0)
19
+ * × 超连接惩罚(degree>60 时 0.85:枢纽节点什么都连,信息密度低)
20
+ * 再排除:已见、冷却中、权重低于门槛、自己
21
+ *
22
+ * 最后按工作区/层级做多样性配额,避免四条全是同一类东西。
23
+ */
24
+ import { resolveIds } from './recall.js'
25
+ import { recall } from './recall.js'
26
+ import { clip } from './text.js'
27
+
28
+ export const DEFAULT_BUDGET = {
29
+ maxItems: 4,
30
+ maxChars: 900,
31
+ minWeight: 0.5,
32
+ hops: 1,
33
+ perWorkspace: 2,
34
+ perLevel: 2,
35
+ maxDegree: 400,
36
+ }
37
+
38
+ /** 建邻接表(i → [{j,w,type,why}])。O(E)。 */
39
+ export function adjacency(graph) {
40
+ const adj = new Map()
41
+ const add = (a, b, edge) => {
42
+ let list = adj.get(a)
43
+ if (!list) adj.set(a, (list = []))
44
+ list.push({ j: b, w: edge.w, type: edge.type, why: edge.why || [] })
45
+ }
46
+ for (const edge of graph?.edges || []) {
47
+ add(edge.s, edge.t, edge)
48
+ add(edge.t, edge.s, edge)
49
+ }
50
+ return adj
51
+ }
52
+
53
+ /** 节点的所有「身份串」:完整 id + 裸 uid。 */
54
+ function identitiesOf(node) {
55
+ const out = [node.id]
56
+ const parts = String(node.id).split(':')
57
+ if (parts.length > 1) out.push(parts[parts.length - 1])
58
+ if (node.uid) out.push(String(node.uid))
59
+ return out
60
+ }
61
+
62
+ function isSeen(node, seen) {
63
+ if (!seen) return false
64
+ for (const key of identitiesOf(node)) if (seen.has(key)) return true
65
+ return false
66
+ }
67
+
68
+ function statusFactor(status) {
69
+ const s = String(status || 'active').toLowerCase()
70
+ if (s === 'archived' || s === 'deleted') return 0
71
+ if (s === 'stale' || s === 'done') return 0.7
72
+ return 1
73
+ }
74
+
75
+ /**
76
+ * 从种子扩散,返回候选(未过滤筛选)。
77
+ * @param {object} graph buildGraph 产物
78
+ * @param {object} opts {ids, query, hops, adj}
79
+ */
80
+ /** 非有限数字(NaN / Infinity / undefined)回落到默认值。 */
81
+ function num(value, fallback) {
82
+ const n = Number(value)
83
+ return Number.isFinite(n) ? n : fallback
84
+ }
85
+
86
+ export function spread(graph, opts = {}) {
87
+ const nodes = graph?.nodes || []
88
+ const adj = opts.adj || adjacency(graph)
89
+ const hops = Math.max(0, Math.min(3, num(opts.hops, 1)))
90
+ const energy = new Map() // i → {e, seeds:Set<i>, via:edge}
91
+ const byId = new Map(nodes.map((n) => [n.id, n]))
92
+
93
+ const seedIdx = new Set()
94
+ if (Array.isArray(opts.ids) && opts.ids.length > 0) {
95
+ for (const node of resolveIds(nodes, opts.ids)) seedIdx.add(node.i)
96
+ }
97
+ if (seedIdx.size === 0 && opts.query) {
98
+ try {
99
+ const res = recall(graph, String(opts.query), { limit: opts.seedLimit || 6, hops: 0 })
100
+ // recall() 的返回键是 hits(早期版本叫 items),两种都认
101
+ const hits = res?.hits || res?.items || []
102
+ for (const hit of hits) {
103
+ const node = byId.get(hit.id)
104
+ if (node) seedIdx.add(node.i)
105
+ }
106
+ } catch {
107
+ /* recall 失败不影响 bridge 本身 */
108
+ }
109
+ }
110
+ for (const i of seedIdx) energy.set(i, { e: 1, seeds: new Set([i]), via: null })
111
+
112
+ // 兼容两种邻接表:bridge 自己的 {j,w,type,why} 和 nebula 索引的 {n,w,t,why}
113
+ const target = (edge) => (edge.j !== undefined ? edge.j : edge.n)
114
+ const kind = (edge) => edge.type || edge.t || ''
115
+
116
+ let frontier = [...seedIdx]
117
+ for (let hop = 1; hop <= hops; hop += 1) {
118
+ const next = []
119
+ for (const from of frontier) {
120
+ const fromE = energy.get(from)
121
+ if (!fromE) continue
122
+ for (const raw of adj.get(from) || []) {
123
+ const to = target(raw)
124
+ if (to === undefined || to === null) continue
125
+ const edge = { j: to, w: raw.w, type: kind(raw), why: raw.why || [] }
126
+ if (edge.type === 'explicit') {
127
+ // 策展边:一步到位,按 1.0 计
128
+ const cur = energy.get(edge.j) || { e: 0, seeds: new Set(), via: null }
129
+ const gain = 1.0
130
+ if (gain > cur.e) {
131
+ cur.e = gain
132
+ cur.seeds.add(from)
133
+ cur.via = { ...edge, from, hop }
134
+ energy.set(edge.j, cur)
135
+ next.push(edge.j)
136
+ }
137
+ continue
138
+ }
139
+ const gain = (fromE.e / Math.max(1, hop)) * edge.w
140
+ if (gain < 0.08) continue
141
+ const cur = energy.get(edge.j) || { e: 0, seeds: new Set(), via: null }
142
+ if (gain > cur.e) {
143
+ cur.e = gain
144
+ cur.seeds.add(from)
145
+ cur.via = { ...edge, from, hop }
146
+ energy.set(edge.j, cur)
147
+ next.push(edge.j)
148
+ }
149
+ }
150
+ }
151
+ frontier = [...new Set(next)]
152
+ if (frontier.length === 0) break
153
+ }
154
+
155
+ energy.delete(-1)
156
+ return { energy, seedIdx, adj }
157
+ }
158
+
159
+ /**
160
+ * 主入口:算出「该补什么」。
161
+ *
162
+ * @param {object} graph
163
+ * @param {object} opts
164
+ * @param {string[]} [opts.ids] 别的插件刚喂过的记忆 id(种子)
165
+ * @param {string} [opts.query] 没有 ids 时,用查询词找种子
166
+ * @param {Set<string>} [opts.seen] 已见集合(完整 id 或裸 uid)
167
+ * @param {Map<string,number>} [opts.cooldown] uid → 上次注入时间
168
+ * @param {object} [opts.budget] 预算
169
+ * @param {boolean} [opts.allowStale] 是否允许 stale(默认不要:0.7 降权只在明确允许时生效)
170
+ * @returns {{items: object[], text: string, seeds: object[], stats: object}}
171
+ */
172
+ export function bridge(graph, opts = {}) {
173
+ // 预算里的数字一律过 num():调用方写 Number(undefined) ?? 1 会得到 NaN,
174
+ // 而 NaN 会让「扩散几跳」那个循环一次都不跑——静默返回空,最难查。
175
+ const raw = { ...DEFAULT_BUDGET, ...(opts.budget || {}) }
176
+ const budget = {
177
+ maxItems: num(raw.maxItems, DEFAULT_BUDGET.maxItems),
178
+ maxChars: num(raw.maxChars, DEFAULT_BUDGET.maxChars),
179
+ minWeight: num(raw.minWeight, DEFAULT_BUDGET.minWeight),
180
+ hops: num(raw.hops, DEFAULT_BUDGET.hops),
181
+ perWorkspace: num(raw.perWorkspace, DEFAULT_BUDGET.perWorkspace),
182
+ perLevel: num(raw.perLevel, DEFAULT_BUDGET.perLevel),
183
+ maxDegree: num(raw.maxDegree, DEFAULT_BUDGET.maxDegree),
184
+ }
185
+ const nodes = graph?.nodes || []
186
+ const byIdx = new Map(nodes.map((n) => [n.i, n]))
187
+ const { energy, seedIdx } = spread(graph, {
188
+ ids: opts.ids,
189
+ query: opts.query,
190
+ hops: budget.hops,
191
+ adj: opts.adj,
192
+ })
193
+ const seen = opts.seen || new Set()
194
+ const cooldown = opts.cooldown || new Map()
195
+ const now = Date.now()
196
+
197
+ const seeds = []
198
+ for (const i of seedIdx) {
199
+ const node = byIdx.get(i)
200
+ if (node) seeds.push({ id: node.id, title: node.title || node.label, ws: node.wsTitle, level: node.level })
201
+ }
202
+
203
+ const candidates = []
204
+ for (const [i, info] of energy) {
205
+ if (seedIdx.has(i)) continue
206
+ const node = byIdx.get(i)
207
+ if (!node) continue
208
+ if (isSeen(node, seen)) continue
209
+ const sf = statusFactor(node.status)
210
+ if (sf === 0) continue
211
+ if (!opts.allowStale && sf < 1) continue
212
+ const edge = info.via
213
+ const weight = edge ? edge.w : 0
214
+ if (weight < budget.minWeight) continue
215
+ const degree = Number(node.degree) || 0
216
+ if (degree > budget.maxDegree) continue
217
+ const uid = String(node.id).split(':').pop()
218
+ if (cooldown.has(uid)) continue
219
+
220
+ const co = 1 + Math.min(4, Number(node.importance) || 0) * 0.15
221
+ const heat = 1 + Math.min(3, Number(node.heat) || 0) * 0.08
222
+ const hub = degree > 60 ? 0.85 : 1
223
+ let score = info.e * co * heat * sf * hub
224
+ if (opts.ws && node.ws === opts.ws) score *= 1.08
225
+ // 越久没被碰过的,稍微抬一点:让「沉底的好记忆」有机会浮上来
226
+ const last = Number(node.accessedAt || node.updatedAt || node.createdAt || 0)
227
+ if (last > 0) {
228
+ const days = (now - last) / 86400000
229
+ if (days > 45) score *= 1.06
230
+ }
231
+
232
+ candidates.push({
233
+ i,
234
+ id: node.id,
235
+ uid,
236
+ title: node.title || node.label,
237
+ label: node.label,
238
+ ws: node.ws,
239
+ wsTitle: node.wsTitle,
240
+ level: node.level,
241
+ importance: node.importance,
242
+ status: node.status,
243
+ project: node.project,
244
+ preview: clip(node.preview || node.content || '', 220),
245
+ score,
246
+ edgeWeight: weight,
247
+ edgeType: edge?.type || '',
248
+ why: (edge?.why || []).slice(0, 3),
249
+ hop: edge?.hop || 1,
250
+ seeds: [...info.seeds].map((s) => byIdx.get(s)).filter(Boolean).map((n) => n.title || n.label),
251
+ })
252
+ }
253
+
254
+ candidates.sort((a, b) => b.score - a.score)
255
+
256
+ // 多样性配额:先按 ws / level 各限 perWorkspace / perLevel,不够再放宽
257
+ const picked = []
258
+ const wsCount = new Map()
259
+ const levelCount = new Map()
260
+ const take = (item, relax) => {
261
+ if (picked.length >= budget.maxItems) return false
262
+ const ws = item.ws || ''
263
+ const lv = item.level || ''
264
+ if (!relax) {
265
+ if ((wsCount.get(ws) || 0) >= budget.perWorkspace) return false
266
+ if ((levelCount.get(lv) || 0) >= budget.perLevel) return false
267
+ }
268
+ picked.push(item)
269
+ wsCount.set(ws, (wsCount.get(ws) || 0) + 1)
270
+ levelCount.set(lv, (levelCount.get(lv) || 0) + 1)
271
+ return true
272
+ }
273
+ for (const item of candidates) take(item, false)
274
+ if (picked.length < budget.maxItems) {
275
+ for (const item of candidates) {
276
+ if (picked.includes(item)) continue
277
+ take(item, true)
278
+ }
279
+ }
280
+
281
+ // 字符预算:超了就从尾巴砍
282
+ let chars = 0
283
+ const bounded = []
284
+ for (const item of picked) {
285
+ const cost = renderLine(item).length
286
+ if (chars + cost > budget.maxChars && bounded.length > 0) break
287
+ chars += cost
288
+ bounded.push(item)
289
+ }
290
+
291
+ return {
292
+ items: bounded,
293
+ text: bounded.map(renderLine).join('\n'),
294
+ seeds,
295
+ stats: {
296
+ seedCount: seedIdx.size,
297
+ considered: candidates.length,
298
+ picked: bounded.length,
299
+ chars,
300
+ hops: budget.hops,
301
+ },
302
+ }
303
+ }
304
+
305
+ /** 一条补充项的紧凑渲染(给模型读的)。 */
306
+ export function renderLine(item) {
307
+ const why = (item.why || []).slice(0, 2).join(';')
308
+ const head = `- 【${LEVEL_ZH[item.level] || item.level || '记忆'}·${shortWs(item.wsTitle)}】${clip(item.title || item.label || '', 46)}`
309
+ return why ? `${head} —— ${why}` : head
310
+ }
311
+
312
+ const LEVEL_ZH = {
313
+ project: '项目',
314
+ fact: '事实',
315
+ lesson: '教训',
316
+ topic: '话题',
317
+ user: '主人',
318
+ rules: '准则',
319
+ soul: '灵魂',
320
+ note: '笔记',
321
+ }
322
+
323
+ function shortWs(title) {
324
+ const s = String(title || '').trim()
325
+ if (s.length <= 14) return s
326
+ return s.slice(0, 13) + '…'
327
+ }
328
+
329
+ /**
330
+ * 从一段上下文文本里提出「已经被别家插件写进 prompt 的记忆标题」。
331
+ *
332
+ * 用途:不是所有插件都留账本。有的只是把一段 markdown 塞进 systemPrompt。
333
+ * 那就从文本里反查:这段话里点到的标题,算已见。
334
+ *
335
+ * 做法保守:只认长度 ≥ 6 的节点标题在文本里出现,且要求成对出现(标题 + 工作区/层名)
336
+ * 太容易误判,所以这里只做「标题完全一致」这一条,宁可漏判不误判。
337
+ */
338
+ export function seenFromText(graph, text) {
339
+ const out = new Set()
340
+ const haystack = String(text || '')
341
+ if (haystack.length < 20) return out
342
+ for (const node of graph?.nodes || []) {
343
+ const title = String(node.title || '').trim()
344
+ if (title.length < 8) continue
345
+ if (haystack.includes(title)) {
346
+ const parts = String(node.id).split(':')
347
+ out.add(parts[parts.length - 1])
348
+ }
349
+ }
350
+ return out
351
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 响应压缩:1.8.0 开始,星图的大响应(/graph、/share、静态脚本)按 Accept-Encoding 压缩。
3
+ *
4
+ * 为什么值得单开一个模块:
5
+ * - 真实库 2000+ 条记忆时 /graph 约 1MB,每换一次图整包重传;20k 时是 20MB。
6
+ * gzip 一般能到原大小的 15–25%,这是首屏最便宜的一刀。
7
+ * - 快照是拿出去分发的文件(360KB+),服务端直接回压缩体,下载也快。
8
+ * - 协商规则(q 值、`*`、`q=0`)容易被写错成「有头就压」,所以单独放一处、单独测。
9
+ *
10
+ * 只用 node:zlib,不引入运行时依赖(包一直是零依赖)。
11
+ */
12
+ import { brotliCompress, gzip, deflate, constants as zlibConstants } from 'node:zlib'
13
+ import { promisify } from 'node:util'
14
+
15
+ const brotli = promisify(brotliCompress)
16
+ const gzipAsync = promisify(gzip)
17
+ const deflateAsync = promisify(deflate)
18
+
19
+ /** 小于这个字节数不压:压缩头和 CPU 都不划算,也免得小响应多出一次协商差异。 */
20
+ export const MIN_COMPRESS_BYTES = 1024
21
+
22
+ /** 偏好顺序:br 体积最小,其次 gzip(兼容性最好),deflate 兜底。 */
23
+ const ORDER = ['br', 'gzip', 'deflate']
24
+
25
+ /**
26
+ * 解析 Accept-Encoding,返回该用哪种编码,或 null(不压缩)。
27
+ * 规则按 RFC 9110:显式项优先于 `*`,q=0 表示明确拒绝。
28
+ * @param {string|undefined|null} header
29
+ * @returns {'br'|'gzip'|'deflate'|null}
30
+ */
31
+ export function pickEncoding(header) {
32
+ const raw = String(header || '').trim().toLowerCase()
33
+ if (!raw) return null
34
+ const quality = new Map()
35
+ for (const part of raw.split(',')) {
36
+ const fields = part.split(';')
37
+ const name = fields[0].trim()
38
+ if (!name) continue
39
+ let q = 1
40
+ for (const field of fields.slice(1)) {
41
+ const m = /^\s*q\s*=\s*([0-9.]+)\s*$/.exec(field)
42
+ if (m) {
43
+ const n = Number(m[1])
44
+ q = Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 0
45
+ }
46
+ }
47
+ // 同一个名字重复出现时取第一次(浏览器不会这么发,但代理可能拼出怪头)
48
+ if (!quality.has(name)) quality.set(name, q)
49
+ }
50
+ const score = (enc) => (quality.has(enc) ? quality.get(enc) : quality.has('*') ? quality.get('*') : 0)
51
+ let best = null
52
+ let bestQ = 0
53
+ for (const enc of ORDER) {
54
+ const q = score(enc)
55
+ if (q > bestQ) {
56
+ best = enc
57
+ bestQ = q
58
+ }
59
+ }
60
+ return best
61
+ }
62
+
63
+ /** 这个响应类型值不值得压。JSON / HTML / 文本 / 脚本 / 样式 / SVG 都是文本。 */
64
+ export function isCompressibleType(contentType) {
65
+ const type = String(contentType || '').toLowerCase()
66
+ if (!type) return false
67
+ if (type.startsWith('image/svg')) return true
68
+ return /^text\//.test(type) || /(json|javascript|ecmascript|xml|wasm)/.test(type)
69
+ }
70
+
71
+ /**
72
+ * 按编码压缩。encoding 为 null 时原样返回(调用方据此决定是否加 content-encoding)。
73
+ * brotli 用质量 5:这台机器上 1MB JSON 约 12ms,质量 9 要 30ms+,体积只差几个百分点,
74
+ * 交互式页面等不起。
75
+ * @param {Buffer|string} body
76
+ * @param {'br'|'gzip'|'deflate'|null} encoding
77
+ * @returns {Promise<Buffer>}
78
+ */
79
+ export async function compressBuffer(body, encoding) {
80
+ const buffer = Buffer.isBuffer(body) ? body : Buffer.from(String(body), 'utf8')
81
+ if (encoding === 'br') return brotli(buffer, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 5 } })
82
+ if (encoding === 'gzip') return gzipAsync(buffer, { level: 6 })
83
+ if (encoding === 'deflate') return deflateAsync(buffer, { level: 6 })
84
+ return buffer
85
+ }
86
+
87
+ /** 把已有 Vary 头和 accept-encoding 合并,不重复、不覆盖别人写的 Origin。 */
88
+ export function mergeVary(existing, extra = 'accept-encoding') {
89
+ const set = new Set(
90
+ String(existing || '')
91
+ .split(',')
92
+ .map((s) => s.trim())
93
+ .filter(Boolean),
94
+ )
95
+ set.add(extra)
96
+ return [...set].join(', ')
97
+ }