@unlinearity/cli-wechat-bridge 1.0.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 (49) hide show
  1. package/LICENSE.txt +21 -0
  2. package/README.md +531 -0
  3. package/bin/_run-entry.mjs +41 -0
  4. package/bin/wechat-bridge-claude.mjs +5 -0
  5. package/bin/wechat-bridge-codex.mjs +5 -0
  6. package/bin/wechat-bridge-opencode.mjs +5 -0
  7. package/bin/wechat-bridge-shell.mjs +5 -0
  8. package/bin/wechat-bridge.mjs +5 -0
  9. package/bin/wechat-check-update.mjs +5 -0
  10. package/bin/wechat-claude-start.mjs +5 -0
  11. package/bin/wechat-claude.mjs +5 -0
  12. package/bin/wechat-codex-start.mjs +5 -0
  13. package/bin/wechat-codex.mjs +5 -0
  14. package/bin/wechat-opencode-start.mjs +5 -0
  15. package/bin/wechat-opencode.mjs +5 -0
  16. package/package.json +86 -0
  17. package/src/bridge/bridge-adapters.claude.ts +1047 -0
  18. package/src/bridge/bridge-adapters.codex.ts +2733 -0
  19. package/src/bridge/bridge-adapters.core.ts +877 -0
  20. package/src/bridge/bridge-adapters.opencode.ts +2390 -0
  21. package/src/bridge/bridge-adapters.shared.ts +1647 -0
  22. package/src/bridge/bridge-adapters.shell.ts +456 -0
  23. package/src/bridge/bridge-adapters.ts +30 -0
  24. package/src/bridge/bridge-controller.ts +58 -0
  25. package/src/bridge/bridge-final-reply.ts +56 -0
  26. package/src/bridge/bridge-process-reaper.ts +417 -0
  27. package/src/bridge/bridge-state.ts +520 -0
  28. package/src/bridge/bridge-types.ts +218 -0
  29. package/src/bridge/bridge-utils.ts +1524 -0
  30. package/src/bridge/claude-hook.ts +92 -0
  31. package/src/bridge/claude-hooks.ts +376 -0
  32. package/src/bridge/wechat-bridge.ts +1305 -0
  33. package/src/commands/check-update.ts +46 -0
  34. package/src/companion/codex-panel-link.ts +151 -0
  35. package/src/companion/codex-panel.ts +225 -0
  36. package/src/companion/codex-remote-client.ts +178 -0
  37. package/src/companion/local-companion-link.ts +338 -0
  38. package/src/companion/local-companion-start.ts +520 -0
  39. package/src/companion/local-companion.ts +532 -0
  40. package/src/media/media-types.ts +11 -0
  41. package/src/runtime/create-runtime-host.ts +16 -0
  42. package/src/runtime/legacy-adapter-runtime.ts +55 -0
  43. package/src/runtime/runtime-types.ts +51 -0
  44. package/src/utils/version-checker.ts +197 -0
  45. package/src/wechat/channel-config.ts +141 -0
  46. package/src/wechat/setup.ts +232 -0
  47. package/src/wechat/standalone-bot.ts +483 -0
  48. package/src/wechat/wechat-channel.ts +608 -0
  49. package/src/wechat/wechat-transport.ts +1290 -0
@@ -0,0 +1,483 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Standalone WeChat + Claude bot.
4
+ *
5
+ * This script directly connects WeChat ClawBot to Claude API,
6
+ * bypassing the MCP channel protocol.
7
+ *
8
+ * Usage:
9
+ * bun run src/wechat/standalone-bot.ts
10
+ */
11
+
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import crypto from "node:crypto";
15
+ import Anthropic from "@anthropic-ai/sdk";
16
+
17
+ // Types
18
+ type AccountData = {
19
+ token: string;
20
+ baseUrl: string;
21
+ accountId: string;
22
+ userId?: string;
23
+ savedAt: string;
24
+ };
25
+
26
+ interface TextItem {
27
+ text?: string;
28
+ }
29
+
30
+ interface RefMessage {
31
+ message_item?: MessageItem;
32
+ title?: string;
33
+ }
34
+
35
+ interface MessageItem {
36
+ type?: number;
37
+ text_item?: TextItem;
38
+ voice_item?: { text?: string };
39
+ ref_msg?: RefMessage;
40
+ }
41
+
42
+ interface WeixinMessage {
43
+ from_user_id?: string;
44
+ to_user_id?: string;
45
+ client_id?: string;
46
+ session_id?: string;
47
+ message_type?: number;
48
+ message_state?: number;
49
+ item_list?: MessageItem[];
50
+ context_token?: string;
51
+ create_time_ms?: number;
52
+ }
53
+
54
+ interface GetUpdatesResp {
55
+ ret?: number;
56
+ errcode?: number;
57
+ errmsg?: string;
58
+ msgs?: WeixinMessage[];
59
+ get_updates_buf?: string;
60
+ longpolling_timeout_ms?: number;
61
+ }
62
+
63
+ // Constants
64
+ const HOME_DIR = os.homedir();
65
+ const CREDENTIALS_FILE = `${HOME_DIR}/.claude/channels/wechat/account.json`;
66
+ const SYNC_BUF_FILE = `${HOME_DIR}/.claude/channels/wechat/sync_buf.txt`;
67
+ const LOG_DIR = `${HOME_DIR}/.claude/channels/wechat/logs`;
68
+ const BOT_TYPE = "3";
69
+ const CHANNEL_VERSION = "0.1.0";
70
+ const LONG_POLL_TIMEOUT_MS = 35_000;
71
+ const MSG_TYPE_USER = 1;
72
+ const MSG_TYPE_BOT = 2;
73
+ const MSG_ITEM_TEXT = 1;
74
+ const MSG_ITEM_VOICE = 3;
75
+ const MSG_STATE_FINISH = 2;
76
+
77
+ // Conversation history per user
78
+ const conversationHistory = new Map<string, Array<{role: string, content: string}>>();
79
+ const MAX_HISTORY = 10;
80
+
81
+ // Logging
82
+ function log(message: string): void {
83
+ const timestamp = new Date().toISOString();
84
+ console.log(`[${timestamp}] ${message}`);
85
+ }
86
+
87
+ function logError(message: string): void {
88
+ const timestamp = new Date().toISOString();
89
+ console.error(`[${timestamp}] ERROR: ${message}`);
90
+ }
91
+
92
+ // Load WeChat credentials
93
+ function loadCredentials(): AccountData | null {
94
+ try {
95
+ if (!fs.existsSync(CREDENTIALS_FILE)) {
96
+ logError(`Credentials file not found: ${CREDENTIALS_FILE}`);
97
+ return null;
98
+ }
99
+ const content = fs.readFileSync(CREDENTIALS_FILE, "utf-8");
100
+ return JSON.parse(content) as AccountData;
101
+ } catch (err) {
102
+ logError(`Failed to read credentials: ${String(err)}`);
103
+ return null;
104
+ }
105
+ }
106
+
107
+ // WeChat API utilities
108
+ function randomWechatUin(): string {
109
+ const uint32 = crypto.randomBytes(4).readUInt32BE(0);
110
+ return Buffer.from(String(uint32), "utf-8").toString("base64");
111
+ }
112
+
113
+ function buildHeaders(token?: string, body?: string): Record<string, string> {
114
+ const headers: Record<string, string> = {
115
+ "Content-Type": "application/json",
116
+ AuthorizationType: "ilink_bot_token",
117
+ "X-WECHAT-UIN": randomWechatUin(),
118
+ };
119
+
120
+ if (body) {
121
+ headers["Content-Length"] = String(Buffer.byteLength(body, "utf-8"));
122
+ }
123
+ if (token?.trim()) {
124
+ headers.Authorization = `Bearer ${token.trim()}`;
125
+ }
126
+
127
+ return headers;
128
+ }
129
+
130
+ async function apiFetch(params: {
131
+ baseUrl: string;
132
+ endpoint: string;
133
+ body: string;
134
+ token?: string;
135
+ timeoutMs: number;
136
+ }): Promise<string> {
137
+ const base = params.baseUrl.endsWith("/") ? params.baseUrl : `${params.baseUrl}/`;
138
+ const url = new URL(params.endpoint, base).toString();
139
+ const controller = new AbortController();
140
+ const timer = setTimeout(() => controller.abort(), params.timeoutMs);
141
+
142
+ try {
143
+ const res = await fetch(url, {
144
+ method: "POST",
145
+ headers: buildHeaders(params.token, params.body),
146
+ body: params.body,
147
+ signal: controller.signal,
148
+ });
149
+ clearTimeout(timer);
150
+
151
+ const text = await res.text();
152
+ if (!res.ok) {
153
+ throw new Error(`HTTP ${res.status}: ${text}`);
154
+ }
155
+ return text;
156
+ } catch (err) {
157
+ clearTimeout(timer);
158
+ throw err;
159
+ }
160
+ }
161
+
162
+ async function getUpdates(
163
+ baseUrl: string,
164
+ token: string,
165
+ getUpdatesBuf: string,
166
+ ): Promise<GetUpdatesResp> {
167
+ try {
168
+ const raw = await apiFetch({
169
+ baseUrl,
170
+ endpoint: "ilink/bot/getupdates",
171
+ body: JSON.stringify({
172
+ get_updates_buf: getUpdatesBuf,
173
+ base_info: { channel_version: CHANNEL_VERSION },
174
+ }),
175
+ token,
176
+ timeoutMs: LONG_POLL_TIMEOUT_MS,
177
+ });
178
+ return JSON.parse(raw) as GetUpdatesResp;
179
+ } catch (err) {
180
+ if (err instanceof Error && err.name === "AbortError") {
181
+ return { ret: 0, msgs: [], get_updates_buf: getUpdatesBuf };
182
+ }
183
+ throw err;
184
+ }
185
+ }
186
+
187
+ function extractTextFromMessage(msg: WeixinMessage): string {
188
+ if (!msg.item_list?.length) {
189
+ return "";
190
+ }
191
+
192
+ const lines: string[] = [];
193
+
194
+ for (const item of msg.item_list) {
195
+ if (item.type === MSG_ITEM_TEXT) {
196
+ const text = item.text_item?.text?.trim();
197
+ if (text) {
198
+ lines.push(text);
199
+ }
200
+ }
201
+
202
+ if (item.type === MSG_ITEM_VOICE) {
203
+ const transcript = item.voice_item?.text?.trim();
204
+ if (transcript) {
205
+ lines.push(transcript);
206
+ }
207
+ }
208
+ }
209
+
210
+ return lines.join("\n").trim();
211
+ }
212
+
213
+ function generateClientId(): string {
214
+ return `claude-wechat-bot:${Date.now()}-${crypto.randomBytes(4).toString("hex")}`;
215
+ }
216
+
217
+ async function sendTextMessage(
218
+ baseUrl: string,
219
+ token: string,
220
+ to: string,
221
+ text: string,
222
+ contextToken: string,
223
+ ): Promise<string> {
224
+ const trimmedText = text.trim();
225
+ if (!trimmedText) {
226
+ throw new Error("Reply text cannot be empty.");
227
+ }
228
+
229
+ const clientId = generateClientId();
230
+ await apiFetch({
231
+ baseUrl,
232
+ endpoint: "ilink/bot/sendmessage",
233
+ body: JSON.stringify({
234
+ msg: {
235
+ from_user_id: "",
236
+ to_user_id: to,
237
+ client_id: clientId,
238
+ message_type: MSG_TYPE_BOT,
239
+ message_state: MSG_STATE_FINISH,
240
+ item_list: [{ type: MSG_ITEM_TEXT, text_item: { text: trimmedText } }],
241
+ context_token: contextToken,
242
+ },
243
+ base_info: { channel_version: CHANNEL_VERSION },
244
+ }),
245
+ token,
246
+ timeoutMs: 15_000,
247
+ });
248
+ return clientId;
249
+ }
250
+
251
+ // Message deduplication
252
+ const recentMessageKeys = new Set<string>();
253
+ const recentMessageOrder: string[] = [];
254
+ const RECENT_MESSAGE_CACHE_SIZE = 500;
255
+
256
+ function buildMessageKey(msg: WeixinMessage): string {
257
+ return [
258
+ msg.from_user_id ?? "",
259
+ msg.client_id ?? "",
260
+ String(msg.create_time_ms ?? ""),
261
+ msg.context_token ?? "",
262
+ ].join("|");
263
+ }
264
+
265
+ function rememberMessage(key: string): boolean {
266
+ if (!key || recentMessageKeys.has(key)) {
267
+ return false;
268
+ }
269
+
270
+ recentMessageKeys.add(key);
271
+ recentMessageOrder.push(key);
272
+
273
+ while (recentMessageOrder.length > RECENT_MESSAGE_CACHE_SIZE) {
274
+ const oldest = recentMessageOrder.shift();
275
+ if (oldest) {
276
+ recentMessageKeys.delete(oldest);
277
+ }
278
+ }
279
+
280
+ return true;
281
+ }
282
+
283
+ // Claude API integration
284
+ let anthropic: Anthropic | null = null;
285
+
286
+ function initClaude(): boolean {
287
+ // 使用与 Claude Code 相同的代理配置
288
+ const baseURL = process.env.ANTHROPIC_BASE_URL || "http://127.0.0.1:15721";
289
+
290
+ anthropic = new Anthropic({
291
+ apiKey: "dummy-key", // 代理不需要真实的 API key
292
+ baseURL: baseURL,
293
+ dangerouslyAllowBrowser: true, // 允许在非标准环境下使用
294
+ });
295
+
296
+ log(`Claude API initialized (via proxy: ${baseURL})`);
297
+ return true;
298
+ }
299
+
300
+ async function getClaudeResponse(
301
+ userMessage: string,
302
+ userId: string,
303
+ ): Promise<string> {
304
+ if (!anthropic) {
305
+ throw new Error("Claude API not initialized");
306
+ }
307
+
308
+ // Get or create conversation history
309
+ let history = conversationHistory.get(userId) || [];
310
+
311
+ // Add user message to history
312
+ history.push({ role: "user", content: userMessage });
313
+
314
+ // Keep only recent messages
315
+ if (history.length > MAX_HISTORY) {
316
+ history = history.slice(-MAX_HISTORY);
317
+ }
318
+
319
+ try {
320
+ const msg = await anthropic.messages.create({
321
+ model: "claude-sonnet-4-20250514",
322
+ max_tokens: 1024,
323
+ system: "你是一个有帮助的AI助手。请用简洁、友好的方式回复,适合微信聊天场景。",
324
+ messages: history as any,
325
+ });
326
+
327
+ // Extract the response text
328
+ let responseText = "";
329
+ for (const block of msg.content) {
330
+ if (block.type === "text") {
331
+ responseText += block.text;
332
+ }
333
+ }
334
+
335
+ // Add assistant response to history
336
+ history.push({ role: "assistant", content: responseText });
337
+ conversationHistory.set(userId, history);
338
+
339
+ return responseText;
340
+ } catch (err) {
341
+ logError(`Claude API error: ${String(err)}`);
342
+ throw err;
343
+ }
344
+ }
345
+
346
+ // Main polling loop
347
+ async function startPolling(account: AccountData): Promise<never> {
348
+ const { baseUrl, token } = account;
349
+ let getUpdatesBuf = "";
350
+
351
+ // Load sync state
352
+ try {
353
+ if (fs.existsSync(SYNC_BUF_FILE)) {
354
+ getUpdatesBuf = fs.readFileSync(SYNC_BUF_FILE, "utf-8");
355
+ if (getUpdatesBuf) {
356
+ log(`Recovered sync state from ${SYNC_BUF_FILE}`);
357
+ }
358
+ }
359
+ } catch (err) {
360
+ logError(`Failed to load sync state: ${String(err)}`);
361
+ }
362
+
363
+ log("Starting WeChat message polling loop...");
364
+ log("Press Ctrl+C to stop");
365
+
366
+ const contextTokenCache = new Map<string, string>();
367
+
368
+ while (true) {
369
+ try {
370
+ const resp = await getUpdates(baseUrl, token, getUpdatesBuf);
371
+
372
+ const isError =
373
+ (resp.ret !== undefined && resp.ret !== 0) ||
374
+ (resp.errcode !== undefined && resp.errcode !== 0);
375
+
376
+ if (isError) {
377
+ logError(
378
+ `getUpdates failed: ret=${resp.ret} errcode=${resp.errcode} errmsg=${resp.errmsg ?? ""}`,
379
+ );
380
+ await new Promise((resolve) => setTimeout(resolve, 2000));
381
+ continue;
382
+ }
383
+
384
+ // Save sync state
385
+ if (resp.get_updates_buf) {
386
+ getUpdatesBuf = resp.get_updates_buf;
387
+ try {
388
+ fs.writeFileSync(SYNC_BUF_FILE, getUpdatesBuf, "utf-8");
389
+ } catch (err) {
390
+ logError(`Failed to persist sync state: ${String(err)}`);
391
+ }
392
+ }
393
+
394
+ // Process messages
395
+ for (const msg of resp.msgs ?? []) {
396
+ if (msg.message_type !== MSG_TYPE_USER) {
397
+ continue;
398
+ }
399
+
400
+ const text = extractTextFromMessage(msg);
401
+ if (!text) {
402
+ continue;
403
+ }
404
+
405
+ const senderId = msg.from_user_id ?? "unknown";
406
+ const messageKey = buildMessageKey(msg);
407
+
408
+ if (!rememberMessage(messageKey)) {
409
+ continue;
410
+ }
411
+
412
+ // Cache context token for replies
413
+ if (msg.context_token) {
414
+ contextTokenCache.set(senderId, msg.context_token);
415
+ }
416
+
417
+ log(`📨 收到消息 from ${senderId}: ${text.slice(0, 50)}${text.length > 50 ? "..." : ""}`);
418
+
419
+ // Get response from Claude
420
+ try {
421
+ const response = await getClaudeResponse(text, senderId);
422
+ log(`📤 发送回复 to ${senderId}: ${response.slice(0, 50)}${response.length > 50 ? "..." : ""}`);
423
+
424
+ const contextToken = contextTokenCache.get(senderId) || "";
425
+ await sendTextMessage(baseUrl, token, senderId, response, contextToken);
426
+ } catch (err) {
427
+ logError(`Failed to get/send response: ${String(err)}`);
428
+ // Send error message to user
429
+ try {
430
+ const contextToken = contextTokenCache.get(senderId) || "";
431
+ await sendTextMessage(
432
+ baseUrl,
433
+ token,
434
+ senderId,
435
+ "抱歉,我遇到了一些问题,请稍后再试。",
436
+ contextToken,
437
+ );
438
+ } catch {
439
+ // Ignore
440
+ }
441
+ }
442
+ }
443
+ } catch (err) {
444
+ logError(`Polling error: ${String(err)}`);
445
+ await new Promise((resolve) => setTimeout(resolve, 2000));
446
+ }
447
+ }
448
+ }
449
+
450
+ // Main function
451
+ async function main() {
452
+ log("=== WeChat + Claude 独立机器人 ===");
453
+ log("");
454
+
455
+ // Load WeChat credentials
456
+ log(`正在加载微信凭据: ${CREDENTIALS_FILE}`);
457
+ const account = loadCredentials();
458
+ if (!account) {
459
+ logError("无法加载微信凭据,请先运行: bun run setup");
460
+ process.exit(1);
461
+ }
462
+ log(`✓ 微信账号: ${account.accountId}`);
463
+
464
+ // Initialize Claude API
465
+ log("");
466
+ log("正在初始化 Claude API...");
467
+ if (!initClaude()) {
468
+ logError("Claude API 初始化失败");
469
+ process.exit(1);
470
+ }
471
+
472
+ log("");
473
+ log("✓ 所有初始化完成!");
474
+ log("");
475
+
476
+ // Start polling
477
+ await startPolling(account);
478
+ }
479
+
480
+ main().catch((err) => {
481
+ logError(`Fatal: ${String(err)}`);
482
+ process.exit(1);
483
+ });