dsh-sixlayer-memory 0.0.0-stage → 2.0.2

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 (91) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +286 -3
  3. package/catalog/.index.json +111704 -0
  4. package/catalog/parts.json +8808 -0
  5. package/cordis.patch.yml +8 -0
  6. package/docs/DETAIL.md +1 -0
  7. package/docs/DETAIL.zh.md +1 -0
  8. package/docs/preview.svg +51 -0
  9. 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
  10. package/icon.svg +8 -0
  11. package/lib/client.js +1209 -0
  12. package/lib/index.js +741 -0
  13. package/lib/memory/affect-alert.js +60 -0
  14. package/lib/memory/affect-events.js +201 -0
  15. package/lib/memory/affect-report.js +61 -0
  16. package/lib/memory/api.js +194 -0
  17. package/lib/memory/crypto.js +68 -0
  18. package/lib/memory/detail.js +43 -0
  19. package/lib/memory/embed.js +394 -0
  20. package/lib/memory/emotion.js +99 -0
  21. package/lib/memory/explain.js +207 -0
  22. package/lib/memory/importer.js +215 -0
  23. package/lib/memory/inject.js +193 -0
  24. package/lib/memory/ledger.js +101 -0
  25. package/lib/memory/lifecycle.js +491 -0
  26. package/lib/memory/notify.js +164 -0
  27. package/lib/memory/policy.js +182 -0
  28. package/lib/memory/qq-official.js +196 -0
  29. package/lib/memory/qq.js +326 -0
  30. package/lib/memory/recorder.js +241 -0
  31. package/lib/memory/redact.js +120 -0
  32. package/lib/memory/scanners.js +142 -0
  33. package/lib/memory/schema.js +205 -0
  34. package/lib/memory/service-plugin.js +69 -0
  35. package/lib/memory/service.js +123 -0
  36. package/lib/memory/shadow.js +133 -0
  37. package/lib/memory/store.js +1138 -0
  38. package/lib/memory/timeline.js +74 -0
  39. package/lib/memory/tokenize.js +66 -0
  40. package/lib/memory/tools.js +1371 -0
  41. package/lib/memory/util.js +129 -0
  42. package/lib/parts/index.js +154 -0
  43. package/lib/parts/installer.js +294 -0
  44. package/lib/parts/jobs.js +91 -0
  45. package/lib/parts/library.js +91 -0
  46. package/lib/probe-plugin.js +38 -0
  47. package/lib/voice/board-asr.js +31 -0
  48. package/locale/en.json +7 -0
  49. package/locale/zh.json +7 -0
  50. package/package.json +114 -3
  51. package/tools/backfill-affect.mjs +82 -0
  52. package/tools/eval.mjs +88 -0
  53. package/tools/p1.mjs +108 -0
  54. package/tools/p10.mjs +36 -0
  55. package/tools/p11.mjs +51 -0
  56. package/tools/p12.mjs +53 -0
  57. package/tools/p13.mjs +65 -0
  58. package/tools/p14.mjs +66 -0
  59. package/tools/p15.mjs +43 -0
  60. package/tools/p16.mjs +42 -0
  61. package/tools/p17.mjs +29 -0
  62. package/tools/p18.mjs +48 -0
  63. package/tools/p19.mjs +50 -0
  64. package/tools/p2.mjs +59 -0
  65. package/tools/p20.mjs +54 -0
  66. package/tools/p21.mjs +42 -0
  67. package/tools/p22.mjs +32 -0
  68. package/tools/p23.mjs +43 -0
  69. package/tools/p24.mjs +40 -0
  70. package/tools/p25.mjs +151 -0
  71. package/tools/p26.mjs +113 -0
  72. package/tools/p27.mjs +89 -0
  73. package/tools/p28.mjs +60 -0
  74. package/tools/p3.mjs +54 -0
  75. package/tools/p4.mjs +73 -0
  76. package/tools/p5.mjs +117 -0
  77. package/tools/p6.mjs +122 -0
  78. package/tools/p8.mjs +50 -0
  79. package/tools/p9.mjs +35 -0
  80. package/tools/phase2.mjs +159 -0
  81. package/tools/preflight.mjs +320 -0
  82. package/tools/quarterly.mjs +129 -0
  83. package/tools/refresh-catalog.mjs +60 -0
  84. package/tools/register-bundle.mjs +38 -0
  85. package/tools/review.mjs +156 -0
  86. package/tools/selfcheck.mjs +80 -0
  87. package/tools/smoke.mjs +112 -0
  88. package/tools/testset-v1.json +70 -0
  89. package/tools/validate-tools.mjs +150 -0
  90. package/tools/verify-all.mjs +39 -0
  91. package/tools/write-chain.mjs +139 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * policy.js — 写入链的判定规则(纯函数,可单独测)。
3
+ *
4
+ * 把这些规则从 store.js 里拆出来,是因为它们会被反复调参:
5
+ * 信任矩阵、投毒特征、沉淀决策、分级、相似/矛盾判定。
6
+ * 规则改了不需要动存储代码,测试也能直接对着这个文件打。
7
+ */
8
+ import { runScanners } from './scanners.js'
9
+
10
+ // ---------- 信任判定 ----------
11
+
12
+ /** 写入通道 → 基础信任级。标签由通道决定,不信任正文自述(方案 §14a)。 */
13
+ const BASE_TRUST = {
14
+ user: 'trusted',
15
+ host: 'trusted',
16
+ legacy_import: 'trusted',
17
+ tool: 'unverified',
18
+ web: 'unverified',
19
+ import: 'unverified',
20
+ mcp: 'unverified',
21
+ unknown: 'unverified',
22
+ }
23
+
24
+ const TRUST_ORDER = ['tainted', 'unverified', 'trusted']
25
+
26
+ /**
27
+ * 通道 × 调用方身份 → 信任级。
28
+ * 身份只用于**下调**:陌生人通过 user 通道说话,不该拿到 trusted。
29
+ */
30
+ export function resolveTrust({ channel = 'unknown', principalId = null } = {}) {
31
+ let trust = BASE_TRUST[channel] ?? 'unverified'
32
+ if (principalId === 'unknown' && trust === 'trusted') trust = 'unverified'
33
+ if (principalId === 'anonymous' && trust === 'trusted') trust = 'unverified'
34
+ return trust
35
+ }
36
+
37
+ /** 从高到低取较低的那个(tainted 最低)。 */
38
+ export function weakerTrust(a, b) {
39
+ return TRUST_ORDER[Math.min(TRUST_ORDER.indexOf(a), TRUST_ORDER.indexOf(b))] ?? 'unverified'
40
+ }
41
+
42
+ // ---------- 投毒扫描(P2:规则已拆到 scanners.js 的 scanner 链) ----------
43
+
44
+ /**
45
+ * 扫描正文。
46
+ * @returns {{flags: string[], injection: string[], sensitive: string[], hits: object[]}}
47
+ */
48
+ export function scan(text) {
49
+ const hits = runScanners(text)
50
+ const injection = hits.filter((h) => h.kind === 'injection').map((h) => h.id)
51
+ const sensitive = hits.filter((h) => h.kind === 'sensitive').map((h) => h.id)
52
+ const flags = []
53
+ if (injection.length) flags.push('injection')
54
+ if (sensitive.length) flags.push('sensitive')
55
+ return { flags, injection, sensitive, hits }
56
+ }
57
+
58
+ // ---------- 沉淀前决策 ----------
59
+
60
+ const SMALL_TALK = /^(?:好的?|嗯+|收到|谢谢|多谢|ok(?:ay)?|thanks?|thx|哈哈+|👍|!|。|\.+)\s*$/i
61
+
62
+ /**
63
+ * 低价值不落库(方案 §14c)。
64
+ * 只对自动采集通道生效 —— 用户自己显式写的东西,再短也要留。
65
+ * @returns {string|null} 命中则返回原因
66
+ */
67
+ export function lowValueReason(text, channel) {
68
+ if (channel === 'user' || channel === 'host') return null
69
+ const s = String(text ?? '').trim()
70
+ if (s.length < 16) return 'too-short'
71
+ if (SMALL_TALK.test(s)) return 'small-talk'
72
+ const hasCjk = /[\u4e00-\u9fff]/.test(s)
73
+ const words = s.split(/\s+/).filter(Boolean)
74
+ if (!hasCjk && words.length < 3) return 'too-few-words'
75
+ return null
76
+ }
77
+
78
+ // ---------- 分级 ----------
79
+
80
+ /**
81
+ * S/A 两级(一期口径:D 级诱饵库在二期才建)。
82
+ * 凭证/隐私一律 S;其余 A。显式传入优先。
83
+ */
84
+ export function classifySAD({ flags, explicit }) {
85
+ if (['S', 'A', 'D'].includes(explicit)) return explicit
86
+ return flags.includes('sensitive') ? 'S' : 'A'
87
+ }
88
+
89
+ // ---------- 相似与矛盾 ----------
90
+
91
+ const OPPOSITE_PAIRS = [
92
+ [/(?:允许|可以|开启|支持|启用)/, /(?:禁止|不可以|关闭|不支持|禁用)/],
93
+ [/(?:是|对|正确|成立)/, /(?:否|不对|错误|不成立)/],
94
+ [/(?:增加|上调|提高)/, /(?:减少|下调|降低)/],
95
+ ]
96
+
97
+ /** bigram 集合的 Jaccard 相似度(0..1),用于判断"是不是在说同一件事"。 */
98
+ export function similarity(a, b) {
99
+ const set = (t) => new Set(tokenizeForCompare(t))
100
+ const A = set(a)
101
+ const B = set(b)
102
+ if (A.size === 0 || B.size === 0) return 0
103
+ let inter = 0
104
+ for (const x of A) if (B.has(x)) inter += 1
105
+ return inter / (A.size + B.size - inter)
106
+ }
107
+
108
+ function tokenizeForCompare(text) {
109
+ const s = String(text ?? '').toLowerCase()
110
+ const out = []
111
+ for (let i = 0; i < s.length - 1; i += 1) {
112
+ const pair = s.slice(i, i + 2)
113
+ if (/[\s,.;:!?,。;:!?、]/.test(pair)) continue
114
+ out.push(pair)
115
+ }
116
+ return out
117
+ }
118
+
119
+ /** 疑似矛盾:说的是同一件事,但结论极性相反。只提示,不裁决(裁决留给人和二期 rerank)。 */
120
+ export function contradictionSuspect(a, b) {
121
+ for (const [pos, neg] of OPPOSITE_PAIRS) {
122
+ const aPos = pos.test(a)
123
+ const aNeg = neg.test(a)
124
+ const bPos = pos.test(b)
125
+ const bNeg = neg.test(b)
126
+ if ((aPos && bNeg) || (aNeg && bPos)) return true
127
+ }
128
+ return false
129
+ }
130
+
131
+ // ---------- 召回时的使用约束 ----------
132
+
133
+ /**
134
+ * 按信任级与 β 给出召回提示(方案 §18)。
135
+ * 返回 null 表示没有附加约束。
136
+ */
137
+ export function usageCaveat({ trustLevel, beta, scored }) {
138
+ if (trustLevel === 'tainted') return '该条已隔离,仅供人工核对,不得引用'
139
+ if (trustLevel === 'unverified') return '来源未验证,仅作线索,不作结论依据'
140
+ if (scored === false || scored === 0) return '未评分,勿作约束性指令'
141
+ if (typeof beta === 'number' && beta < 0.3) return '可信度较低(β<0.3),勿作约束性指令'
142
+ return null
143
+ }
144
+
145
+ // ---------- 修改权分档(协作机制) ----------
146
+
147
+ /**
148
+ * 判定"这个 actor 能不能写这个目标"。
149
+ * 分档来自 luanyujia-workbench:
150
+ * A 共享·宪法 / C 共享·工具 → 只有负责人能改,别人只能提请求
151
+ * B 共享·板与台账 → 只能写自己的行
152
+ * D 自己的专属 → 自己改
153
+ * E 别人的专属 → 一个字都不许写,只能写请求
154
+ *
155
+ * @param {{actor?:string, target?:string, kind?:'rule'|'tool'|'board'|'own', ruleOwner?:string|null, rowOwner?:string|null}} input
156
+ */
157
+ export function canWrite({ actor, target, kind = 'own', ruleOwner = null, rowOwner = null } = {}) {
158
+ const a = String(actor ?? '').trim()
159
+ const t = String(target ?? '').trim()
160
+ if (kind === 'rule' || kind === 'tool') {
161
+ const tier = kind === 'rule' ? 'A' : 'C'
162
+ if (ruleOwner && a === ruleOwner) return { tier, allowed: true, reason: '你是该档负责人' }
163
+ return {
164
+ tier,
165
+ allowed: false,
166
+ reason: kind === 'rule' ? '共享宪法只有负责人能改' : '共享工具与运行时只有负责人能改',
167
+ request: '写请求:现象 + 照哪节做 + 做完怎么验 + 回一句',
168
+ }
169
+ }
170
+ if (kind === 'board') {
171
+ if (rowOwner && a === rowOwner) return { tier: 'B', allowed: true, reason: '写自己那些行' }
172
+ return { tier: 'B', allowed: false, reason: '板上只能写自己的行,不许删改别人的行', request: '只加自己那一行' }
173
+ }
174
+ // own:D / E
175
+ if (a && t && a === t) return { tier: 'D', allowed: true, reason: '自己的地盘' }
176
+ return {
177
+ tier: 'E',
178
+ allowed: false,
179
+ reason: '别人的专属地盘,一个字都不许写',
180
+ request: '写请求:现象 + 该谁做 + 怎么做 + 做完怎么验',
181
+ }
182
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * qq-official.js — QQ 官方机器人(QQ Bot v2)桥。
3
+ *
4
+ * 流程:
5
+ * AppID + AppSecret → access_token(2 小时有效,提前刷新)
6
+ * → GET /gateway 拿 WS 地址
7
+ * → WS:op 10 Hello 后发 op 2 Identify(intents = GROUP_AND_C2C)
8
+ * → 收到 GROUP_AT_MESSAGE_CREATE / C2C_MESSAGE_CREATE
9
+ * → 复用 runMemoryCommand → POST /v2/groups|users/{openid}/messages 回复
10
+ *
11
+ * 安全:AppSecret 只读本地配置文件,不进日志;白名单按 openid 过滤。
12
+ */
13
+ import { runMemoryCommand, parseCommand } from './qq.js'
14
+
15
+ const API_BASE = 'https://api.sgroup.qq.com'
16
+ const SANDBOX_BASE = 'https://sandbox.api.sgroup.qq.com'
17
+ const TOKEN_URL = 'https://bots.qq.com/app/getAppAccessToken'
18
+ export const INTENT_GROUP_AND_C2C = 1 << 25
19
+
20
+ export class QqOfficialBridge {
21
+ constructor({ store, config, log, fetchImpl }) {
22
+ if (!store) throw new Error('QqOfficialBridge: store 必填')
23
+ this.store = store
24
+ this.config = config ?? {}
25
+ this.log = log ?? (() => {})
26
+ this.fetch = fetchImpl ?? globalThis.fetch
27
+ this.accessToken = ''
28
+ this.expiresAt = 0
29
+ this.ws = null
30
+ this.stopped = true
31
+ this.seq = null
32
+ this.heartbeatTimer = null
33
+ this.stats = { connected: false, received: 0, replied: 0, ignored: 0, errors: 0 }
34
+ }
35
+
36
+ get enabled() {
37
+ return this.config.enabled === true && Boolean(this.config.appId) && Boolean(this.config.appSecret)
38
+ }
39
+
40
+ get baseUrl() {
41
+ return this.config.sandbox ? SANDBOX_BASE : API_BASE
42
+ }
43
+
44
+ status() {
45
+ return { ...this.stats, enabled: this.enabled, appId: this.config.appId ?? null, sandbox: Boolean(this.config.sandbox) }
46
+ }
47
+
48
+ async start() {
49
+ if (!this.enabled || !this.stopped) return
50
+ this.stopped = false
51
+ await this._connect()
52
+ }
53
+
54
+ stop() {
55
+ this.stopped = true
56
+ clearInterval(this.heartbeatTimer)
57
+ try {
58
+ this.ws?.close()
59
+ } catch {
60
+ /* 忽略 */
61
+ }
62
+ this.ws = null
63
+ this.stats.connected = false
64
+ }
65
+
66
+ async _ensureToken() {
67
+ if (this.accessToken && Date.now() < this.expiresAt - 60_000) return this.accessToken
68
+ const res = await this.fetch(TOKEN_URL, {
69
+ method: 'POST',
70
+ headers: { 'content-type': 'application/json' },
71
+ body: JSON.stringify({ appId: String(this.config.appId), clientSecret: String(this.config.appSecret) }),
72
+ })
73
+ const json = await res.json()
74
+ if (!json?.access_token) throw new Error('获取 access_token 失败:' + JSON.stringify(json).slice(0, 200))
75
+ this.accessToken = json.access_token
76
+ this.expiresAt = Date.now() + Number(json.expires_in ?? 7200) * 1000
77
+ return this.accessToken
78
+ }
79
+
80
+ async _connect() {
81
+ if (this.stopped) return
82
+ try {
83
+ const token = await this._ensureToken()
84
+ const res = await this.fetch(`${this.baseUrl}/gateway`, { headers: { authorization: 'QQBot ' + token } })
85
+ const json = await res.json()
86
+ if (!json?.url) throw new Error('获取网关失败:' + JSON.stringify(json).slice(0, 200))
87
+ this._openSocket(json.url, token)
88
+ } catch (error) {
89
+ this.stats.errors += 1
90
+ this.log('qq-official: ' + (error?.message ?? String(error)))
91
+ if (!this.stopped) setTimeout(() => this._connect(), 5000)
92
+ }
93
+ }
94
+
95
+ _openSocket(url, token) {
96
+ const ws = new WebSocket(url)
97
+ this.ws = ws
98
+ ws.addEventListener('open', () => {
99
+ this.stats.connected = true
100
+ this.log('qq-official: 已连接网关')
101
+ })
102
+ ws.addEventListener('message', (event) => {
103
+ let payload
104
+ try {
105
+ payload = JSON.parse(String(event.data))
106
+ } catch {
107
+ return
108
+ }
109
+ this._onPayload(payload, token)
110
+ })
111
+ ws.addEventListener('close', () => {
112
+ this.stats.connected = false
113
+ clearInterval(this.heartbeatTimer)
114
+ if (!this.stopped) setTimeout(() => this._connect(), 3000)
115
+ })
116
+ ws.addEventListener('error', () => {
117
+ this.stats.errors += 1
118
+ })
119
+ }
120
+
121
+ _send(payload) {
122
+ try {
123
+ this.ws?.send(JSON.stringify(payload))
124
+ } catch {
125
+ /* 忽略 */
126
+ }
127
+ }
128
+
129
+ _onPayload(payload, token) {
130
+ if (payload?.s !== undefined) this.seq = payload.s
131
+ if (payload?.op === 10) {
132
+ this._send({
133
+ op: 2,
134
+ d: { token: 'QQBot ' + token, intents: INTENT_GROUP_AND_C2C, shard: [0, 1] },
135
+ })
136
+ clearInterval(this.heartbeatTimer)
137
+ this.heartbeatTimer = setInterval(() => this._send({ op: 1, d: this.seq }), payload.d?.heartbeat_interval ?? 30000)
138
+ return
139
+ }
140
+ if (payload?.op === 0) {
141
+ this._onDispatch(payload.t, payload.d)
142
+ }
143
+ }
144
+
145
+ _onDispatch(type, data) {
146
+ if (type !== 'GROUP_AT_MESSAGE_CREATE' && type !== 'C2C_MESSAGE_CREATE') return
147
+ this.stats.received += 1
148
+ this._handleMessage(type, data).catch((error) => {
149
+ this.stats.errors += 1
150
+ this.log('qq-official: 处理失败 ' + (error?.message ?? String(error)))
151
+ })
152
+ }
153
+
154
+ async _handleMessage(type, data) {
155
+ const content = String(data?.content ?? '').trim()
156
+ const isGroup = type === 'GROUP_AT_MESSAGE_CREATE'
157
+ const openid = isGroup ? String(data?.group_openid ?? '') : String(data?.author?.user_openid ?? data?.author?.id ?? '')
158
+ if (!openid) {
159
+ this.stats.ignored += 1
160
+ return
161
+ }
162
+ const allowed = (this.config.allowedOpenids ?? []).map(String).filter(Boolean)
163
+ if (allowed.length > 0 && !allowed.includes(openid)) {
164
+ this.stats.ignored += 1
165
+ return
166
+ }
167
+ const parsed = parseCommand(content, this.config.prefix ?? '/')
168
+ if (!parsed) return
169
+ const reply = await runMemoryCommand(this.store, parsed, {
170
+ userId: openid,
171
+ groupId: isGroup ? openid : '',
172
+ isGroup,
173
+ })
174
+ if (!reply) return
175
+ await this._reply(type, data, reply)
176
+ this.stats.replied += 1
177
+ }
178
+
179
+ /** 回复消息(QQ Bot v2 群/单聊接口)。 */
180
+ async _reply(type, data, content) {
181
+ const token = await this._ensureToken()
182
+ const isGroup = type === 'GROUP_AT_MESSAGE_CREATE'
183
+ const url = isGroup
184
+ ? `${this.baseUrl}/v2/groups/${data.group_openid}/messages`
185
+ : `${this.baseUrl}/v2/users/${data.author?.user_openid ?? ''}/messages`
186
+ return this.fetch(url, {
187
+ method: 'POST',
188
+ headers: { authorization: 'QQBot ' + token, 'content-type': 'application/json' },
189
+ body: JSON.stringify({ content, msg_type: 0, msg_id: data.id }),
190
+ })
191
+ }
192
+ }
193
+
194
+ export function createQqOfficialBridge(options) {
195
+ return new QqOfficialBridge(options)
196
+ }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * qq.js — QQ 机器人桥(OneBot v11 WebSocket 客户端)。
3
+ *
4
+ * 为什么是「客户端」而不是「收 webhook」:
5
+ * DSH 的 webServer 端口每次重启会变,让 NapCat 反向 HTTP 指过来很脆弱;
6
+ * 反过来由我们连 NapCat 的 WebSocket 服务端,端口固定、断线可重连。
7
+ *
8
+ * 职责边界:
9
+ * - 只做「IM → 记忆」的消费侧:记 / 搜 / 联想 / 状态 / 最近
10
+ * - 不碰 S 级正文;QQ 写入一律 unverified → 先审后入(闸门公理不变)
11
+ * - 白名单之外的消息直接忽略,不回复、不落库
12
+ */
13
+
14
+ const DEFAULTS = {
15
+ wsUrl: 'ws://127.0.0.1:3001',
16
+ accessToken: '',
17
+ allowedUsers: [],
18
+ allowedGroups: [],
19
+ rateLimitMs: 2000,
20
+ prefix: '/',
21
+ }
22
+
23
+ function nowMs() {
24
+ return Date.now()
25
+ }
26
+
27
+ /** 把 OneBot 消息段数组压成纯文本。 */
28
+ export function segmentsToText(segments) {
29
+ if (!Array.isArray(segments)) return ''
30
+ return segments
31
+ .map((seg) => {
32
+ if (!seg || typeof seg !== 'object') return ''
33
+ if (seg.type === 'text') return String(seg.data?.text ?? '')
34
+ if (seg.type === 'at') return `@${seg.data?.qq ?? ''}`
35
+ if (seg.type === 'image') return '[图片]'
36
+ if (seg.type === 'face') return '[表情]'
37
+ return ''
38
+ })
39
+ .join('')
40
+ .trim()
41
+ }
42
+
43
+ /** 解析命令:返回 { cmd, arg };不是命令返回 null。 */
44
+ export function parseCommand(text, prefix = '/') {
45
+ const body = String(text ?? '').trim()
46
+ if (!body.startsWith(prefix)) return null
47
+ const rest = body.slice(prefix.length).trim()
48
+ if (!rest) return null
49
+ const match = rest.match(/^(\S+)\s*([\s\S]*)$/)
50
+ if (!match) return null
51
+ const raw = match[1].toLowerCase()
52
+ const arg = match[2].trim()
53
+ const alias = {
54
+ 记: 'remember', 记住: 'remember', remember: 'remember', add: 'remember',
55
+ 搜: 'search', 搜索: 'search', search: 'search', find: 'search',
56
+ 联想: 'associate', associate: 'associate', relate: 'associate',
57
+ 状态: 'status', status: 'status', stat: 'status',
58
+ 最近: 'recent', recent: 'recent', latest: 'recent',
59
+ 帮助: 'help', help: 'help', '?': 'help',
60
+ }
61
+ const cmd = alias[raw]
62
+ if (!cmd) return { cmd: 'unknown', arg: rest }
63
+ return { cmd, arg }
64
+ }
65
+
66
+ function oneLine(text, max = 60) {
67
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim()
68
+ return s.length > max ? `${s.slice(0, max)}…` : s
69
+ }
70
+
71
+ export class QqBridge {
72
+ /**
73
+ * @param {{store: any, config?: object, log?: (msg: string) => void}} options
74
+ */
75
+ constructor(options) {
76
+ if (!options?.store) throw new Error('QqBridge: store 必填')
77
+ this.store = options.store
78
+ this.config = { ...DEFAULTS, ...(options.config ?? {}) }
79
+ this.log = options.log ?? (() => {})
80
+ this.ws = null
81
+ this.stopped = true
82
+ this.retry = 0
83
+ this.timer = null
84
+ this.pending = new Map()
85
+ this.lastCmdAt = new Map()
86
+ this.stats = { connected: false, received: 0, replied: 0, ignored: 0, errors: 0 }
87
+ }
88
+
89
+ get enabled() {
90
+ return this.config.enabled !== false && Boolean(this.config.wsUrl)
91
+ }
92
+
93
+ start() {
94
+ if (!this.enabled || !this.stopped) return
95
+ this.stopped = false
96
+ this._connect()
97
+ }
98
+
99
+ stop() {
100
+ this.stopped = true
101
+ if (this.timer) {
102
+ clearTimeout(this.timer)
103
+ this.timer = null
104
+ }
105
+ try {
106
+ this.ws?.close()
107
+ } catch {
108
+ /* 忽略 */
109
+ }
110
+ this.ws = null
111
+ this.stats.connected = false
112
+ }
113
+
114
+ status() {
115
+ return { ...this.stats, wsUrl: this.config.wsUrl, enabled: this.enabled }
116
+ }
117
+
118
+ _connect() {
119
+ if (this.stopped) return
120
+ let socket
121
+ try {
122
+ const url = new URL(this.config.wsUrl)
123
+ socket = new WebSocket(url, {
124
+ headers: this.config.accessToken ? { Authorization: `Bearer ${this.config.accessToken}` } : {},
125
+ })
126
+ } catch (error) {
127
+ this.stats.errors += 1
128
+ this.log('qq: WebSocket 创建失败:' + (error?.message ?? String(error)))
129
+ this._scheduleRetry()
130
+ return
131
+ }
132
+ this.ws = socket
133
+ socket.addEventListener('open', () => {
134
+ this.retry = 0
135
+ this.stats.connected = true
136
+ this.log('qq: 已连接 ' + this.config.wsUrl)
137
+ })
138
+ socket.addEventListener('message', (event) => {
139
+ let payload
140
+ try {
141
+ payload = JSON.parse(typeof event.data === 'string' ? event.data : String(event.data))
142
+ } catch {
143
+ return
144
+ }
145
+ this._onPayload(payload)
146
+ })
147
+ socket.addEventListener('close', () => {
148
+ this.stats.connected = false
149
+ if (!this.stopped) this._scheduleRetry()
150
+ })
151
+ socket.addEventListener('error', () => {
152
+ this.stats.errors += 1
153
+ })
154
+ }
155
+
156
+ _scheduleRetry() {
157
+ if (this.stopped) return
158
+ this.retry = Math.min(this.retry + 1, 6)
159
+ const delay = Math.min(30000, 1000 * 2 ** this.retry)
160
+ this.timer = setTimeout(() => this._connect(), delay)
161
+ }
162
+
163
+ _onPayload(payload) {
164
+ if (!payload || typeof payload !== 'object') return
165
+ // API 响应
166
+ if (typeof payload.echo === 'string' && payload.action === undefined) {
167
+ const pending = this.pending.get(payload.echo)
168
+ if (pending) {
169
+ this.pending.delete(payload.echo)
170
+ pending.resolve(payload)
171
+ }
172
+ return
173
+ }
174
+ if (payload.post_type !== 'message') return
175
+ this.stats.received += 1
176
+ this._handleEvent(payload).catch((error) => {
177
+ this.stats.errors += 1
178
+ this.log('qq: 处理消息失败:' + (error?.message ?? String(error)))
179
+ })
180
+ }
181
+
182
+ async _handleEvent(event) {
183
+ const selfId = String(event.self_id ?? '')
184
+ const userId = String(event.user_id ?? '')
185
+ const groupId = String(event.group_id ?? '')
186
+ if (userId === selfId) return
187
+
188
+ const text = segmentsToText(event.message)
189
+ const isGroup = event.message_type === 'group'
190
+ const isPrivate = event.message_type === 'private'
191
+ if (!isGroup && !isPrivate) return
192
+
193
+ // 白名单:没配就是全拒(安全默认)
194
+ const allowed =
195
+ isGroup
196
+ ? this.config.allowedGroups.map(String).includes(groupId)
197
+ : this.config.allowedUsers.map(String).includes(userId)
198
+ if (!allowed) {
199
+ this.stats.ignored += 1
200
+ return
201
+ }
202
+
203
+ // 群聊要求 @ 机器人(私聊不要求)
204
+ if (isGroup) {
205
+ const mentioned = Array.isArray(event.message) && event.message.some((seg) => seg.type === 'at' && String(seg.data?.qq) === selfId)
206
+ if (!mentioned) {
207
+ this.stats.ignored += 1
208
+ return
209
+ }
210
+ }
211
+
212
+ const parsed = parseCommand(text, this.config.prefix)
213
+ if (!parsed) return
214
+
215
+ // 简单限流:同一用户 2 秒一条
216
+ const key = userId
217
+ const last = this.lastCmdAt.get(key) ?? 0
218
+ if (nowMs() - last < this.config.rateLimitMs) {
219
+ this.stats.ignored += 1
220
+ return
221
+ }
222
+ this.lastCmdAt.set(key, nowMs())
223
+
224
+ const reply = await this.handleCommand(parsed, { userId, groupId, isGroup, messageId: event.message_id })
225
+ if (!reply) return
226
+ const target = isGroup ? { message_type: 'group', group_id: Number(groupId) } : { message_type: 'private', user_id: Number(userId) }
227
+ await this._call('send_msg', { ...target, message: reply })
228
+ this.stats.replied += 1
229
+ }
230
+
231
+ /** 命令处理:纯函数式,便于单测。 */
232
+ async handleCommand(parsed, context = {}) {
233
+ return runMemoryCommand(this.store, parsed, context)
234
+ }
235
+
236
+ _call(action, params) {
237
+ return new Promise((resolve) => {
238
+ if (!this.ws || this.ws.readyState !== 1) {
239
+ resolve({ status: 'failed', retcode: -1, message: 'not connected' })
240
+ return
241
+ }
242
+ const echo = `mc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
243
+ this.pending.set(echo, { resolve })
244
+ try {
245
+ this.ws.send(JSON.stringify({ action, params, echo }))
246
+ } catch (error) {
247
+ this.pending.delete(echo)
248
+ resolve({ status: 'failed', retcode: -1, message: error?.message ?? String(error) })
249
+ return
250
+ }
251
+ setTimeout(() => {
252
+ if (this.pending.has(echo)) {
253
+ this.pending.delete(echo)
254
+ resolve({ status: 'failed', retcode: -1, message: 'timeout' })
255
+ }
256
+ }, 10000)
257
+ })
258
+ }
259
+ }
260
+
261
+ /** 命令实现(两个桥共用:OneBot 本地 / QQ 官方)。 */
262
+ export async function runMemoryCommand(store, parsed, context = {}) {
263
+ const arg = String(parsed?.arg ?? '').trim()
264
+ switch (parsed?.cmd) {
265
+ case 'remember': {
266
+ if (!arg) return '用法:/记 <要记住的内容>'
267
+ const result = store.write({
268
+ content: arg,
269
+ layer: 'L2',
270
+ sourceChannel: 'qq',
271
+ trustLevel: 'unverified',
272
+ explicit: true,
273
+ principalId: context.userId ? `qq:${context.userId}` : null,
274
+ })
275
+ return result?.dedup ? `已存在相同内容:${result.record_id}` : `已记下(待审):${result.record_id}`
276
+ }
277
+ case 'search': {
278
+ if (!arg) return '用法:/搜 <关键词>'
279
+ const hits = store.search({ query: arg, topK: 3 })
280
+ if (!hits.length) return '没搜到相关记忆。'
281
+ return ['搜到:', ...hits.map((h, i) => `${i + 1}. [${h.layer}] ${oneLine(h.summary, 50)}`)].join('\n')
282
+ }
283
+ case 'associate': {
284
+ if (!arg) return '用法:/联想 <关键词或一句话>'
285
+ const result = store.associate({ query: arg, topK: 3 })
286
+ if (!result.items.length) return '没想到相关的记忆。'
287
+ return [
288
+ '联想到:',
289
+ ...result.items.map((it, i) => `${i + 1}. [${it.layer}] ${oneLine(it.summary, 50)}(${it.reasons.join('、')})`),
290
+ ].join('\n')
291
+ }
292
+ case 'recent': {
293
+ const rows = store.db
294
+ .prepare(
295
+ "SELECT record_id, layer, summary FROM records WHERE status = 'active' AND sad_level != 'S' ORDER BY created_at DESC LIMIT 5",
296
+ )
297
+ .all()
298
+ if (!rows.length) return '还没有记忆。'
299
+ return ['最近:', ...rows.map((r, i) => `${i + 1}. [${r.layer}] ${oneLine(r.summary, 50)}`)].join('\n')
300
+ }
301
+ case 'status': {
302
+ const s = store.stats()
303
+ return [
304
+ `记录 ${s.records}(S 级 ${s.sLevel})`,
305
+ `待审 ${s.pending}`,
306
+ `审计 ${s.audit?.ok ? '一致' : '异常'}`,
307
+ `schema v${s.schemaVersion}`,
308
+ ].join('\n')
309
+ }
310
+ case 'help':
311
+ return [
312
+ '可用命令:',
313
+ '/记 <内容> — 写入记忆(先审后入)',
314
+ '/搜 <关键词> — 检索',
315
+ '/联想 <关键词> — 由 A 想到 B',
316
+ '/最近 — 最近 5 条',
317
+ '/状态 — 库健康',
318
+ ].join('\n')
319
+ default:
320
+ return '不认识的命令,发 /帮助 看用法。'
321
+ }
322
+ }
323
+
324
+ export function createQqBridge(options) {
325
+ return new QqBridge(options)
326
+ }