dsh-wechat-access 0.0.0-stage → 0.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.
- package/CHANGELOG.md +56 -0
- package/LICENSE +675 -0
- package/README.md +278 -2
- package/cordis.patch.yml +5 -0
- package/examples/config.example.json +98 -0
- package/index.mjs +123 -0
- package/lib/access.mjs +131 -0
- package/lib/anysearch.mjs +143 -0
- package/lib/capabilities.mjs +312 -0
- package/lib/client.js +2532 -0
- package/lib/config.mjs +509 -0
- package/lib/emotion-store.mjs +352 -0
- package/lib/emotion.mjs +428 -0
- package/lib/endocrine/LICENSE +21 -0
- package/lib/endocrine/README.md +39 -0
- package/lib/endocrine/diseases.js +791 -0
- package/lib/endocrine/engine.mjs +131 -0
- package/lib/endocrine/store.mjs +253 -0
- package/lib/endocrine/upstream.mjs +1230 -0
- package/lib/group-gate.mjs +305 -0
- package/lib/imagegen.mjs +360 -0
- package/lib/lock.mjs +204 -0
- package/lib/meme-classify.mjs +190 -0
- package/lib/memes.mjs +442 -0
- package/lib/memory.mjs +437 -0
- package/lib/normalize.mjs +230 -0
- package/lib/parser.mjs +602 -0
- package/lib/reply-settled.mjs +130 -0
- package/lib/runtime.mjs +3367 -0
- package/lib/startup.mjs +70 -0
- package/lib/steam-binding.mjs +144 -0
- package/lib/steam.mjs +334 -0
- package/lib/store.mjs +259 -0
- package/lib/thoughts.mjs +149 -0
- package/lib/time-context.mjs +182 -0
- package/lib/tools.mjs +583 -0
- package/lib/ui.mjs +997 -0
- package/lib/util.mjs +489 -0
- package/lib/virtual-life-generate.mjs +421 -0
- package/lib/virtual-life.mjs +971 -0
- package/lib/weather.mjs +172 -0
- package/lib/wechat-client.mjs +476 -0
- package/lib/wechat-events.mjs +269 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-wechat 事件流(SSE)订阅与游标持久化。
|
|
3
|
+
*
|
|
4
|
+
* 这一层取代 dsh-qq-access 的 `lib/events.mjs`(本地 HTTP 服务器 + HMAC 上报)
|
|
5
|
+
* 和 runtime 里的轮询兜底。三件事变简单了:
|
|
6
|
+
*
|
|
7
|
+
* 1. 不用开监听端口,也不用管签名密钥 —— 是我们主动连出去。
|
|
8
|
+
* 2. 游标由服务端给(`?after=N`),断线重连天然可续传,不需要
|
|
9
|
+
* 「记住最后一条消息 ID 再回查」那套补漏逻辑。
|
|
10
|
+
* 3. 事件是**持久日志**,重连后能拿到断线期间漏掉的全部事件。
|
|
11
|
+
*
|
|
12
|
+
* 但有两点必须自己处理:
|
|
13
|
+
*
|
|
14
|
+
* - `message.committed` **只给 messageId + threadId,没有正文**。
|
|
15
|
+
* 收到事件后必须再 GET 一次消息本体,否则会以为收到了一条空消息。
|
|
16
|
+
* - 同一个 messageId 可能因为重放/重连被投递多次,去重不能省。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
|
|
20
|
+
import { dirname, join } from 'node:path';
|
|
21
|
+
import { assert, checkSignal, safeLog } from './util.mjs';
|
|
22
|
+
|
|
23
|
+
/** 断线重连的退避:0.5s 起步,最长 30s。 */
|
|
24
|
+
const RECONNECT_MIN_MS = 500;
|
|
25
|
+
const RECONNECT_MAX_MS = 30_000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 解析一段 SSE 文本为事件数组。
|
|
29
|
+
*
|
|
30
|
+
* 只实现 agent-wechat 实际用到的子集:`id:` / `data:` / 注释行。
|
|
31
|
+
* 单独抽出来是为了能脱离网络单测。
|
|
32
|
+
*/
|
|
33
|
+
export function parseSseChunk(text) {
|
|
34
|
+
const events = [];
|
|
35
|
+
for (const block of text.split('\n\n')) {
|
|
36
|
+
if (!block.trim()) continue;
|
|
37
|
+
let id = '';
|
|
38
|
+
const dataLines = [];
|
|
39
|
+
for (const line of block.split('\n')) {
|
|
40
|
+
if (line.startsWith(':')) continue; // ": connected" 之类的心跳注释
|
|
41
|
+
if (line.startsWith('id:')) { id = line.slice(3).trim(); continue; }
|
|
42
|
+
if (line.startsWith('data:')) { dataLines.push(line.slice(5).trimStart()); continue; }
|
|
43
|
+
}
|
|
44
|
+
if (!dataLines.length) continue;
|
|
45
|
+
const raw = dataLines.join('\n');
|
|
46
|
+
let parsed;
|
|
47
|
+
try { parsed = JSON.parse(raw); }
|
|
48
|
+
catch { continue; } // 半截 JSON 由调用方按块边界处理
|
|
49
|
+
events.push({ id: id || String(parsed?.cursor ?? ''), event: parsed });
|
|
50
|
+
}
|
|
51
|
+
return events;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class WechatEventStream {
|
|
55
|
+
#controller = null;
|
|
56
|
+
#running = false;
|
|
57
|
+
#cursor = '';
|
|
58
|
+
#cursorFile;
|
|
59
|
+
#messageHandlers = new Set();
|
|
60
|
+
#eventHandlers = new Set();
|
|
61
|
+
#seen = new Set();
|
|
62
|
+
#stats = { received: 0, dispatched: 0, duplicates: 0, reconnects: 0, errors: 0 };
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {object} options
|
|
66
|
+
* @param {import('./wechat-client.mjs').WechatClient} options.client
|
|
67
|
+
* @param {string} options.dataDir 游标持久化目录
|
|
68
|
+
* @param {object} [options.logger]
|
|
69
|
+
*/
|
|
70
|
+
constructor({ client, dataDir, logger }) {
|
|
71
|
+
this.client = client;
|
|
72
|
+
this.logger = logger ?? console;
|
|
73
|
+
this.#cursorFile = join(dataDir, 'wechat-events-cursor.json');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
get cursor() { return this.#cursor; }
|
|
77
|
+
get stats() { return { ...this.#stats, cursor: this.#cursor }; }
|
|
78
|
+
|
|
79
|
+
onMessage(handler) { this.#messageHandlers.add(handler); return () => this.#messageHandlers.delete(handler); }
|
|
80
|
+
onEvent(handler) { this.#eventHandlers.add(handler); return () => this.#eventHandlers.delete(handler); }
|
|
81
|
+
|
|
82
|
+
async #loadCursor() {
|
|
83
|
+
try {
|
|
84
|
+
const raw = JSON.parse(await readFile(this.#cursorFile, 'utf8'));
|
|
85
|
+
this.#cursor = String(raw?.cursor ?? '');
|
|
86
|
+
} catch { /* 首次运行没有游标文件 */ }
|
|
87
|
+
// 首次运行绝不能从头回放。
|
|
88
|
+
//
|
|
89
|
+
// 实测:不带 after 连上去会从游标 1 开始推——那是账号登录以来的**全部**
|
|
90
|
+
// 历史事件(几千条联系人/群更新),插件会瞬间被淹没,还会把几天前的
|
|
91
|
+
// 消息当成新消息回复。所以没有游标时先问服务端「现在到哪了」。
|
|
92
|
+
if (!this.#cursor) {
|
|
93
|
+
try {
|
|
94
|
+
this.#cursor = await this.#resolveNewestCursor();
|
|
95
|
+
} catch { this.#cursor = ''; }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 当前事件游标。
|
|
101
|
+
*
|
|
102
|
+
* `/events?newest=true&limit=1` 返回一条最新事件,取它的 cursor 作为起点。
|
|
103
|
+
* 用「取一条」而不是「读全部」,避免为了知道位置付出回放几千条的代价。
|
|
104
|
+
*/
|
|
105
|
+
async #resolveNewestCursor() {
|
|
106
|
+
const base = this.client.baseUrl;
|
|
107
|
+
const account = encodeURIComponent(this.client.accountId);
|
|
108
|
+
const response = await fetch(`${base}/accounts/${account}/events?newest=true&limit=1`, {
|
|
109
|
+
headers: { Authorization: `Bearer ${this.client.config.token}` },
|
|
110
|
+
});
|
|
111
|
+
if (!response.ok) return '';
|
|
112
|
+
const data = await response.json();
|
|
113
|
+
const newest = Array.isArray(data?.items) ? data.items[0] : null;
|
|
114
|
+
return String(newest?.cursor ?? '');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async #saveCursor() {
|
|
118
|
+
if (!this.#cursor) return;
|
|
119
|
+
const temp = `${this.#cursorFile}.${process.pid}.tmp`;
|
|
120
|
+
try {
|
|
121
|
+
await mkdir(dirname(this.#cursorFile), { recursive: true, mode: 0o700 });
|
|
122
|
+
await writeFile(temp, JSON.stringify({ cursor: this.#cursor, at: Date.now() }), { mode: 0o600 });
|
|
123
|
+
await rename(temp, this.#cursorFile);
|
|
124
|
+
} catch (error) { safeLog(this.logger, '微信事件游标写入失败', error); }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 去重:事件重放会让同一个 messageId 出现多次。
|
|
129
|
+
*
|
|
130
|
+
* 用 messageId 而不是 cursor 做键——cursor 每次重连都会变,
|
|
131
|
+
* 但同一条消息的 id 不会变。集合上限防止长时间运行无界增长。
|
|
132
|
+
*/
|
|
133
|
+
#isDuplicate(messageId) {
|
|
134
|
+
const id = String(messageId ?? '');
|
|
135
|
+
if (!id) return false;
|
|
136
|
+
if (this.#seen.has(id)) { this.#stats.duplicates += 1; return true; }
|
|
137
|
+
this.#seen.add(id);
|
|
138
|
+
if (this.#seen.size > 20_000) this.#seen.delete(this.#seen.values().next().value);
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async #dispatch(event) {
|
|
143
|
+
this.#stats.received += 1;
|
|
144
|
+
if (event?.cursor) {
|
|
145
|
+
this.#cursor = String(event.cursor);
|
|
146
|
+
}
|
|
147
|
+
for (const handler of this.#eventHandlers) {
|
|
148
|
+
try { await handler(event); }
|
|
149
|
+
catch (error) { safeLog(this.logger, `微信事件处理失败(${event?.kind})`, error); }
|
|
150
|
+
}
|
|
151
|
+
if (event?.kind !== 'message.committed') return;
|
|
152
|
+
const data = event.data ?? {};
|
|
153
|
+
// 只处理收到的消息;自己发出去的那份已经在发送时归档过了。
|
|
154
|
+
if (String(data.direction ?? '') !== 'incoming') return;
|
|
155
|
+
const threadId = String(data.threadId ?? '');
|
|
156
|
+
const messageId = String(data.messageId ?? '');
|
|
157
|
+
if (!threadId || !messageId) return;
|
|
158
|
+
if (this.#isDuplicate(messageId)) return;
|
|
159
|
+
|
|
160
|
+
// 事件里没有正文,必须回查。查失败不算致命:丢这一条,游标照常前进。
|
|
161
|
+
let message;
|
|
162
|
+
try {
|
|
163
|
+
message = await this.client.message(threadId, messageId, this.#controller?.signal);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
safeLog(this.logger, `微信消息回查失败(${messageId.slice(0, 24)})`, error);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (!message) return;
|
|
169
|
+
this.#stats.dispatched += 1;
|
|
170
|
+
for (const handler of this.#messageHandlers) {
|
|
171
|
+
try { await handler(message); }
|
|
172
|
+
catch (error) { safeLog(this.logger, '微信入站消息处理失败', error); }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 建立 SSE 连接并持续消费,直到 stop() 或 signal 中止。
|
|
178
|
+
*
|
|
179
|
+
* 重连策略:断线后按指数退避重连,并从已保存的游标续传。
|
|
180
|
+
* 只要游标还在,断线期间的事件不会丢。
|
|
181
|
+
*/
|
|
182
|
+
async start(signal) {
|
|
183
|
+
if (this.#running) return;
|
|
184
|
+
this.#running = true;
|
|
185
|
+
await this.#loadCursor();
|
|
186
|
+
const loop = async () => {
|
|
187
|
+
let backoff = RECONNECT_MIN_MS;
|
|
188
|
+
while (this.#running) {
|
|
189
|
+
checkSignal(signal);
|
|
190
|
+
this.#controller = new AbortController();
|
|
191
|
+
const onAbort = () => this.#controller?.abort();
|
|
192
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
193
|
+
try {
|
|
194
|
+
const ok = await this.#consumeOnce(this.#controller.signal);
|
|
195
|
+
if (ok) backoff = RECONNECT_MIN_MS;
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if (!this.#running || signal?.aborted) break;
|
|
198
|
+
this.#stats.errors += 1;
|
|
199
|
+
this.logger.warn?.('微信事件流断开,' + String(error?.message ?? error).slice(0, 200));
|
|
200
|
+
} finally {
|
|
201
|
+
signal?.removeEventListener('abort', onAbort);
|
|
202
|
+
}
|
|
203
|
+
if (!this.#running || signal?.aborted) break;
|
|
204
|
+
this.#stats.reconnects += 1;
|
|
205
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
206
|
+
backoff = Math.min(RECONNECT_MAX_MS, backoff * 2);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
// 不 await:start() 只负责把循环拉起来,调用方继续往下走。
|
|
210
|
+
this.#loop = loop().catch((error) => safeLog(this.logger, '微信事件流终止', error));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
#loop = null;
|
|
214
|
+
|
|
215
|
+
async #consumeOnce(signal) {
|
|
216
|
+
const base = this.client.baseUrl;
|
|
217
|
+
const account = encodeURIComponent(this.client.accountId);
|
|
218
|
+
// 参数名是 `after`,不是文档里写的 `cursor`——实测 400 会明确告诉你。
|
|
219
|
+
const qs = new URLSearchParams();
|
|
220
|
+
if (this.#cursor) qs.set('after', this.#cursor);
|
|
221
|
+
const url = `${base}/accounts/${account}/events${qs.toString() ? `?${qs}` : ''}`;
|
|
222
|
+
|
|
223
|
+
const response = await fetch(url, {
|
|
224
|
+
headers: { Authorization: `Bearer ${this.client.config.token}`, Accept: 'text/event-stream' },
|
|
225
|
+
signal,
|
|
226
|
+
});
|
|
227
|
+
if (!response.ok) {
|
|
228
|
+
throw new Error(`事件流返回 HTTP ${response.status}`);
|
|
229
|
+
}
|
|
230
|
+
if (!response.body) throw new Error('事件流没有响应体');
|
|
231
|
+
|
|
232
|
+
const reader = response.body.getReader();
|
|
233
|
+
const decoder = new TextDecoder();
|
|
234
|
+
let buffer = '';
|
|
235
|
+
try {
|
|
236
|
+
while (this.#running) {
|
|
237
|
+
const { done, value } = await reader.read();
|
|
238
|
+
if (done) break;
|
|
239
|
+
buffer += decoder.decode(value, { stream: true });
|
|
240
|
+
// SSE 以空行分帧;最后一段可能是半帧,留在 buffer 里等下一块。
|
|
241
|
+
let boundary;
|
|
242
|
+
while ((boundary = buffer.indexOf('\n\n')) !== -1) {
|
|
243
|
+
const frame = buffer.slice(0, boundary);
|
|
244
|
+
buffer = buffer.slice(boundary + 2);
|
|
245
|
+
for (const { event } of parseSseChunk(frame)) {
|
|
246
|
+
await this.#dispatch(event);
|
|
247
|
+
}
|
|
248
|
+
await this.#saveCursor();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
} finally {
|
|
252
|
+
try { await reader.cancel(); } catch { /* 已关闭 */ }
|
|
253
|
+
}
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async stop() {
|
|
258
|
+
this.#running = false;
|
|
259
|
+
try { this.#controller?.abort(); } catch { /* 忽略 */ }
|
|
260
|
+
await this.#saveCursor();
|
|
261
|
+
try { await this.#loop; } catch { /* 已记录 */ }
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** 事件流健康状态,给 qq_status 风格的 status() 用。 */
|
|
266
|
+
export function eventStreamStatus(stream) {
|
|
267
|
+
if (!stream) return { running: false };
|
|
268
|
+
return { running: true, ...stream.stats };
|
|
269
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-wechat-access",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "DeepSeek Harness 的微信接入插件:基于 agent-wechat 守护进程,消息归档、表情包、虚拟人生、情感关系、长期记忆与群聊智能回复。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.mjs",
|
|
9
|
+
"./client": "./lib/client.js",
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.14.0",
|
|
14
|
+
"dsh": ">=0.2.1-rc.4"
|
|
15
|
+
},
|
|
16
|
+
"license": "GPL-3.0-or-later",
|
|
17
|
+
"keywords": [
|
|
18
|
+
"dsh",
|
|
19
|
+
"dsh-plugin",
|
|
20
|
+
"deepseek-harness",
|
|
21
|
+
"wechat",
|
|
22
|
+
"agent-wechat",
|
|
23
|
+
"wechat-bot",
|
|
24
|
+
"emotion",
|
|
25
|
+
"chatbot"
|
|
26
|
+
],
|
|
27
|
+
"files": [
|
|
28
|
+
"index.mjs",
|
|
29
|
+
"lib/",
|
|
30
|
+
"examples/",
|
|
31
|
+
"locale/",
|
|
32
|
+
"cordis.patch.yml",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
"dsh": {
|
|
38
|
+
"bundle": {
|
|
39
|
+
"patch": "./cordis.patch.yml"
|
|
40
|
+
},
|
|
41
|
+
"client": {
|
|
42
|
+
"platform": "web",
|
|
43
|
+
"immediately": true,
|
|
44
|
+
"inject": [
|
|
45
|
+
"@deepseek-ai/dsh-client-ui-sidebar",
|
|
46
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
47
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
48
|
+
],
|
|
49
|
+
"external": [
|
|
50
|
+
"react"
|
|
51
|
+
]
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"@deepseek-ai/dsh-llm": "*"
|
|
56
|
+
},
|
|
57
|
+
"peerDependenciesMeta": {
|
|
58
|
+
"@deepseek-ai/dsh-llm": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"test": "node --test",
|
|
64
|
+
"pack:tgz": "npm pack"
|
|
65
|
+
},
|
|
66
|
+
"author": "Applepinea (https://github.com/Applepinea)",
|
|
67
|
+
"repository": {
|
|
68
|
+
"type": "git",
|
|
69
|
+
"url": "git+https://github.com/Applepinea/dsh-wechat-access.git"
|
|
70
|
+
},
|
|
71
|
+
"homepage": "https://github.com/Applepinea/dsh-wechat-access#readme",
|
|
72
|
+
"bugs": {
|
|
73
|
+
"url": "https://github.com/Applepinea/dsh-wechat-access/issues"
|
|
74
|
+
},
|
|
75
|
+
"publishConfig": {
|
|
76
|
+
"access": "public",
|
|
77
|
+
"registry": "https://registry.npmjs.org/"
|
|
78
|
+
}
|
|
79
|
+
}
|