codeksei 0.1.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 (80) hide show
  1. package/LICENSE +661 -0
  2. package/README.en.md +215 -0
  3. package/README.md +259 -0
  4. package/bin/codeksei.js +10 -0
  5. package/bin/cyberboss.js +11 -0
  6. package/package.json +86 -0
  7. package/scripts/install-background-tasks.ps1 +135 -0
  8. package/scripts/open_shared_wechat_thread.sh +94 -0
  9. package/scripts/open_wechat_thread.sh +117 -0
  10. package/scripts/shared-common.js +791 -0
  11. package/scripts/shared-open.js +46 -0
  12. package/scripts/shared-start.js +41 -0
  13. package/scripts/shared-status.js +74 -0
  14. package/scripts/shared-supervisor.js +141 -0
  15. package/scripts/shared-task-runner.ps1 +87 -0
  16. package/scripts/shared-watchdog.js +290 -0
  17. package/scripts/show_shared_status.sh +53 -0
  18. package/scripts/start_shared_app_server.sh +65 -0
  19. package/scripts/start_shared_wechat.sh +108 -0
  20. package/scripts/timeline-screenshot.sh +15 -0
  21. package/scripts/uninstall-background-tasks.ps1 +23 -0
  22. package/src/adapters/channel/weixin/account-store.js +135 -0
  23. package/src/adapters/channel/weixin/api-v2.js +258 -0
  24. package/src/adapters/channel/weixin/api.js +180 -0
  25. package/src/adapters/channel/weixin/context-token-store.js +84 -0
  26. package/src/adapters/channel/weixin/index.js +605 -0
  27. package/src/adapters/channel/weixin/legacy.js +567 -0
  28. package/src/adapters/channel/weixin/login-common.js +63 -0
  29. package/src/adapters/channel/weixin/login-legacy.js +124 -0
  30. package/src/adapters/channel/weixin/login-v2.js +186 -0
  31. package/src/adapters/channel/weixin/media-mime.js +22 -0
  32. package/src/adapters/channel/weixin/media-receive.js +370 -0
  33. package/src/adapters/channel/weixin/media-send.js +331 -0
  34. package/src/adapters/channel/weixin/message-utils-v2.js +282 -0
  35. package/src/adapters/channel/weixin/message-utils.js +199 -0
  36. package/src/adapters/channel/weixin/protocol.js +77 -0
  37. package/src/adapters/channel/weixin/redact.js +41 -0
  38. package/src/adapters/channel/weixin/reminder-queue-store.js +101 -0
  39. package/src/adapters/channel/weixin/sync-buffer-store.js +35 -0
  40. package/src/adapters/runtime/codex/events.js +252 -0
  41. package/src/adapters/runtime/codex/index.js +502 -0
  42. package/src/adapters/runtime/codex/message-utils.js +141 -0
  43. package/src/adapters/runtime/codex/model-catalog.js +106 -0
  44. package/src/adapters/runtime/codex/protocol-leak-monitor.js +75 -0
  45. package/src/adapters/runtime/codex/rpc-client.js +443 -0
  46. package/src/adapters/runtime/codex/session-store.js +376 -0
  47. package/src/app/channel-send-file-cli.js +57 -0
  48. package/src/app/diary-write-cli.js +620 -0
  49. package/src/app/note-auto-cli.js +201 -0
  50. package/src/app/note-sync-cli.js +130 -0
  51. package/src/app/project-radar-cli.js +165 -0
  52. package/src/app/reminder-write-cli.js +210 -0
  53. package/src/app/review-cli.js +134 -0
  54. package/src/app/system-checkin-poller.js +100 -0
  55. package/src/app/system-send-cli.js +129 -0
  56. package/src/app/timeline-event-cli.js +273 -0
  57. package/src/app/timeline-screenshot-cli.js +109 -0
  58. package/src/core/app.js +1810 -0
  59. package/src/core/branding.js +167 -0
  60. package/src/core/command-registry.js +609 -0
  61. package/src/core/config.js +84 -0
  62. package/src/core/default-targets.js +163 -0
  63. package/src/core/durable-note-schema.js +325 -0
  64. package/src/core/instructions-template.js +31 -0
  65. package/src/core/note-sync.js +433 -0
  66. package/src/core/project-radar.js +402 -0
  67. package/src/core/review-semantic.js +524 -0
  68. package/src/core/review.js +1081 -0
  69. package/src/core/shared-bridge-heartbeat.js +140 -0
  70. package/src/core/stream-delivery.js +990 -0
  71. package/src/core/system-message-dispatcher.js +68 -0
  72. package/src/core/system-message-queue-store.js +128 -0
  73. package/src/core/thread-state-store.js +135 -0
  74. package/src/core/timeline-screenshot-queue-store.js +134 -0
  75. package/src/core/workspace-alias.js +163 -0
  76. package/src/core/workspace-bootstrap.js +338 -0
  77. package/src/index.js +270 -0
  78. package/src/integrations/timeline/index.js +191 -0
  79. package/templates/weixin-instructions.md +53 -0
  80. package/templates/weixin-operations.md +69 -0
@@ -0,0 +1,605 @@
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 = [
563
+ `[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
+ };