dsh-sixlayer-memory 0.0.0-stage → 2.0.3
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/CHANGELOG.md +123 -0
- package/README.md +292 -3
- package/catalog/.index.json +111704 -0
- package/catalog/parts.json +8808 -0
- package/cordis.patch.yml +8 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +51 -0
- package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
- package/icon.svg +8 -0
- package/lib/client.js +1209 -0
- package/lib/index.js +741 -0
- package/lib/memory/affect-alert.js +60 -0
- package/lib/memory/affect-events.js +201 -0
- package/lib/memory/affect-report.js +61 -0
- package/lib/memory/api.js +194 -0
- package/lib/memory/crypto.js +68 -0
- package/lib/memory/detail.js +43 -0
- package/lib/memory/embed.js +394 -0
- package/lib/memory/emotion.js +99 -0
- package/lib/memory/explain.js +207 -0
- package/lib/memory/importer.js +215 -0
- package/lib/memory/inject.js +193 -0
- package/lib/memory/ledger.js +101 -0
- package/lib/memory/lifecycle.js +491 -0
- package/lib/memory/notify.js +164 -0
- package/lib/memory/policy.js +182 -0
- package/lib/memory/qq-official.js +196 -0
- package/lib/memory/qq.js +326 -0
- package/lib/memory/recorder.js +241 -0
- package/lib/memory/redact.js +120 -0
- package/lib/memory/scanners.js +142 -0
- package/lib/memory/schema.js +205 -0
- package/lib/memory/service-plugin.js +69 -0
- package/lib/memory/service.js +123 -0
- package/lib/memory/shadow.js +133 -0
- package/lib/memory/store.js +1138 -0
- package/lib/memory/timeline.js +74 -0
- package/lib/memory/tokenize.js +66 -0
- package/lib/memory/tools.js +1371 -0
- package/lib/memory/util.js +129 -0
- package/lib/parts/index.js +154 -0
- package/lib/parts/installer.js +294 -0
- package/lib/parts/jobs.js +91 -0
- package/lib/parts/library.js +91 -0
- package/lib/probe-plugin.js +38 -0
- package/lib/voice/board-asr.js +31 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +114 -3
- package/tools/backfill-affect.mjs +82 -0
- package/tools/eval.mjs +88 -0
- package/tools/p1.mjs +108 -0
- package/tools/p10.mjs +36 -0
- package/tools/p11.mjs +51 -0
- package/tools/p12.mjs +53 -0
- package/tools/p13.mjs +65 -0
- package/tools/p14.mjs +66 -0
- package/tools/p15.mjs +43 -0
- package/tools/p16.mjs +42 -0
- package/tools/p17.mjs +29 -0
- package/tools/p18.mjs +48 -0
- package/tools/p19.mjs +50 -0
- package/tools/p2.mjs +59 -0
- package/tools/p20.mjs +54 -0
- package/tools/p21.mjs +42 -0
- package/tools/p22.mjs +32 -0
- package/tools/p23.mjs +43 -0
- package/tools/p24.mjs +40 -0
- package/tools/p25.mjs +151 -0
- package/tools/p26.mjs +113 -0
- package/tools/p27.mjs +89 -0
- package/tools/p28.mjs +60 -0
- package/tools/p3.mjs +54 -0
- package/tools/p4.mjs +73 -0
- package/tools/p5.mjs +117 -0
- package/tools/p6.mjs +122 -0
- package/tools/p8.mjs +50 -0
- package/tools/p9.mjs +35 -0
- package/tools/phase2.mjs +159 -0
- package/tools/preflight.mjs +320 -0
- package/tools/push-via-api.mjs +187 -0
- package/tools/quarterly.mjs +129 -0
- package/tools/refresh-catalog.mjs +60 -0
- package/tools/register-bundle.mjs +38 -0
- package/tools/review.mjs +156 -0
- package/tools/selfcheck.mjs +80 -0
- package/tools/smoke.mjs +112 -0
- package/tools/testset-v1.json +70 -0
- package/tools/validate-tools.mjs +150 -0
- package/tools/verify-all.mjs +39 -0
- package/tools/write-chain.mjs +139 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* affect-alert.js — 情绪提醒(三期)。
|
|
3
|
+
*
|
|
4
|
+
* 两种提醒:
|
|
5
|
+
* 1. 注入提示:最近 N 小时负面/紧急偏多时,注入一行「情绪提示」,影响 agent 语气
|
|
6
|
+
* 2. 主动通知:同一次尖峰只通知一次(默认 6 小时冷却),走现有邮件/飞书通道
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const NEGATIVE = ['negative', 'urgent']
|
|
10
|
+
|
|
11
|
+
export function affectSpike(store, { hours = 3, threshold = 2 } = {}) {
|
|
12
|
+
const since = new Date(Date.now() - Number(hours) * 3600 * 1000).toISOString()
|
|
13
|
+
const row = store.db
|
|
14
|
+
.prepare("SELECT COUNT(*) AS n FROM affect_events WHERE occurred_at >= ? AND label IN ('negative','urgent')")
|
|
15
|
+
.get(since)
|
|
16
|
+
return {
|
|
17
|
+
spike: Number(row?.n ?? 0) >= Number(threshold),
|
|
18
|
+
count: Number(row?.n ?? 0),
|
|
19
|
+
hours: Number(hours),
|
|
20
|
+
threshold: Number(threshold),
|
|
21
|
+
since,
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 注入用的一行提示;没有尖峰返回空串。 */
|
|
26
|
+
export function affectHint(store, options = {}) {
|
|
27
|
+
try {
|
|
28
|
+
const s = affectSpike(store, options)
|
|
29
|
+
if (!s.spike) return ''
|
|
30
|
+
return `> 情绪提示:近 ${s.hours} 小时负面/紧急消息 ${s.count} 条。先安抚再解决,语气放慢,不追问细节。`
|
|
31
|
+
} catch {
|
|
32
|
+
return ''
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 主动通知:尖峰时发一封邮件/飞书(同一尖峰冷却默认 6 小时)。
|
|
38
|
+
* @returns {Promise<{sent: boolean, reason?: string, channel?: string}>}
|
|
39
|
+
*/
|
|
40
|
+
export async function notifyAffectSpike({ store, notify, options = {}, cooldownMs = 6 * 3600 * 1000 } = {}) {
|
|
41
|
+
const s = affectSpike(store, options)
|
|
42
|
+
if (!s.spike) return { sent: false, reason: 'no-spike' }
|
|
43
|
+
if (!notify) return { sent: false, reason: 'notify-unavailable' }
|
|
44
|
+
|
|
45
|
+
const last = store.getMeta('affect_last_notify') ?? ''
|
|
46
|
+
if (last && Date.now() - Number(last) < cooldownMs) return { sent: false, reason: 'cooldown' }
|
|
47
|
+
|
|
48
|
+
const text = [
|
|
49
|
+
`近 ${s.hours} 小时检测到负面/紧急消息 ${s.count} 条(阈值 ${s.threshold})。`,
|
|
50
|
+
'',
|
|
51
|
+
'可以去工作台 → 观测 → 今日情绪事件查看明细。',
|
|
52
|
+
].join('\n')
|
|
53
|
+
try {
|
|
54
|
+
await notify({ subject: '情绪提醒:最近负面偏多', text })
|
|
55
|
+
store.setMeta('affect_last_notify', String(Date.now()))
|
|
56
|
+
return { sent: true, channel: 'notify' }
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return { sent: false, reason: error?.message ?? String(error) }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* affect-events.js — 情绪事件采集与分析(一期:只采 QQ)。
|
|
3
|
+
*
|
|
4
|
+
* 数据源:DSH 会话日志
|
|
5
|
+
* ~/.dsh/sessions/--…-dsh-qqbot-workspace--/session-<id>/session.v4.jsonl.zstd
|
|
6
|
+
* 文件是多帧 zstd(追加写),需要逐帧解压。
|
|
7
|
+
*
|
|
8
|
+
* 口径:
|
|
9
|
+
* - 只取 user/message(用户说的话)
|
|
10
|
+
* - 只存 ≤80 字脱敏摘要,不存全文
|
|
11
|
+
* - 按 (session_id, excerpt_hash, occurred_at) 去重
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import os from 'node:os'
|
|
16
|
+
import zlib from 'node:zlib'
|
|
17
|
+
import { analyzeAffect } from './emotion.js'
|
|
18
|
+
import { redact, brief } from './redact.js'
|
|
19
|
+
import { sha256, nowIso } from './util.js'
|
|
20
|
+
|
|
21
|
+
const QQ_WORKSPACE_MARK = 'dsh-qqbot-workspace'
|
|
22
|
+
const MAGIC = [0x28, 0xb5, 0x2f, 0xfd]
|
|
23
|
+
|
|
24
|
+
/** 多帧 zstd:按魔数切帧,逐帧解压。 */
|
|
25
|
+
export function decodeZstdFrames(buffer) {
|
|
26
|
+
const starts = []
|
|
27
|
+
for (let i = 0; i + 4 <= buffer.length; i += 1) {
|
|
28
|
+
if (buffer[i] === MAGIC[0] && buffer[i + 1] === MAGIC[1] && buffer[i + 2] === MAGIC[2] && buffer[i + 3] === MAGIC[3]) {
|
|
29
|
+
starts.push(i)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
starts.push(buffer.length)
|
|
33
|
+
let text = ''
|
|
34
|
+
for (let k = 0; k < starts.length - 1; k += 1) {
|
|
35
|
+
try {
|
|
36
|
+
text += zlib.zstdDecompressSync(buffer.subarray(starts[k], starts[k + 1])).toString('utf8')
|
|
37
|
+
} catch {
|
|
38
|
+
/* 误命中或坏帧,跳过 */
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return text
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 从会话日志文本里抽出用户消息。 */
|
|
45
|
+
export function extractUserMessages(text) {
|
|
46
|
+
const out = []
|
|
47
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
48
|
+
if (!line.trim()) continue
|
|
49
|
+
let event
|
|
50
|
+
try {
|
|
51
|
+
event = JSON.parse(line)
|
|
52
|
+
} catch {
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
if (event.type !== 'user/message') continue
|
|
56
|
+
// 只收真实用户消息:runtime-context / time-context / skill-catalog 都是注入的
|
|
57
|
+
const kind = event.data?.source?.kind
|
|
58
|
+
if (kind !== undefined && kind !== 'user') continue
|
|
59
|
+
const parts = Array.isArray(event.data?.content) ? event.data.content : []
|
|
60
|
+
const body = parts
|
|
61
|
+
.filter((p) => p && p.type === 'text')
|
|
62
|
+
.map((p) => String(p.text ?? ''))
|
|
63
|
+
.join(' ')
|
|
64
|
+
.trim()
|
|
65
|
+
if (!body) continue
|
|
66
|
+
out.push({
|
|
67
|
+
id: event.data?.id ?? null,
|
|
68
|
+
time: event.time ? new Date(Number(event.time)).toISOString() : nowIso(),
|
|
69
|
+
text: body,
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
return out
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 找 QQ 工作区下的会话文件(新→旧)。 */
|
|
76
|
+
export function findQqSessions(sessionsRoot = path.join(os.homedir(), '.dsh', 'sessions')) {
|
|
77
|
+
const out = []
|
|
78
|
+
if (!fs.existsSync(sessionsRoot)) return out
|
|
79
|
+
for (const ws of fs.readdirSync(sessionsRoot, { withFileTypes: true })) {
|
|
80
|
+
if (!ws.isDirectory() || !ws.name.includes(QQ_WORKSPACE_MARK)) continue
|
|
81
|
+
const wsDir = path.join(sessionsRoot, ws.name)
|
|
82
|
+
for (const s of fs.readdirSync(wsDir, { withFileTypes: true })) {
|
|
83
|
+
if (!s.isDirectory()) continue
|
|
84
|
+
const file = path.join(wsDir, s.name, 'session.v4.jsonl.zstd')
|
|
85
|
+
if (!fs.existsSync(file)) continue
|
|
86
|
+
out.push({ sessionId: s.name, file, mtime: fs.statSync(file).mtimeMs })
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return out.sort((a, b) => b.mtime - a.mtime)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 采集:解析最近 limit 个 QQ 会话,写入 affect_events。
|
|
94
|
+
* @returns {{files: number, scanned: number, added: number, skipped: number, labels: object}}
|
|
95
|
+
*/
|
|
96
|
+
export function ingestQqSessions({ store, sessionsRoot, limit = 20, source = 'qq' }) {
|
|
97
|
+
const files = findQqSessions(sessionsRoot).slice(0, Math.max(1, Number(limit) || 20))
|
|
98
|
+
const insert = store.db.prepare(
|
|
99
|
+
`INSERT OR IGNORE INTO affect_events
|
|
100
|
+
(event_id, session_id, source, occurred_at, label, valence, arousal, excerpt, excerpt_hash, triggers, created_at)
|
|
101
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
102
|
+
)
|
|
103
|
+
const labels = { neutral: 0, positive: 0, negative: 0, urgent: 0 }
|
|
104
|
+
let scanned = 0
|
|
105
|
+
let added = 0
|
|
106
|
+
let skipped = 0
|
|
107
|
+
|
|
108
|
+
for (const file of files) {
|
|
109
|
+
let text
|
|
110
|
+
try {
|
|
111
|
+
text = decodeZstdFrames(fs.readFileSync(file.file))
|
|
112
|
+
} catch {
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
for (const message of extractUserMessages(text)) {
|
|
116
|
+
scanned += 1
|
|
117
|
+
const safe = redact(message.text).text ?? message.text
|
|
118
|
+
const excerpt = brief(String(safe ?? message.text), 80)
|
|
119
|
+
const hash = sha256(excerpt)
|
|
120
|
+
const affect = analyzeAffect(message.text)
|
|
121
|
+
const eventId = `ae_${hash.slice(0, 16)}_${message.time}`
|
|
122
|
+
const result = insert.run(
|
|
123
|
+
eventId,
|
|
124
|
+
file.sessionId,
|
|
125
|
+
source,
|
|
126
|
+
message.time,
|
|
127
|
+
affect.label,
|
|
128
|
+
affect.valence,
|
|
129
|
+
affect.arousal,
|
|
130
|
+
excerpt,
|
|
131
|
+
hash,
|
|
132
|
+
JSON.stringify(affect.words ?? []),
|
|
133
|
+
nowIso(),
|
|
134
|
+
)
|
|
135
|
+
if (result.changes > 0) {
|
|
136
|
+
added += 1
|
|
137
|
+
labels[affect.label] += 1
|
|
138
|
+
} else {
|
|
139
|
+
skipped += 1
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return { files: files.length, scanned, added, skipped, labels }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const RANGE_DAYS = { day: 1, week: 7, month: 30 }
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 分析:区间内的情绪分布、负面占比、触发词、时段分布。
|
|
151
|
+
*/
|
|
152
|
+
export function affectReport({ store, range = 'day' }) {
|
|
153
|
+
const days = RANGE_DAYS[range] ?? 1
|
|
154
|
+
const since = new Date(Date.now() - days * 24 * 3600 * 1000).toISOString()
|
|
155
|
+
|
|
156
|
+
const byLabel = Object.fromEntries(
|
|
157
|
+
store.db
|
|
158
|
+
.prepare('SELECT label, COUNT(*) AS n FROM affect_events WHERE occurred_at >= ? GROUP BY label')
|
|
159
|
+
.all(since)
|
|
160
|
+
.map((r) => [r.label, r.n]),
|
|
161
|
+
)
|
|
162
|
+
const total = Object.values(byLabel).reduce((a, b) => a + b, 0)
|
|
163
|
+
const negative = (byLabel.negative ?? 0) + (byLabel.urgent ?? 0)
|
|
164
|
+
|
|
165
|
+
const triggerRows = store.db
|
|
166
|
+
.prepare('SELECT triggers FROM affect_events WHERE occurred_at >= ?')
|
|
167
|
+
.all(since)
|
|
168
|
+
const triggerSum = new Map()
|
|
169
|
+
for (const row of triggerRows) {
|
|
170
|
+
let words = []
|
|
171
|
+
try {
|
|
172
|
+
words = JSON.parse(row.triggers || '[]')
|
|
173
|
+
} catch {
|
|
174
|
+
words = []
|
|
175
|
+
}
|
|
176
|
+
if (!Array.isArray(words)) continue
|
|
177
|
+
for (const word of words) {
|
|
178
|
+
if (!word) continue
|
|
179
|
+
triggerSum.set(word, (triggerSum.get(word) ?? 0) + 1)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const topTriggers = [...triggerSum.entries()]
|
|
183
|
+
.sort((a, b) => b[1] - a[1])
|
|
184
|
+
.slice(0, 8)
|
|
185
|
+
.map(([word, n]) => ({ word, n }))
|
|
186
|
+
|
|
187
|
+
const byHour = store.db
|
|
188
|
+
.prepare("SELECT substr(occurred_at, 12, 2) AS hour, COUNT(*) AS n FROM affect_events WHERE occurred_at >= ? GROUP BY hour ORDER BY hour")
|
|
189
|
+
.all(since)
|
|
190
|
+
.map((r) => ({ hour: r.hour, n: r.n }))
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
range,
|
|
194
|
+
since,
|
|
195
|
+
total,
|
|
196
|
+
byLabel,
|
|
197
|
+
negativeRatio: total ? Math.round((negative / total) * 100) / 100 : 0,
|
|
198
|
+
topTriggers,
|
|
199
|
+
byHour,
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* affect-report.js — 情绪日报/周报(二期)。
|
|
3
|
+
*
|
|
4
|
+
* 输入:affectReport() 的聚合结果
|
|
5
|
+
* 输出:Markdown 报告文本 + 落盘文件(dataDir/reports/affect/)
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { affectReport } from './affect-events.js'
|
|
10
|
+
|
|
11
|
+
const LABEL_CN = { neutral: '中性', positive: '正面', negative: '负面', urgent: '紧急' }
|
|
12
|
+
|
|
13
|
+
export function buildAffectReportText(report, { title = null } = {}) {
|
|
14
|
+
const labels = report.byLabel ?? {}
|
|
15
|
+
const total = report.total ?? 0
|
|
16
|
+
const lines = []
|
|
17
|
+
lines.push(`# ${title ?? (report.range === 'week' ? '情绪周报' : '情绪日报')}`)
|
|
18
|
+
lines.push('')
|
|
19
|
+
lines.push(`- 区间:${report.range}(自 ${String(report.since).slice(0, 10)})`)
|
|
20
|
+
lines.push(`- 事件:${total} 条`)
|
|
21
|
+
lines.push(`- 分布:${Object.keys(LABEL_CN).map((k) => `${LABEL_CN[k]} ${labels[k] ?? 0}`).join(' · ')}`)
|
|
22
|
+
lines.push(`- 负面占比:${Math.round((report.negativeRatio ?? 0) * 100)}%`)
|
|
23
|
+
lines.push('')
|
|
24
|
+
|
|
25
|
+
if (report.topTriggers?.length) {
|
|
26
|
+
lines.push('## 高频触发词')
|
|
27
|
+
for (const item of report.topTriggers) lines.push(`- ${item.word} × ${item.n}`)
|
|
28
|
+
lines.push('')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (report.byHour?.length) {
|
|
32
|
+
lines.push('## 时段分布(UTC)')
|
|
33
|
+
const max = Math.max(...report.byHour.map((x) => x.n), 1)
|
|
34
|
+
for (const item of report.byHour) {
|
|
35
|
+
const bar = '█'.repeat(Math.max(1, Math.round((item.n / max) * 20)))
|
|
36
|
+
lines.push(`- ${item.hour}时 ${bar} ${item.n}`)
|
|
37
|
+
}
|
|
38
|
+
lines.push('')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (total === 0) lines.push('> 本期没有采集到情绪事件。')
|
|
42
|
+
else if ((report.negativeRatio ?? 0) >= 0.5) lines.push('> 负面占比偏高,建议回看本期对话的触发点。')
|
|
43
|
+
else lines.push('> 整体平稳。')
|
|
44
|
+
|
|
45
|
+
return lines.join('\n')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 生成并落盘报告。
|
|
50
|
+
* @returns {{path: string, text: string, report: object}}
|
|
51
|
+
*/
|
|
52
|
+
export function saveAffectReport({ store, dataDir, range = 'day' }) {
|
|
53
|
+
const report = affectReport({ store, range })
|
|
54
|
+
const text = buildAffectReportText(report)
|
|
55
|
+
const dir = path.join(dataDir, 'reports', 'affect')
|
|
56
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
57
|
+
const day = new Date().toISOString().slice(0, 10)
|
|
58
|
+
const file = path.join(dir, `${day}-${range}.md`)
|
|
59
|
+
fs.writeFileSync(file, text + '\n', 'utf8')
|
|
60
|
+
return { path: file, text, report }
|
|
61
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* api.js — 把记忆暴露成 HTTP API(只读优先)。
|
|
3
|
+
*
|
|
4
|
+
* 用途:让「不在 DSH 进程里」的程序(QQ 机器人、脚本、云函数)能调记忆。
|
|
5
|
+
* 边界:
|
|
6
|
+
* - 默认只读:status / recall / read
|
|
7
|
+
* - 写入必须显式开 allowWrite,且仍然只读 S 级:S 级永不外发
|
|
8
|
+
* - token 走 Authorization: Bearer 或 x-api-token
|
|
9
|
+
* - 每个 token 每分钟 120 次
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import http from 'node:http'
|
|
14
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
15
|
+
|
|
16
|
+
const TOKEN_FILE = 'meta/api-token.txt'
|
|
17
|
+
const RATE_LIMIT = 120
|
|
18
|
+
const RATE_WINDOW_MS = 60_000
|
|
19
|
+
|
|
20
|
+
function safeEqual(a, b) {
|
|
21
|
+
const left = Buffer.from(String(a ?? ''))
|
|
22
|
+
const right = Buffer.from(String(b ?? ''))
|
|
23
|
+
if (left.length !== right.length) return false
|
|
24
|
+
return timingSafeEqual(left, right)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 读或生成 API token(落盘,权限尽量收紧)。 */
|
|
28
|
+
export function ensureApiToken({ dataDir, configured }) {
|
|
29
|
+
if (configured) return String(configured)
|
|
30
|
+
const file = path.join(dataDir, TOKEN_FILE)
|
|
31
|
+
try {
|
|
32
|
+
const existing = fs.readFileSync(file, 'utf8').trim()
|
|
33
|
+
if (existing) return existing
|
|
34
|
+
} catch {
|
|
35
|
+
/* 不存在就生成 */
|
|
36
|
+
}
|
|
37
|
+
const token = randomBytes(16).toString('hex')
|
|
38
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
39
|
+
fs.writeFileSync(file, token + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
40
|
+
return token
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 固定端口的 API 服务器(不依赖 DSH webServer 的随机端口)。
|
|
45
|
+
* 返回未 listen 的 Server;调用方负责 `.listen(port, '127.0.0.1')`。
|
|
46
|
+
* 只监听回环地址,外部要用请自己做隧道,避免意外暴露。
|
|
47
|
+
*/
|
|
48
|
+
export function createApiServer({ handler }) {
|
|
49
|
+
return http.createServer(async (req, res) => {
|
|
50
|
+
try {
|
|
51
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
52
|
+
const route = url.pathname
|
|
53
|
+
.replace(/^\/+/, '')
|
|
54
|
+
.replace(/^memory-core\/api\//, '')
|
|
55
|
+
.replace(/^api\//, '')
|
|
56
|
+
let body = ''
|
|
57
|
+
for await (const chunk of req) body += chunk
|
|
58
|
+
let parsed = {}
|
|
59
|
+
try {
|
|
60
|
+
parsed = body ? JSON.parse(body) : {}
|
|
61
|
+
} catch {
|
|
62
|
+
parsed = {}
|
|
63
|
+
}
|
|
64
|
+
const result = await handler({ path: route, method: req.method ?? 'POST', headers: req.headers ?? {}, body: parsed })
|
|
65
|
+
res.statusCode = result.status
|
|
66
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
67
|
+
res.end(JSON.stringify(result.json))
|
|
68
|
+
} catch (error) {
|
|
69
|
+
res.statusCode = 500
|
|
70
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
71
|
+
res.end(JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function extractToken(headers) {
|
|
77
|
+
const auth = headers?.authorization ?? headers?.Authorization
|
|
78
|
+
if (typeof auth === 'string' && auth.toLowerCase().startsWith('bearer ')) return auth.slice(7).trim()
|
|
79
|
+
const direct = headers?.['x-api-token'] ?? headers?.['X-Api-Token']
|
|
80
|
+
return typeof direct === 'string' ? direct.trim() : ''
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {{store: any, token: string, allowWrite?: boolean}} options
|
|
85
|
+
* @returns {(req: {path: string, method: string, headers: object, body: any}) => Promise<{status: number, json: any}>}
|
|
86
|
+
*/
|
|
87
|
+
export function createApiHandler({ store, token, allowWrite = false }) {
|
|
88
|
+
let windowStart = Date.now()
|
|
89
|
+
let used = 0
|
|
90
|
+
|
|
91
|
+
return async function handle(req) {
|
|
92
|
+
const now = Date.now()
|
|
93
|
+
if (now - windowStart > RATE_WINDOW_MS) {
|
|
94
|
+
windowStart = now
|
|
95
|
+
used = 0
|
|
96
|
+
}
|
|
97
|
+
used += 1
|
|
98
|
+
if (used > RATE_LIMIT) {
|
|
99
|
+
return { status: 429, json: { ok: false, error: 'rate_limited' } }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (!safeEqual(extractToken(req.headers), token)) {
|
|
103
|
+
return { status: 401, json: { ok: false, error: 'unauthorized' } }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const route = String(req.path ?? '').replace(/^\/+/, '')
|
|
107
|
+
const body = req.body && typeof req.body === 'object' ? req.body : {}
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
if (route === 'status') {
|
|
111
|
+
const s = store.stats()
|
|
112
|
+
return {
|
|
113
|
+
status: 200,
|
|
114
|
+
json: {
|
|
115
|
+
ok: true,
|
|
116
|
+
value: {
|
|
117
|
+
records: s.records,
|
|
118
|
+
active: s.active,
|
|
119
|
+
pending: s.pending,
|
|
120
|
+
sLevel: s.sLevel,
|
|
121
|
+
schemaVersion: s.schemaVersion,
|
|
122
|
+
auditOk: Boolean(s.audit?.ok),
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (route === 'recall') {
|
|
129
|
+
const query = String(body.query ?? '').trim()
|
|
130
|
+
if (!query) return { status: 400, json: { ok: false, error: 'query_required' } }
|
|
131
|
+
const topK = Math.min(Math.max(Number(body.topK ?? 5), 1), 20)
|
|
132
|
+
const hits = store.search({ query, topK })
|
|
133
|
+
return {
|
|
134
|
+
status: 200,
|
|
135
|
+
json: {
|
|
136
|
+
ok: true,
|
|
137
|
+
value: {
|
|
138
|
+
items: hits.map((h) => ({
|
|
139
|
+
record_id: h.record_id,
|
|
140
|
+
layer: h.layer,
|
|
141
|
+
summary: h.summary,
|
|
142
|
+
score: h.score,
|
|
143
|
+
})),
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (route === 'read') {
|
|
150
|
+
const record = store.read(String(body.record_id ?? ''), { includeSensitive: false })
|
|
151
|
+
if (!record) return { status: 404, json: { ok: false, error: 'not_found' } }
|
|
152
|
+
if (record.denied || record.sad_level === 'S') {
|
|
153
|
+
return { status: 403, json: { ok: false, error: 's_level_denied' } }
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
status: 200,
|
|
157
|
+
json: {
|
|
158
|
+
ok: true,
|
|
159
|
+
value: {
|
|
160
|
+
record_id: record.record_id,
|
|
161
|
+
layer: record.layer,
|
|
162
|
+
sad_level: record.sad_level,
|
|
163
|
+
trust_level: record.trust_level,
|
|
164
|
+
summary: record.summary,
|
|
165
|
+
content: record.content,
|
|
166
|
+
created_at: record.created_at,
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (route === 'remember') {
|
|
173
|
+
if (!allowWrite) return { status: 403, json: { ok: false, error: 'write_disabled' } }
|
|
174
|
+
const content = String(body.content ?? '').trim()
|
|
175
|
+
if (!content) return { status: 400, json: { ok: false, error: 'content_required' } }
|
|
176
|
+
const result = store.write({
|
|
177
|
+
content,
|
|
178
|
+
layer: body.layer ?? 'L2',
|
|
179
|
+
sourceChannel: body.sourceChannel ?? 'api',
|
|
180
|
+
trustLevel: 'unverified',
|
|
181
|
+
explicit: true,
|
|
182
|
+
})
|
|
183
|
+
return {
|
|
184
|
+
status: 200,
|
|
185
|
+
json: { ok: true, value: { record_id: result.record_id, status: result.status, dedup: Boolean(result.dedup) } },
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return { status: 404, json: { ok: false, error: 'unknown_route' } }
|
|
190
|
+
} catch (error) {
|
|
191
|
+
return { status: 500, json: { ok: false, error: String(error?.message ?? error) } }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* crypto.js — 静态数据加密(四期核心项,默认关闭)。
|
|
3
|
+
*
|
|
4
|
+
* 设计:
|
|
5
|
+
* - AES-256-GCM,每条记录独立 nonce
|
|
6
|
+
* - 密钥:dataDir/meta/enc.key(32 字节 hex,仅当前用户可读)
|
|
7
|
+
* - 密文格式:enc:v1:<iv_b64>:<tag_b64>:<ct_b64>
|
|
8
|
+
* - 只加密 records.content(摘要/标签保持明文,检索依赖它们)
|
|
9
|
+
* - 透明解密:store.read 遇到密文自动解;无密钥时返回明确错误,不崩
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import crypto from 'node:crypto'
|
|
14
|
+
|
|
15
|
+
const PREFIX = 'enc:v1:'
|
|
16
|
+
const KEY_FILE = 'enc.key'
|
|
17
|
+
|
|
18
|
+
export function keyPath(dataDir) {
|
|
19
|
+
return path.join(dataDir, 'meta', KEY_FILE)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function cryptoStatus(dataDir) {
|
|
23
|
+
const file = keyPath(dataDir)
|
|
24
|
+
return { enabled: fs.existsSync(file), keyPath: file }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function loadKey(dataDir) {
|
|
28
|
+
const file = keyPath(dataDir)
|
|
29
|
+
if (!fs.existsSync(file)) return null
|
|
30
|
+
const hex = fs.readFileSync(file, 'utf8').trim()
|
|
31
|
+
if (!/^[0-9a-f]{64}$/i.test(hex)) throw new Error('enc.key 格式错误:应为 64 位 hex')
|
|
32
|
+
return Buffer.from(hex, 'hex')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function ensureKey(dataDir) {
|
|
36
|
+
const existing = loadKey(dataDir)
|
|
37
|
+
if (existing) return { created: false, key: existing }
|
|
38
|
+
const key = crypto.randomBytes(32)
|
|
39
|
+
fs.mkdirSync(path.dirname(keyPath(dataDir)), { recursive: true })
|
|
40
|
+
fs.writeFileSync(keyPath(dataDir), key.toString('hex') + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
41
|
+
return { created: true, key }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isEncrypted(text) {
|
|
45
|
+
return typeof text === 'string' && text.startsWith(PREFIX)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function encryptText(text, key) {
|
|
49
|
+
if (isEncrypted(text)) return text
|
|
50
|
+
const iv = crypto.randomBytes(12)
|
|
51
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
|
|
52
|
+
const ct = Buffer.concat([cipher.update(String(text ?? ''), 'utf8'), cipher.final()])
|
|
53
|
+
const tag = cipher.getAuthTag()
|
|
54
|
+
return PREFIX + [iv.toString('base64'), tag.toString('base64'), ct.toString('base64')].join(':')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function decryptText(payload, key) {
|
|
58
|
+
if (!isEncrypted(payload)) return payload
|
|
59
|
+
if (!key) throw new Error('缺少密钥(meta/enc.key)')
|
|
60
|
+
const parts = payload.split(':')
|
|
61
|
+
if (parts.length !== 5) throw new Error('密文格式损坏')
|
|
62
|
+
const iv = Buffer.from(parts[2], 'base64')
|
|
63
|
+
const tag = Buffer.from(parts[3], 'base64')
|
|
64
|
+
const ct = Buffer.from(parts[4], 'base64')
|
|
65
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)
|
|
66
|
+
decipher.setAuthTag(tag)
|
|
67
|
+
return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8')
|
|
68
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* detail.js — 「这一条记忆的全部」:正文 + 标签 + 相关记忆 + 人话标题。
|
|
3
|
+
*
|
|
4
|
+
* 面板里点一个圆点,看到的就是这个函数的返回值。
|
|
5
|
+
* 单独拆出来是为了能离线回归(tools/p28.mjs),不用起宿主。
|
|
6
|
+
*/
|
|
7
|
+
import { explainRecord } from './explain.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {{store:any, recordId:string, includeSensitive?:boolean}} input
|
|
11
|
+
* @returns {object|null}
|
|
12
|
+
*/
|
|
13
|
+
export function readDetail({ store, recordId, includeSensitive = false } = {}) {
|
|
14
|
+
const id = String(recordId ?? '')
|
|
15
|
+
if (!id) return null
|
|
16
|
+
const row = store.read(id, { includeSensitive })
|
|
17
|
+
if (!row) return null
|
|
18
|
+
|
|
19
|
+
let tags = []
|
|
20
|
+
try {
|
|
21
|
+
tags = store.db
|
|
22
|
+
.prepare('SELECT tag FROM tags WHERE record_id = ?')
|
|
23
|
+
.all(id)
|
|
24
|
+
.map((t) => t.tag)
|
|
25
|
+
} catch {
|
|
26
|
+
/* 标签读不到就给空数组 */
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let neighbors = []
|
|
30
|
+
try {
|
|
31
|
+
const assoc = store.associate({ recordId: id, topK: 5 })
|
|
32
|
+
neighbors = (assoc?.items ?? []).map((item) => ({
|
|
33
|
+
record_id: item.record_id,
|
|
34
|
+
title: explainRecord({ summary: item.summary }).title,
|
|
35
|
+
reasons: item.reasons ?? [],
|
|
36
|
+
weight: item.weight ?? null,
|
|
37
|
+
}))
|
|
38
|
+
} catch {
|
|
39
|
+
/* 联想失败不影响详情 */
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return { ...row, tags, neighbors, display: explainRecord(row) }
|
|
43
|
+
}
|