codeksei 0.1.0 → 0.1.1

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 (68) hide show
  1. package/LICENSE +661 -661
  2. package/README.en.md +109 -47
  3. package/README.md +79 -58
  4. package/bin/cyberboss.js +1 -1
  5. package/package.json +86 -86
  6. package/scripts/open_shared_wechat_thread.sh +77 -77
  7. package/scripts/open_wechat_thread.sh +108 -108
  8. package/scripts/shared-common.js +144 -144
  9. package/scripts/shared-open.js +14 -14
  10. package/scripts/shared-start.js +5 -5
  11. package/scripts/shared-status.js +27 -27
  12. package/scripts/show_shared_status.sh +45 -45
  13. package/scripts/start_shared_app_server.sh +52 -52
  14. package/scripts/start_shared_wechat.sh +94 -94
  15. package/scripts/timeline-screenshot.sh +14 -14
  16. package/src/adapters/channel/weixin/account-store.js +99 -99
  17. package/src/adapters/channel/weixin/api-v2.js +50 -50
  18. package/src/adapters/channel/weixin/api.js +169 -169
  19. package/src/adapters/channel/weixin/context-token-store.js +84 -84
  20. package/src/adapters/channel/weixin/index.js +618 -604
  21. package/src/adapters/channel/weixin/legacy.js +579 -566
  22. package/src/adapters/channel/weixin/media-mime.js +22 -22
  23. package/src/adapters/channel/weixin/media-receive.js +370 -370
  24. package/src/adapters/channel/weixin/media-send.js +102 -102
  25. package/src/adapters/channel/weixin/message-utils-v2.js +282 -282
  26. package/src/adapters/channel/weixin/message-utils.js +199 -199
  27. package/src/adapters/channel/weixin/redact.js +41 -41
  28. package/src/adapters/channel/weixin/reminder-queue-store.js +101 -101
  29. package/src/adapters/channel/weixin/sync-buffer-store.js +35 -35
  30. package/src/adapters/runtime/codex/events.js +215 -215
  31. package/src/adapters/runtime/codex/index.js +109 -104
  32. package/src/adapters/runtime/codex/message-utils.js +95 -95
  33. package/src/adapters/runtime/codex/model-catalog.js +106 -106
  34. package/src/adapters/runtime/codex/protocol-leak-monitor.js +75 -75
  35. package/src/adapters/runtime/codex/rpc-client.js +339 -339
  36. package/src/adapters/runtime/codex/session-store.js +286 -286
  37. package/src/app/channel-send-file-cli.js +57 -57
  38. package/src/app/diary-write-cli.js +236 -88
  39. package/src/app/note-sync-cli.js +2 -2
  40. package/src/app/reminder-write-cli.js +215 -210
  41. package/src/app/review-cli.js +7 -5
  42. package/src/app/system-checkin-poller.js +64 -64
  43. package/src/app/system-send-cli.js +129 -129
  44. package/src/app/timeline-event-cli.js +28 -25
  45. package/src/app/timeline-screenshot-cli.js +103 -100
  46. package/src/core/app.js +1763 -1763
  47. package/src/core/branding.js +2 -1
  48. package/src/core/command-registry.js +381 -369
  49. package/src/core/config.js +30 -14
  50. package/src/core/default-targets.js +163 -163
  51. package/src/core/durable-note-schema.js +9 -8
  52. package/src/core/instructions-template.js +17 -16
  53. package/src/core/note-sync.js +8 -7
  54. package/src/core/path-utils.js +54 -0
  55. package/src/core/project-radar.js +11 -10
  56. package/src/core/review.js +48 -50
  57. package/src/core/stream-delivery.js +1162 -983
  58. package/src/core/system-message-dispatcher.js +68 -68
  59. package/src/core/system-message-queue-store.js +128 -128
  60. package/src/core/thread-state-store.js +96 -96
  61. package/src/core/timeline-screenshot-queue-store.js +134 -134
  62. package/src/core/timezone.js +436 -0
  63. package/src/core/workspace-bootstrap.js +9 -1
  64. package/src/index.js +148 -146
  65. package/src/integrations/timeline/index.js +130 -74
  66. package/src/integrations/timeline/state-sync.js +240 -0
  67. package/templates/weixin-instructions.md +12 -38
  68. package/templates/weixin-operations.md +29 -31
@@ -1,605 +1,619 @@
1
- const crypto = require("crypto");
2
- const { listWeixinAccounts, resolveSelectedAccount } = require("./account-store");
3
- const { loadPersistedContextTokens, persistContextToken } = require("./context-token-store");
4
- const { runV2LoginFlow } = require("./login-v2");
5
- const {
6
- getConfigV2,
7
- getUpdatesV2,
8
- sendTextV2,
9
- sendTypingV2,
10
- } = require("./api-v2");
11
- const { createLegacyWeixinChannelAdapter } = require("./legacy");
12
- const { createInboundFilter } = require("./message-utils-v2");
13
- const { sendWeixinMediaFile } = require("./media-send");
14
- const { loadSyncBuffer, saveSyncBuffer } = require("./sync-buffer-store");
15
-
16
- const LONG_POLL_TIMEOUT_MS = 35_000;
17
- const MAX_WEIXIN_CHUNK = 3800;
18
- const SEND_MESSAGE_CHUNK_INTERVAL_MS = 350;
19
- const WEIXIN_SEND_CHUNK_LIMIT = 80;
20
- const WEIXIN_MAX_DELIVERY_MESSAGES = 10;
21
- const SEND_RETRY_DELAYS_MS = [900, 1800];
22
-
23
- function createWeixinChannelAdapter(config) {
24
- const variant = normalizeAdapterVariant(config.weixinAdapterVariant);
25
- if (variant === "legacy") {
26
- return createLegacyWeixinChannelAdapter(config);
27
- }
28
-
29
- let selectedAccount = null;
30
- let contextTokenCache = null;
31
- const inboundFilter = createInboundFilter();
32
-
33
- function ensureAccount() {
34
- if (!selectedAccount) {
35
- selectedAccount = resolveSelectedAccount(config);
36
- contextTokenCache = loadPersistedContextTokens(config, selectedAccount.accountId);
37
- }
38
- return selectedAccount;
39
- }
40
-
41
- function ensureContextTokenCache() {
42
- if (!contextTokenCache) {
43
- const account = ensureAccount();
44
- contextTokenCache = loadPersistedContextTokens(config, account.accountId);
45
- }
46
- return contextTokenCache;
47
- }
48
-
49
- function rememberContextToken(userId, contextToken) {
50
- const account = ensureAccount();
51
- const normalizedUserId = typeof userId === "string" ? userId.trim() : "";
52
- const normalizedToken = typeof contextToken === "string" ? contextToken.trim() : "";
53
- if (!normalizedUserId || !normalizedToken) {
54
- return "";
55
- }
56
- contextTokenCache = persistContextToken(config, account.accountId, normalizedUserId, normalizedToken);
57
- return normalizedToken;
58
- }
59
-
60
- function resolveContextToken(userId, explicitToken = "") {
61
- const normalizedExplicitToken = typeof explicitToken === "string" ? explicitToken.trim() : "";
62
- if (normalizedExplicitToken) {
63
- return normalizedExplicitToken;
64
- }
65
- const normalizedUserId = typeof userId === "string" ? userId.trim() : "";
66
- if (!normalizedUserId) {
67
- return "";
68
- }
69
- return ensureContextTokenCache()[normalizedUserId] || "";
70
- }
71
-
72
- function sendTextChunks({ userId, text, contextToken = "", preserveBlock = false, trace = null }) {
73
- const account = ensureAccount();
74
- const resolvedToken = resolveContextToken(userId, contextToken);
75
- if (!resolvedToken) {
76
- throw new Error(`缺少 context_token,无法回复用户 ${userId}`);
77
- }
78
- const content = String(text || "");
79
- if (!content.trim()) {
80
- return Promise.resolve();
81
- }
82
- const sendChunks = preserveBlock
83
- ? splitUtf8(compactPlainTextForWeixin(content) || "已完成。", MAX_WEIXIN_CHUNK)
84
- : packChunksForWeixinDelivery(
85
- chunkReplyTextForWeixin(content, WEIXIN_SEND_CHUNK_LIMIT).length
86
- ? chunkReplyTextForWeixin(content, WEIXIN_SEND_CHUNK_LIMIT)
87
- : ["已完成。"],
88
- WEIXIN_MAX_DELIVERY_MESSAGES,
89
- MAX_WEIXIN_CHUNK
90
- );
91
- const traceContext = buildWeixinTraceContext(trace, {
92
- enabled: config.weixinDeliveryTrace,
93
- origin: "adapter.sendText",
94
- variant: "v2",
95
- preserveBlock,
96
- chunkTotal: sendChunks.length,
97
- });
98
- return sendChunks.reduce((promise, chunk, index) => promise
99
- .then(() => {
100
- const compactChunk = compactPlainTextForWeixin(chunk) || "已完成。";
101
- const clientId = `cb-${crypto.randomUUID()}`;
102
- return sendV2TextChunk({
103
- baseUrl: account.baseUrl,
104
- token: account.token,
105
- routeTag: account.routeTag,
106
- clientVersion: config.weixinProtocolClientVersion,
107
- toUserId: userId,
108
- text: compactChunk,
109
- contextToken: resolvedToken,
110
- clientId,
111
- trace: {
112
- ...traceContext,
113
- chunkIndex: index + 1,
114
- chars: compactChunk.length,
115
- textHash: hashTraceText(compactChunk),
116
- clientId,
117
- },
118
- });
119
- })
120
- .then(() => {
121
- if (index < sendChunks.length - 1) {
122
- return sleep(SEND_MESSAGE_CHUNK_INTERVAL_MS);
123
- }
124
- return null;
125
- }), Promise.resolve());
126
- }
127
-
128
- return {
129
- describe() {
130
- return {
131
- id: "weixin",
132
- variant: "v2",
133
- kind: "channel",
134
- stateDir: config.stateDir,
135
- baseUrl: config.weixinBaseUrl,
136
- accountsDir: config.accountsDir,
137
- syncBufferDir: config.syncBufferDir,
138
- protocolClientVersion: config.weixinProtocolClientVersion,
139
- routeTag: config.weixinRouteTag,
140
- };
141
- },
142
- async login() {
143
- await runV2LoginFlow(config);
144
- },
145
- printAccounts() {
146
- const accounts = listWeixinAccounts(config);
147
- if (!accounts.length) {
148
- console.log("当前没有已保存的微信账号。先执行 `npm run login`。");
149
- return;
150
- }
151
- console.log("已保存账号:");
152
- for (const account of accounts) {
153
- console.log(`- ${account.accountId}`);
154
- console.log(` userId: ${account.userId || "(unknown)"}`);
155
- console.log(` baseUrl: ${account.baseUrl || config.weixinBaseUrl}`);
156
- if (account.routeTag) {
157
- console.log(` routeTag: ${account.routeTag}`);
158
- }
159
- console.log(` savedAt: ${account.savedAt || "(unknown)"}`);
160
- }
161
- },
162
- resolveAccount() {
163
- return ensureAccount();
164
- },
165
- getKnownContextTokens() {
166
- return { ...ensureContextTokenCache() };
167
- },
168
- loadSyncBuffer() {
169
- const account = ensureAccount();
170
- return loadSyncBuffer(config, account.accountId);
171
- },
172
- saveSyncBuffer(buffer) {
173
- const account = ensureAccount();
174
- saveSyncBuffer(config, account.accountId, buffer);
175
- },
176
- rememberContextToken,
177
- async getUpdates({ syncBuffer = "", timeoutMs = LONG_POLL_TIMEOUT_MS } = {}) {
178
- const account = ensureAccount();
179
- const response = await getUpdatesV2({
180
- baseUrl: account.baseUrl,
181
- token: account.token,
182
- getUpdatesBuf: syncBuffer,
183
- timeoutMs,
184
- routeTag: account.routeTag,
185
- clientVersion: config.weixinProtocolClientVersion,
186
- });
187
- if (typeof response?.get_updates_buf === "string" && response.get_updates_buf.trim()) {
188
- this.saveSyncBuffer(response.get_updates_buf.trim());
189
- }
190
- const messages = Array.isArray(response?.msgs) ? response.msgs : [];
191
- for (const message of messages) {
192
- const userId = typeof message?.from_user_id === "string" ? message.from_user_id.trim() : "";
193
- const contextToken = typeof message?.context_token === "string" ? message.context_token.trim() : "";
194
- if (userId && contextToken) {
195
- rememberContextToken(userId, contextToken);
196
- }
197
- }
198
- return response;
199
- },
200
- normalizeIncomingMessage(message) {
201
- const account = ensureAccount();
202
- return inboundFilter.normalize(message, config, account.accountId);
203
- },
204
- async sendText({ userId, text, contextToken = "", preserveBlock = false, trace = null }) {
205
- await sendTextChunks({ userId, text, contextToken, preserveBlock, trace });
206
- },
207
- async sendTyping({ userId, status = 1, contextToken = "" }) {
208
- const account = ensureAccount();
209
- const resolvedToken = resolveContextToken(userId, contextToken);
210
- if (!resolvedToken) {
211
- return;
212
- }
213
- const configResponse = await getConfigV2({
214
- baseUrl: account.baseUrl,
215
- token: account.token,
216
- routeTag: account.routeTag,
217
- clientVersion: config.weixinProtocolClientVersion,
218
- ilinkUserId: userId,
219
- contextToken: resolvedToken,
220
- }).catch(() => null);
221
- const typingTicket = typeof configResponse?.typing_ticket === "string"
222
- ? configResponse.typing_ticket.trim()
223
- : "";
224
- if (!typingTicket) {
225
- return;
226
- }
227
- await sendTypingV2({
228
- baseUrl: account.baseUrl,
229
- token: account.token,
230
- routeTag: account.routeTag,
231
- clientVersion: config.weixinProtocolClientVersion,
232
- body: {
233
- ilink_user_id: userId,
234
- typing_ticket: typingTicket,
235
- status,
236
- },
237
- });
238
- },
239
- async sendFile({ userId, filePath, contextToken = "" }) {
240
- const account = ensureAccount();
241
- const resolvedToken = resolveContextToken(userId, contextToken);
242
- if (!resolvedToken) {
243
- throw new Error(`缺少 context_token,无法发送文件给用户 ${userId}`);
244
- }
245
- // Text polling/sending lives on the v2 stack, but attachments intentionally
246
- // stay on the legacy media API. The original repo never moved sendFile onto
247
- // v2, and live timeline screenshot failures ("getUploadUrl returned no
248
- // upload_param") only appeared after we forced media onto the v2 headers.
249
- // Keep this split explicit so future "cleanup" work does not silently route
250
- // screenshots/files back onto the broken stack.
251
- return sendWeixinMediaFile({
252
- filePath,
253
- to: userId,
254
- contextToken: resolvedToken,
255
- baseUrl: account.baseUrl,
256
- token: account.token,
257
- cdnBaseUrl: config.weixinCdnBaseUrl,
258
- apiVariant: "legacy",
259
- routeTag: account.routeTag,
260
- clientVersion: config.weixinProtocolClientVersion,
261
- });
262
- },
263
- };
264
- }
265
-
266
- function normalizeAdapterVariant(value) {
267
- const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
268
- return normalized === "legacy" ? "legacy" : "v2";
269
- }
270
-
271
- function splitUtf8(text, maxRunes) {
272
- const runes = Array.from(String(text || ""));
273
- if (!runes.length || runes.length <= maxRunes) {
274
- return [String(text || "")];
275
- }
276
- const chunks = [];
277
- while (runes.length) {
278
- chunks.push(runes.splice(0, maxRunes).join(""));
279
- }
280
- return chunks;
281
- }
282
-
283
- function compactPlainTextForWeixin(text) {
284
- const normalized = String(text || "").replace(/\r\n/g, "\n");
285
- return trimOuterBlankLines(normalized.replace(/\n\s*\n+/g, "\n"));
286
- }
287
-
288
- function chunkReplyText(text, limit = 3500) {
289
- const normalized = trimOuterBlankLines(String(text || "").replace(/\r\n/g, "\n"));
290
- if (!normalized.trim()) {
291
- return [];
292
- }
293
-
294
- const chunks = [];
295
- let remaining = normalized;
296
- while (remaining.length > limit) {
297
- const candidate = remaining.slice(0, limit);
298
- const splitIndex = Math.max(
299
- candidate.lastIndexOf("\n\n"),
300
- candidate.lastIndexOf("\n"),
301
- candidate.lastIndexOf(""),
302
- candidate.lastIndexOf(". "),
303
- candidate.lastIndexOf(" ")
304
- );
305
- const cut = splitIndex > limit * 0.4 ? splitIndex + (candidate[splitIndex] === "\n" ? 0 : 1) : limit;
306
- const chunk = trimOuterBlankLines(remaining.slice(0, cut));
307
- if (chunk.trim()) {
308
- chunks.push(chunk);
309
- }
310
- remaining = trimOuterBlankLines(remaining.slice(cut));
311
- }
312
- if (remaining) {
313
- chunks.push(remaining);
314
- }
315
- return chunks.filter(Boolean);
316
- }
317
-
318
- function chunkReplyTextForWeixin(text, limit = 80) {
319
- const normalized = trimOuterBlankLines(String(text || "").replace(/\r\n/g, "\n"));
320
- if (!normalized.trim()) {
321
- return [];
322
- }
323
-
324
- const boundaries = collectStreamingBoundaries(normalized);
325
- if (!boundaries.length) {
326
- return chunkReplyText(normalized, limit);
327
- }
328
-
329
- const units = [];
330
- let start = 0;
331
- for (const boundary of boundaries) {
332
- if (boundary <= start) {
333
- continue;
334
- }
335
- const unit = trimOuterBlankLines(normalized.slice(start, boundary));
336
- if (unit) {
337
- units.push(unit);
338
- }
339
- start = boundary;
340
- }
341
-
342
- const tail = trimOuterBlankLines(normalized.slice(start));
343
- if (tail) {
344
- units.push(tail);
345
- }
346
-
347
- if (!units.length) {
348
- return chunkReplyText(normalized, limit);
349
- }
350
-
351
- const chunks = [];
352
- for (const unit of units) {
353
- if (unit.length <= limit) {
354
- chunks.push(unit);
355
- continue;
356
- }
357
- chunks.push(...chunkReplyText(unit, limit));
358
- }
359
- return chunks.filter(Boolean);
360
- }
361
-
362
- function packChunksForWeixinDelivery(chunks, maxMessages = 10, maxChunkChars = 3800) {
363
- const normalizedChunks = Array.isArray(chunks)
364
- ? chunks.map((chunk) => compactPlainTextForWeixin(chunk)).filter(Boolean)
365
- : [];
366
- if (!normalizedChunks.length || normalizedChunks.length <= maxMessages) {
367
- return normalizedChunks;
368
- }
369
-
370
- const packed = normalizedChunks.slice(0, Math.max(0, maxMessages - 1));
371
- const tailChunks = normalizedChunks.slice(Math.max(0, maxMessages - 1));
372
- if (!tailChunks.length) {
373
- return packed;
374
- }
375
-
376
- const tailText = compactPlainTextForWeixin(tailChunks.join("\n")) || "已完成。";
377
- if (tailText.length <= maxChunkChars) {
378
- packed.push(tailText);
379
- return packed;
380
- }
381
-
382
- const tailHardChunks = splitUtf8(tailText, maxChunkChars);
383
- if (tailHardChunks.length === 1) {
384
- packed.push(tailHardChunks[0]);
385
- return packed;
386
- }
387
-
388
- const preserveCount = Math.max(0, maxMessages - tailHardChunks.length);
389
- const preserved = normalizedChunks.slice(0, preserveCount);
390
- const rebundledTail = normalizedChunks.slice(preserveCount);
391
- const groupedTail = [];
392
- let current = "";
393
- for (const chunk of rebundledTail) {
394
- const joined = current ? `${current}\n${chunk}` : chunk;
395
- if (current && joined.length > maxChunkChars) {
396
- groupedTail.push(current);
397
- current = chunk;
398
- continue;
399
- }
400
- current = joined;
401
- }
402
- if (current) {
403
- groupedTail.push(current);
404
- }
405
-
406
- const normalizedGroupedTail = groupedTail.map((item) => compactPlainTextForWeixin(item) || "已完成。");
407
- if (preserved.length + normalizedGroupedTail.length <= maxMessages) {
408
- return preserved.concat(normalizedGroupedTail);
409
- }
410
-
411
- // Never silently drop the tail of a long reply. If grouping by semantic
412
- // chunk boundaries still overflows the per-message budget, fall back to hard
413
- // UTF-8 splits of the already-joined tail so the full answer is still sent.
414
- return preserved.concat(tailHardChunks.slice(0, Math.max(1, maxMessages - preserved.length)));
415
- }
416
-
417
- function collectStreamingBoundaries(text) {
418
- const boundaries = new Set();
419
-
420
- const regex = /\n\s*\n+/g;
421
- let match = regex.exec(text);
422
- while (match) {
423
- boundaries.add(match.index + match[0].length);
424
- match = regex.exec(text);
425
- }
426
-
427
- const listRegex = /\n(?:(?:[-*])\s+|(?:\d+\.)\s+)/g;
428
- match = listRegex.exec(text);
429
- while (match) {
430
- boundaries.add(match.index + 1);
431
- match = listRegex.exec(text);
432
- }
433
-
434
- for (let index = 0; index < text.length; index += 1) {
435
- const char = text[index];
436
- if (!/[。!?!?]/.test(char)) {
437
- continue;
438
- }
439
-
440
- let end = index + 1;
441
- while (end < text.length && /["'”’))\]」』】]/.test(text[end])) {
442
- end += 1;
443
- }
444
- while (end < text.length && /[\t \n]/.test(text[end])) {
445
- end += 1;
446
- }
447
- boundaries.add(end);
448
- }
449
-
450
- return Array.from(boundaries).sort((left, right) => left - right);
451
- }
452
-
453
- async function sendTextChunkWithRetry(send, { trace = null } = {}) {
454
- let lastError = null;
455
- for (let attempt = 0; attempt <= SEND_RETRY_DELAYS_MS.length; attempt += 1) {
456
- const attemptNumber = attempt + 1;
457
- try {
458
- logWeixinSendTrace("attempt", {
459
- ...buildWeixinTraceContext(trace),
460
- attempt: attemptNumber,
461
- });
462
- const result = await send();
463
- logWeixinSendTrace("success", {
464
- ...buildWeixinTraceContext(trace),
465
- attempt: attemptNumber,
466
- });
467
- return result;
468
- } catch (error) {
469
- lastError = error;
470
- const retryable = isRetryableSendError(error);
471
- logWeixinSendTrace("error", {
472
- ...buildWeixinTraceContext(trace),
473
- attempt: attemptNumber,
474
- retryable,
475
- error: String(error?.message || error || ""),
476
- });
477
- if (!retryable || attempt >= SEND_RETRY_DELAYS_MS.length) {
478
- throw error;
479
- }
480
- await sleep(SEND_RETRY_DELAYS_MS[attempt]);
481
- }
482
- }
483
- throw lastError || new Error("sendText chunk failed");
484
- }
485
-
486
- function sendV2TextChunk({
487
- sendTextImpl = sendTextV2,
488
- baseUrl,
489
- token,
490
- routeTag = "",
491
- clientVersion = "",
492
- toUserId,
493
- text,
494
- contextToken,
495
- clientId = "",
496
- trace = null,
497
- }) {
498
- const stableClientId = String(clientId || "").trim() || `cb-${crypto.randomUUID()}`;
499
- return sendTextChunkWithRetry(
500
- () => sendTextImpl({
501
- baseUrl,
502
- token,
503
- routeTag,
504
- clientVersion,
505
- toUserId,
506
- text,
507
- contextToken,
508
- clientId: stableClientId,
509
- }),
510
- {
511
- trace: buildWeixinTraceContext(trace, {
512
- variant: "v2",
513
- clientId: stableClientId,
514
- chars: String(text || "").length,
515
- textHash: hashTraceText(text),
516
- }),
517
- }
518
- );
519
- }
520
-
521
- function isRetryableSendError(error) {
522
- const message = String(error?.message || error || "");
523
- // `ret=-2` is ambiguous in live WeChat delivery: the API can still return it
524
- // after the user-facing message has already landed. Retrying that chunk risks
525
- // duplicating the same assistant block in chat, which is worse than surfacing
526
- // one degraded turn locally and letting the operator re-send intentionally.
527
- return message.includes("AbortError")
528
- || message.includes("aborted")
529
- || message.includes("fetch failed")
530
- || message.includes("ECONNRESET")
531
- || message.includes("ETIMEDOUT")
532
- || /http 5\d\d/.test(message);
533
- }
534
-
535
- function buildWeixinTraceContext(trace, defaults = {}) {
536
- const normalizedTrace = normalizeTraceContext(trace);
537
- return {
538
- ...defaults,
539
- ...normalizedTrace,
540
- enabled: Boolean(normalizedTrace.enabled ?? defaults.enabled),
541
- traceId: normalizeTraceText(normalizedTrace.traceId)
542
- || normalizeTraceText(defaults.traceId)
543
- || `wx-${crypto.randomUUID().slice(0, 8)}`,
544
- };
545
- }
546
-
547
- function normalizeTraceContext(trace) {
548
- if (!trace || typeof trace !== "object") {
549
- return {};
550
- }
551
- return { ...trace };
552
- }
553
-
554
- function normalizeTraceText(value) {
555
- return typeof value === "string" ? value.trim() : "";
556
- }
557
-
558
- function logWeixinSendTrace(stage, trace) {
559
- if (!Boolean(trace?.enabled)) {
560
- return;
561
- }
562
- const parts = [
1
+ const crypto = require("crypto");
2
+ const { listWeixinAccounts, resolveSelectedAccount } = require("./account-store");
3
+ const { loadPersistedContextTokens, persistContextToken } = require("./context-token-store");
4
+ const { runV2LoginFlow } = require("./login-v2");
5
+ const {
6
+ getConfigV2,
7
+ getUpdatesV2,
8
+ sendTextV2,
9
+ sendTypingV2,
10
+ } = require("./api-v2");
11
+ const { createLegacyWeixinChannelAdapter } = require("./legacy");
12
+ const { createInboundFilter } = require("./message-utils-v2");
13
+ const { sendWeixinMediaFile } = require("./media-send");
14
+ const { loadSyncBuffer, saveSyncBuffer } = require("./sync-buffer-store");
15
+
16
+ const LONG_POLL_TIMEOUT_MS = 35_000;
17
+ const MAX_WEIXIN_CHUNK = 3800;
18
+ const SEND_MESSAGE_CHUNK_INTERVAL_MS = 350;
19
+ const WEIXIN_SEND_CHUNK_LIMIT = 80;
20
+ const WEIXIN_MAX_DELIVERY_MESSAGES = 10;
21
+ const SEND_RETRY_DELAYS_MS = [900, 1800];
22
+ const AMBIGUOUS_SEND_RETRY_DELAYS_MS = [1200];
23
+
24
+ function createWeixinChannelAdapter(config) {
25
+ const variant = normalizeAdapterVariant(config.weixinAdapterVariant);
26
+ if (variant === "legacy") {
27
+ return createLegacyWeixinChannelAdapter(config);
28
+ }
29
+
30
+ let selectedAccount = null;
31
+ let contextTokenCache = null;
32
+ const inboundFilter = createInboundFilter();
33
+
34
+ function ensureAccount() {
35
+ if (!selectedAccount) {
36
+ selectedAccount = resolveSelectedAccount(config);
37
+ contextTokenCache = loadPersistedContextTokens(config, selectedAccount.accountId);
38
+ }
39
+ return selectedAccount;
40
+ }
41
+
42
+ function ensureContextTokenCache() {
43
+ if (!contextTokenCache) {
44
+ const account = ensureAccount();
45
+ contextTokenCache = loadPersistedContextTokens(config, account.accountId);
46
+ }
47
+ return contextTokenCache;
48
+ }
49
+
50
+ function rememberContextToken(userId, contextToken) {
51
+ const account = ensureAccount();
52
+ const normalizedUserId = typeof userId === "string" ? userId.trim() : "";
53
+ const normalizedToken = typeof contextToken === "string" ? contextToken.trim() : "";
54
+ if (!normalizedUserId || !normalizedToken) {
55
+ return "";
56
+ }
57
+ contextTokenCache = persistContextToken(config, account.accountId, normalizedUserId, normalizedToken);
58
+ return normalizedToken;
59
+ }
60
+
61
+ function resolveContextToken(userId, explicitToken = "") {
62
+ const normalizedExplicitToken = typeof explicitToken === "string" ? explicitToken.trim() : "";
63
+ if (normalizedExplicitToken) {
64
+ return normalizedExplicitToken;
65
+ }
66
+ const normalizedUserId = typeof userId === "string" ? userId.trim() : "";
67
+ if (!normalizedUserId) {
68
+ return "";
69
+ }
70
+ return ensureContextTokenCache()[normalizedUserId] || "";
71
+ }
72
+
73
+ function sendTextChunks({ userId, text, contextToken = "", preserveBlock = false, trace = null }) {
74
+ const account = ensureAccount();
75
+ const resolvedToken = resolveContextToken(userId, contextToken);
76
+ if (!resolvedToken) {
77
+ throw new Error(`缺少 context_token,无法回复用户 ${userId}`);
78
+ }
79
+ const content = String(text || "");
80
+ if (!content.trim()) {
81
+ return Promise.resolve();
82
+ }
83
+ const sendChunks = preserveBlock
84
+ ? splitUtf8(compactPlainTextForWeixin(content) || "已完成。", MAX_WEIXIN_CHUNK)
85
+ : packChunksForWeixinDelivery(
86
+ chunkReplyTextForWeixin(content, WEIXIN_SEND_CHUNK_LIMIT).length
87
+ ? chunkReplyTextForWeixin(content, WEIXIN_SEND_CHUNK_LIMIT)
88
+ : ["已完成。"],
89
+ WEIXIN_MAX_DELIVERY_MESSAGES,
90
+ MAX_WEIXIN_CHUNK
91
+ );
92
+ const traceContext = buildWeixinTraceContext(trace, {
93
+ enabled: config.weixinDeliveryTrace,
94
+ origin: "adapter.sendText",
95
+ variant: "v2",
96
+ preserveBlock,
97
+ chunkTotal: sendChunks.length,
98
+ });
99
+ return sendChunks.reduce((promise, chunk, index) => promise
100
+ .then(() => {
101
+ const compactChunk = compactPlainTextForWeixin(chunk) || "已完成。";
102
+ const clientId = `cb-${crypto.randomUUID()}`;
103
+ return sendV2TextChunk({
104
+ baseUrl: account.baseUrl,
105
+ token: account.token,
106
+ routeTag: account.routeTag,
107
+ clientVersion: config.weixinProtocolClientVersion,
108
+ toUserId: userId,
109
+ text: compactChunk,
110
+ contextToken: resolvedToken,
111
+ clientId,
112
+ trace: {
113
+ ...traceContext,
114
+ chunkIndex: index + 1,
115
+ chars: compactChunk.length,
116
+ textHash: hashTraceText(compactChunk),
117
+ clientId,
118
+ },
119
+ });
120
+ })
121
+ .then(() => {
122
+ if (index < sendChunks.length - 1) {
123
+ return sleep(SEND_MESSAGE_CHUNK_INTERVAL_MS);
124
+ }
125
+ return null;
126
+ }), Promise.resolve());
127
+ }
128
+
129
+ return {
130
+ describe() {
131
+ return {
132
+ id: "weixin",
133
+ variant: "v2",
134
+ kind: "channel",
135
+ stateDir: config.stateDir,
136
+ baseUrl: config.weixinBaseUrl,
137
+ accountsDir: config.accountsDir,
138
+ syncBufferDir: config.syncBufferDir,
139
+ protocolClientVersion: config.weixinProtocolClientVersion,
140
+ routeTag: config.weixinRouteTag,
141
+ };
142
+ },
143
+ async login() {
144
+ await runV2LoginFlow(config);
145
+ },
146
+ printAccounts() {
147
+ const accounts = listWeixinAccounts(config);
148
+ if (!accounts.length) {
149
+ console.log("当前没有已保存的微信账号。先执行 `npm run login`。");
150
+ return;
151
+ }
152
+ console.log("已保存账号:");
153
+ for (const account of accounts) {
154
+ console.log(`- ${account.accountId}`);
155
+ console.log(` userId: ${account.userId || "(unknown)"}`);
156
+ console.log(` baseUrl: ${account.baseUrl || config.weixinBaseUrl}`);
157
+ if (account.routeTag) {
158
+ console.log(` routeTag: ${account.routeTag}`);
159
+ }
160
+ console.log(` savedAt: ${account.savedAt || "(unknown)"}`);
161
+ }
162
+ },
163
+ resolveAccount() {
164
+ return ensureAccount();
165
+ },
166
+ getKnownContextTokens() {
167
+ return { ...ensureContextTokenCache() };
168
+ },
169
+ loadSyncBuffer() {
170
+ const account = ensureAccount();
171
+ return loadSyncBuffer(config, account.accountId);
172
+ },
173
+ saveSyncBuffer(buffer) {
174
+ const account = ensureAccount();
175
+ saveSyncBuffer(config, account.accountId, buffer);
176
+ },
177
+ rememberContextToken,
178
+ async getUpdates({ syncBuffer = "", timeoutMs = LONG_POLL_TIMEOUT_MS } = {}) {
179
+ const account = ensureAccount();
180
+ const response = await getUpdatesV2({
181
+ baseUrl: account.baseUrl,
182
+ token: account.token,
183
+ getUpdatesBuf: syncBuffer,
184
+ timeoutMs,
185
+ routeTag: account.routeTag,
186
+ clientVersion: config.weixinProtocolClientVersion,
187
+ });
188
+ if (typeof response?.get_updates_buf === "string" && response.get_updates_buf.trim()) {
189
+ this.saveSyncBuffer(response.get_updates_buf.trim());
190
+ }
191
+ const messages = Array.isArray(response?.msgs) ? response.msgs : [];
192
+ for (const message of messages) {
193
+ const userId = typeof message?.from_user_id === "string" ? message.from_user_id.trim() : "";
194
+ const contextToken = typeof message?.context_token === "string" ? message.context_token.trim() : "";
195
+ if (userId && contextToken) {
196
+ rememberContextToken(userId, contextToken);
197
+ }
198
+ }
199
+ return response;
200
+ },
201
+ normalizeIncomingMessage(message) {
202
+ const account = ensureAccount();
203
+ return inboundFilter.normalize(message, config, account.accountId);
204
+ },
205
+ async sendText({ userId, text, contextToken = "", preserveBlock = false, trace = null }) {
206
+ await sendTextChunks({ userId, text, contextToken, preserveBlock, trace });
207
+ },
208
+ async sendTyping({ userId, status = 1, contextToken = "" }) {
209
+ const account = ensureAccount();
210
+ const resolvedToken = resolveContextToken(userId, contextToken);
211
+ if (!resolvedToken) {
212
+ return;
213
+ }
214
+ const configResponse = await getConfigV2({
215
+ baseUrl: account.baseUrl,
216
+ token: account.token,
217
+ routeTag: account.routeTag,
218
+ clientVersion: config.weixinProtocolClientVersion,
219
+ ilinkUserId: userId,
220
+ contextToken: resolvedToken,
221
+ }).catch(() => null);
222
+ const typingTicket = typeof configResponse?.typing_ticket === "string"
223
+ ? configResponse.typing_ticket.trim()
224
+ : "";
225
+ if (!typingTicket) {
226
+ return;
227
+ }
228
+ await sendTypingV2({
229
+ baseUrl: account.baseUrl,
230
+ token: account.token,
231
+ routeTag: account.routeTag,
232
+ clientVersion: config.weixinProtocolClientVersion,
233
+ body: {
234
+ ilink_user_id: userId,
235
+ typing_ticket: typingTicket,
236
+ status,
237
+ },
238
+ });
239
+ },
240
+ async sendFile({ userId, filePath, contextToken = "" }) {
241
+ const account = ensureAccount();
242
+ const resolvedToken = resolveContextToken(userId, contextToken);
243
+ if (!resolvedToken) {
244
+ throw new Error(`缺少 context_token,无法发送文件给用户 ${userId}`);
245
+ }
246
+ // Text polling/sending lives on the v2 stack, but attachments intentionally
247
+ // stay on the legacy media API. The original repo never moved sendFile onto
248
+ // v2, and live timeline screenshot failures ("getUploadUrl returned no
249
+ // upload_param") only appeared after we forced media onto the v2 headers.
250
+ // Keep this split explicit so future "cleanup" work does not silently route
251
+ // screenshots/files back onto the broken stack.
252
+ return sendWeixinMediaFile({
253
+ filePath,
254
+ to: userId,
255
+ contextToken: resolvedToken,
256
+ baseUrl: account.baseUrl,
257
+ token: account.token,
258
+ cdnBaseUrl: config.weixinCdnBaseUrl,
259
+ apiVariant: "legacy",
260
+ routeTag: account.routeTag,
261
+ clientVersion: config.weixinProtocolClientVersion,
262
+ });
263
+ },
264
+ };
265
+ }
266
+
267
+ function normalizeAdapterVariant(value) {
268
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
269
+ return normalized === "legacy" ? "legacy" : "v2";
270
+ }
271
+
272
+ function splitUtf8(text, maxRunes) {
273
+ const runes = Array.from(String(text || ""));
274
+ if (!runes.length || runes.length <= maxRunes) {
275
+ return [String(text || "")];
276
+ }
277
+ const chunks = [];
278
+ while (runes.length) {
279
+ chunks.push(runes.splice(0, maxRunes).join(""));
280
+ }
281
+ return chunks;
282
+ }
283
+
284
+ function compactPlainTextForWeixin(text) {
285
+ const normalized = String(text || "").replace(/\r\n/g, "\n");
286
+ return trimOuterBlankLines(normalized.replace(/\n\s*\n+/g, "\n"));
287
+ }
288
+
289
+ function chunkReplyText(text, limit = 3500) {
290
+ const normalized = trimOuterBlankLines(String(text || "").replace(/\r\n/g, "\n"));
291
+ if (!normalized.trim()) {
292
+ return [];
293
+ }
294
+
295
+ const chunks = [];
296
+ let remaining = normalized;
297
+ while (remaining.length > limit) {
298
+ const candidate = remaining.slice(0, limit);
299
+ const splitIndex = Math.max(
300
+ candidate.lastIndexOf("\n\n"),
301
+ candidate.lastIndexOf("\n"),
302
+ candidate.lastIndexOf(""),
303
+ candidate.lastIndexOf(". "),
304
+ candidate.lastIndexOf(" ")
305
+ );
306
+ const cut = splitIndex > limit * 0.4 ? splitIndex + (candidate[splitIndex] === "\n" ? 0 : 1) : limit;
307
+ const chunk = trimOuterBlankLines(remaining.slice(0, cut));
308
+ if (chunk.trim()) {
309
+ chunks.push(chunk);
310
+ }
311
+ remaining = trimOuterBlankLines(remaining.slice(cut));
312
+ }
313
+ if (remaining) {
314
+ chunks.push(remaining);
315
+ }
316
+ return chunks.filter(Boolean);
317
+ }
318
+
319
+ function chunkReplyTextForWeixin(text, limit = 80) {
320
+ const normalized = trimOuterBlankLines(String(text || "").replace(/\r\n/g, "\n"));
321
+ if (!normalized.trim()) {
322
+ return [];
323
+ }
324
+
325
+ const boundaries = collectStreamingBoundaries(normalized);
326
+ if (!boundaries.length) {
327
+ return chunkReplyText(normalized, limit);
328
+ }
329
+
330
+ const units = [];
331
+ let start = 0;
332
+ for (const boundary of boundaries) {
333
+ if (boundary <= start) {
334
+ continue;
335
+ }
336
+ const unit = trimOuterBlankLines(normalized.slice(start, boundary));
337
+ if (unit) {
338
+ units.push(unit);
339
+ }
340
+ start = boundary;
341
+ }
342
+
343
+ const tail = trimOuterBlankLines(normalized.slice(start));
344
+ if (tail) {
345
+ units.push(tail);
346
+ }
347
+
348
+ if (!units.length) {
349
+ return chunkReplyText(normalized, limit);
350
+ }
351
+
352
+ const chunks = [];
353
+ for (const unit of units) {
354
+ if (unit.length <= limit) {
355
+ chunks.push(unit);
356
+ continue;
357
+ }
358
+ chunks.push(...chunkReplyText(unit, limit));
359
+ }
360
+ return chunks.filter(Boolean);
361
+ }
362
+
363
+ function packChunksForWeixinDelivery(chunks, maxMessages = 10, maxChunkChars = 3800) {
364
+ const normalizedChunks = Array.isArray(chunks)
365
+ ? chunks.map((chunk) => compactPlainTextForWeixin(chunk)).filter(Boolean)
366
+ : [];
367
+ if (!normalizedChunks.length) {
368
+ return normalizedChunks;
369
+ }
370
+
371
+ const groupedChunks = groupChunksWithinBudget(normalizedChunks, maxChunkChars);
372
+ if (groupedChunks.length <= maxMessages) {
373
+ return groupedChunks;
374
+ }
375
+
376
+ const fullText = compactPlainTextForWeixin(normalizedChunks.join("\n")) || "已完成。";
377
+ const hardChunks = splitUtf8(fullText, maxChunkChars);
378
+ if (hardChunks.length <= maxMessages) {
379
+ return hardChunks;
380
+ }
381
+
382
+ // `maxMessages` is only a spam guard. If the full reply still needs more
383
+ // chunks at the hard per-message budget, prefer complete delivery over
384
+ // silently dropping the tail.
385
+ return hardChunks;
386
+ }
387
+
388
+ function groupChunksWithinBudget(chunks, maxChunkChars) {
389
+ const grouped = [];
390
+ let current = "";
391
+
392
+ for (const rawChunk of Array.isArray(chunks) ? chunks : []) {
393
+ const normalizedChunk = compactPlainTextForWeixin(rawChunk);
394
+ if (!normalizedChunk) {
395
+ continue;
396
+ }
397
+
398
+ const units = normalizedChunk.length > maxChunkChars
399
+ ? splitUtf8(normalizedChunk, maxChunkChars)
400
+ : [normalizedChunk];
401
+
402
+ for (const unit of units) {
403
+ if (!current) {
404
+ current = unit;
405
+ continue;
406
+ }
407
+ const joined = `${current}\n${unit}`;
408
+ if (joined.length > maxChunkChars) {
409
+ grouped.push(current);
410
+ current = unit;
411
+ continue;
412
+ }
413
+ current = joined;
414
+ }
415
+ }
416
+
417
+ if (current) {
418
+ grouped.push(current);
419
+ }
420
+ return grouped;
421
+ }
422
+
423
+ function collectStreamingBoundaries(text) {
424
+ const boundaries = new Set();
425
+
426
+ const regex = /\n\s*\n+/g;
427
+ let match = regex.exec(text);
428
+ while (match) {
429
+ boundaries.add(match.index + match[0].length);
430
+ match = regex.exec(text);
431
+ }
432
+
433
+ const listRegex = /\n(?:(?:[-*])\s+|(?:\d+\.)\s+)/g;
434
+ match = listRegex.exec(text);
435
+ while (match) {
436
+ boundaries.add(match.index + 1);
437
+ match = listRegex.exec(text);
438
+ }
439
+
440
+ for (let index = 0; index < text.length; index += 1) {
441
+ const char = text[index];
442
+ if (!/[。!?!?]/.test(char)) {
443
+ continue;
444
+ }
445
+
446
+ let end = index + 1;
447
+ while (end < text.length && /["'”’))\]」』】]/.test(text[end])) {
448
+ end += 1;
449
+ }
450
+ while (end < text.length && /[\t \n]/.test(text[end])) {
451
+ end += 1;
452
+ }
453
+ boundaries.add(end);
454
+ }
455
+
456
+ return Array.from(boundaries).sort((left, right) => left - right);
457
+ }
458
+
459
+ async function sendTextChunkWithRetry(send, { trace = null } = {}) {
460
+ let lastError = null;
461
+ for (let attempt = 0; ; attempt += 1) {
462
+ const attemptNumber = attempt + 1;
463
+ try {
464
+ logWeixinSendTrace("attempt", {
465
+ ...buildWeixinTraceContext(trace),
466
+ attempt: attemptNumber,
467
+ });
468
+ const result = await send();
469
+ logWeixinSendTrace("success", {
470
+ ...buildWeixinTraceContext(trace),
471
+ attempt: attemptNumber,
472
+ });
473
+ return result;
474
+ } catch (error) {
475
+ lastError = error;
476
+ const retryDelays = getSendRetryDelaysMs(error);
477
+ const retryable = attempt < retryDelays.length;
478
+ logWeixinSendTrace("error", {
479
+ ...buildWeixinTraceContext(trace),
480
+ attempt: attemptNumber,
481
+ retryable,
482
+ error: String(error?.message || error || ""),
483
+ });
484
+ if (!retryable) {
485
+ throw error;
486
+ }
487
+ await sleep(retryDelays[attempt]);
488
+ }
489
+ }
490
+ throw lastError || new Error("sendText chunk failed");
491
+ }
492
+
493
+ function sendV2TextChunk({
494
+ sendTextImpl = sendTextV2,
495
+ baseUrl,
496
+ token,
497
+ routeTag = "",
498
+ clientVersion = "",
499
+ toUserId,
500
+ text,
501
+ contextToken,
502
+ clientId = "",
503
+ trace = null,
504
+ }) {
505
+ const stableClientId = String(clientId || "").trim() || `cb-${crypto.randomUUID()}`;
506
+ return sendTextChunkWithRetry(
507
+ () => sendTextImpl({
508
+ baseUrl,
509
+ token,
510
+ routeTag,
511
+ clientVersion,
512
+ toUserId,
513
+ text,
514
+ contextToken,
515
+ clientId: stableClientId,
516
+ }),
517
+ {
518
+ trace: buildWeixinTraceContext(trace, {
519
+ variant: "v2",
520
+ clientId: stableClientId,
521
+ chars: String(text || "").length,
522
+ textHash: hashTraceText(text),
523
+ }),
524
+ }
525
+ );
526
+ }
527
+
528
+ function getSendRetryDelaysMs(error) {
529
+ const message = String(error?.message || error || "");
530
+ // `ret=-2` is ambiguous: the first attempt may already have landed, or it may
531
+ // have died before the user ever saw it. Retrying with the same client_id once
532
+ // keeps the call idempotent enough to avoid visible truncation without turning
533
+ // one flaky send into a burst of duplicate bubbles.
534
+ if (message.includes("ret=-2")) {
535
+ return AMBIGUOUS_SEND_RETRY_DELAYS_MS;
536
+ }
537
+ if (message.includes("AbortError")
538
+ || message.includes("aborted")
539
+ || message.includes("fetch failed")
540
+ || message.includes("ECONNRESET")
541
+ || message.includes("ETIMEDOUT")
542
+ || /http 5\d\d/.test(message)) {
543
+ return SEND_RETRY_DELAYS_MS;
544
+ }
545
+ return [];
546
+ }
547
+
548
+ function buildWeixinTraceContext(trace, defaults = {}) {
549
+ const normalizedTrace = normalizeTraceContext(trace);
550
+ return {
551
+ ...defaults,
552
+ ...normalizedTrace,
553
+ enabled: Boolean(normalizedTrace.enabled ?? defaults.enabled),
554
+ traceId: normalizeTraceText(normalizedTrace.traceId)
555
+ || normalizeTraceText(defaults.traceId)
556
+ || `wx-${crypto.randomUUID().slice(0, 8)}`,
557
+ };
558
+ }
559
+
560
+ function normalizeTraceContext(trace) {
561
+ if (!trace || typeof trace !== "object") {
562
+ return {};
563
+ }
564
+ return { ...trace };
565
+ }
566
+
567
+ function normalizeTraceText(value) {
568
+ return typeof value === "string" ? value.trim() : "";
569
+ }
570
+
571
+ function logWeixinSendTrace(stage, trace) {
572
+ if (!Boolean(trace?.enabled)) {
573
+ return;
574
+ }
575
+ const parts = [
563
576
  `[codeksei] weixin send trace stage=${stage}`,
564
- `pid=${process.pid}`,
565
- `trace=${trace.traceId || "(none)"}`,
566
- `origin=${trace.origin || "adapter.sendText"}`,
567
- `variant=${trace.variant || "v2"}`,
568
- trace.threadId ? `thread=${trace.threadId}` : "",
569
- `turn=${trace.turnId || "(pending)"}`,
570
- trace.mode ? `mode=${trace.mode}` : "",
571
- trace.trigger ? `trigger=${trace.trigger}` : "",
572
- `chunk=${trace.chunkIndex || 1}/${trace.chunkTotal || 1}`,
573
- `preserveBlock=${trace.preserveBlock ? "1" : "0"}`,
574
- `attempt=${trace.attempt || 1}`,
575
- trace.retryable === undefined ? "" : `retryable=${trace.retryable ? "1" : "0"}`,
576
- `clientId=${trace.clientId || "(none)"}`,
577
- `chars=${trace.chars || 0}`,
578
- `hash=${trace.textHash || hashTraceText("")}`,
579
- ].filter(Boolean);
580
- if (trace.error) {
581
- parts.push(`error=${JSON.stringify(String(trace.error || ""))}`);
582
- console.error(parts.join(" "));
583
- return;
584
- }
585
- console.log(parts.join(" "));
586
- }
587
-
588
- function hashTraceText(text) {
589
- return crypto.createHash("sha1").update(String(text || ""), "utf8").digest("hex").slice(0, 12);
590
- }
591
-
592
- function trimOuterBlankLines(text) {
593
- return String(text || "")
594
- .replace(/^\s*\n+/g, "")
595
- .replace(/\n+\s*$/g, "");
596
- }
597
-
598
- function sleep(ms) {
599
- return new Promise((resolve) => setTimeout(resolve, ms));
600
- }
601
-
602
- module.exports = {
603
- createWeixinChannelAdapter,
604
- sendV2TextChunk,
605
- };
577
+ `pid=${process.pid}`,
578
+ `trace=${trace.traceId || "(none)"}`,
579
+ `origin=${trace.origin || "adapter.sendText"}`,
580
+ `variant=${trace.variant || "v2"}`,
581
+ trace.threadId ? `thread=${trace.threadId}` : "",
582
+ `turn=${trace.turnId || "(pending)"}`,
583
+ trace.mode ? `mode=${trace.mode}` : "",
584
+ trace.trigger ? `trigger=${trace.trigger}` : "",
585
+ `chunk=${trace.chunkIndex || 1}/${trace.chunkTotal || 1}`,
586
+ `preserveBlock=${trace.preserveBlock ? "1" : "0"}`,
587
+ `attempt=${trace.attempt || 1}`,
588
+ trace.retryable === undefined ? "" : `retryable=${trace.retryable ? "1" : "0"}`,
589
+ `clientId=${trace.clientId || "(none)"}`,
590
+ `chars=${trace.chars || 0}`,
591
+ `hash=${trace.textHash || hashTraceText("")}`,
592
+ ].filter(Boolean);
593
+ if (trace.error) {
594
+ parts.push(`error=${JSON.stringify(String(trace.error || ""))}`);
595
+ console.error(parts.join(" "));
596
+ return;
597
+ }
598
+ console.log(parts.join(" "));
599
+ }
600
+
601
+ function hashTraceText(text) {
602
+ return crypto.createHash("sha1").update(String(text || ""), "utf8").digest("hex").slice(0, 12);
603
+ }
604
+
605
+ function trimOuterBlankLines(text) {
606
+ return String(text || "")
607
+ .replace(/^\s*\n+/g, "")
608
+ .replace(/\n+\s*$/g, "");
609
+ }
610
+
611
+ function sleep(ms) {
612
+ return new Promise((resolve) => setTimeout(resolve, ms));
613
+ }
614
+
615
+ module.exports = {
616
+ createWeixinChannelAdapter,
617
+ packChunksForWeixinDelivery,
618
+ sendV2TextChunk,
619
+ };