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.
- package/LICENSE +661 -0
- package/README.en.md +215 -0
- package/README.md +259 -0
- package/bin/codeksei.js +10 -0
- package/bin/cyberboss.js +11 -0
- package/package.json +86 -0
- package/scripts/install-background-tasks.ps1 +135 -0
- package/scripts/open_shared_wechat_thread.sh +94 -0
- package/scripts/open_wechat_thread.sh +117 -0
- package/scripts/shared-common.js +791 -0
- package/scripts/shared-open.js +46 -0
- package/scripts/shared-start.js +41 -0
- package/scripts/shared-status.js +74 -0
- package/scripts/shared-supervisor.js +141 -0
- package/scripts/shared-task-runner.ps1 +87 -0
- package/scripts/shared-watchdog.js +290 -0
- package/scripts/show_shared_status.sh +53 -0
- package/scripts/start_shared_app_server.sh +65 -0
- package/scripts/start_shared_wechat.sh +108 -0
- package/scripts/timeline-screenshot.sh +15 -0
- package/scripts/uninstall-background-tasks.ps1 +23 -0
- package/src/adapters/channel/weixin/account-store.js +135 -0
- package/src/adapters/channel/weixin/api-v2.js +258 -0
- package/src/adapters/channel/weixin/api.js +180 -0
- package/src/adapters/channel/weixin/context-token-store.js +84 -0
- package/src/adapters/channel/weixin/index.js +605 -0
- package/src/adapters/channel/weixin/legacy.js +567 -0
- package/src/adapters/channel/weixin/login-common.js +63 -0
- package/src/adapters/channel/weixin/login-legacy.js +124 -0
- package/src/adapters/channel/weixin/login-v2.js +186 -0
- package/src/adapters/channel/weixin/media-mime.js +22 -0
- package/src/adapters/channel/weixin/media-receive.js +370 -0
- package/src/adapters/channel/weixin/media-send.js +331 -0
- package/src/adapters/channel/weixin/message-utils-v2.js +282 -0
- package/src/adapters/channel/weixin/message-utils.js +199 -0
- package/src/adapters/channel/weixin/protocol.js +77 -0
- package/src/adapters/channel/weixin/redact.js +41 -0
- package/src/adapters/channel/weixin/reminder-queue-store.js +101 -0
- package/src/adapters/channel/weixin/sync-buffer-store.js +35 -0
- package/src/adapters/runtime/codex/events.js +252 -0
- package/src/adapters/runtime/codex/index.js +502 -0
- package/src/adapters/runtime/codex/message-utils.js +141 -0
- package/src/adapters/runtime/codex/model-catalog.js +106 -0
- package/src/adapters/runtime/codex/protocol-leak-monitor.js +75 -0
- package/src/adapters/runtime/codex/rpc-client.js +443 -0
- package/src/adapters/runtime/codex/session-store.js +376 -0
- package/src/app/channel-send-file-cli.js +57 -0
- package/src/app/diary-write-cli.js +620 -0
- package/src/app/note-auto-cli.js +201 -0
- package/src/app/note-sync-cli.js +130 -0
- package/src/app/project-radar-cli.js +165 -0
- package/src/app/reminder-write-cli.js +210 -0
- package/src/app/review-cli.js +134 -0
- package/src/app/system-checkin-poller.js +100 -0
- package/src/app/system-send-cli.js +129 -0
- package/src/app/timeline-event-cli.js +273 -0
- package/src/app/timeline-screenshot-cli.js +109 -0
- package/src/core/app.js +1810 -0
- package/src/core/branding.js +167 -0
- package/src/core/command-registry.js +609 -0
- package/src/core/config.js +84 -0
- package/src/core/default-targets.js +163 -0
- package/src/core/durable-note-schema.js +325 -0
- package/src/core/instructions-template.js +31 -0
- package/src/core/note-sync.js +433 -0
- package/src/core/project-radar.js +402 -0
- package/src/core/review-semantic.js +524 -0
- package/src/core/review.js +1081 -0
- package/src/core/shared-bridge-heartbeat.js +140 -0
- package/src/core/stream-delivery.js +990 -0
- package/src/core/system-message-dispatcher.js +68 -0
- package/src/core/system-message-queue-store.js +128 -0
- package/src/core/thread-state-store.js +135 -0
- package/src/core/timeline-screenshot-queue-store.js +134 -0
- package/src/core/workspace-alias.js +163 -0
- package/src/core/workspace-bootstrap.js +338 -0
- package/src/index.js +270 -0
- package/src/integrations/timeline/index.js +191 -0
- package/templates/weixin-instructions.md +53 -0
- package/templates/weixin-operations.md +69 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
const crypto = require("crypto");
|
|
2
|
+
const { listWeixinAccounts } = require("./account-store");
|
|
3
|
+
const { resolveSelectedAccount } = require("./account-store");
|
|
4
|
+
const { loadPersistedContextTokens, persistContextToken } = require("./context-token-store");
|
|
5
|
+
const { runLegacyLoginFlow } = require("./login-legacy");
|
|
6
|
+
const { getConfig, getUpdates, sendMessage, sendTyping } = require("./api");
|
|
7
|
+
const { sendWeixinMediaFile } = require("./media-send");
|
|
8
|
+
const { normalizeWeixinIncomingMessage } = require("./message-utils");
|
|
9
|
+
const { loadSyncBuffer, saveSyncBuffer } = require("./sync-buffer-store");
|
|
10
|
+
|
|
11
|
+
const LONG_POLL_TIMEOUT_MS = 35_000;
|
|
12
|
+
const SEND_MESSAGE_CHUNK_INTERVAL_MS = 350;
|
|
13
|
+
const WEIXIN_SEND_CHUNK_LIMIT = 80;
|
|
14
|
+
const MAX_WEIXIN_CHUNK = 3800;
|
|
15
|
+
const WEIXIN_MAX_DELIVERY_MESSAGES = 10;
|
|
16
|
+
const SEND_RETRY_DELAYS_MS = [900, 1800];
|
|
17
|
+
|
|
18
|
+
function createLegacyWeixinChannelAdapter(config) {
|
|
19
|
+
let selectedAccount = null;
|
|
20
|
+
let contextTokenCache = null;
|
|
21
|
+
|
|
22
|
+
function ensureAccount() {
|
|
23
|
+
if (!selectedAccount) {
|
|
24
|
+
selectedAccount = resolveSelectedAccount(config);
|
|
25
|
+
contextTokenCache = loadPersistedContextTokens(config, selectedAccount.accountId);
|
|
26
|
+
}
|
|
27
|
+
return selectedAccount;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function ensureContextTokenCache() {
|
|
31
|
+
if (!contextTokenCache) {
|
|
32
|
+
const account = ensureAccount();
|
|
33
|
+
contextTokenCache = loadPersistedContextTokens(config, account.accountId);
|
|
34
|
+
}
|
|
35
|
+
return contextTokenCache;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function rememberContextToken(userId, contextToken) {
|
|
39
|
+
const account = ensureAccount();
|
|
40
|
+
const normalizedUserId = typeof userId === "string" ? userId.trim() : "";
|
|
41
|
+
const normalizedToken = typeof contextToken === "string" ? contextToken.trim() : "";
|
|
42
|
+
if (!normalizedUserId || !normalizedToken) {
|
|
43
|
+
return "";
|
|
44
|
+
}
|
|
45
|
+
contextTokenCache = persistContextToken(config, account.accountId, normalizedUserId, normalizedToken);
|
|
46
|
+
return normalizedToken;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function resolveContextToken(userId, explicitToken = "") {
|
|
50
|
+
const normalizedExplicitToken = typeof explicitToken === "string" ? explicitToken.trim() : "";
|
|
51
|
+
if (normalizedExplicitToken) {
|
|
52
|
+
return normalizedExplicitToken;
|
|
53
|
+
}
|
|
54
|
+
const normalizedUserId = typeof userId === "string" ? userId.trim() : "";
|
|
55
|
+
if (!normalizedUserId) {
|
|
56
|
+
return "";
|
|
57
|
+
}
|
|
58
|
+
return ensureContextTokenCache()[normalizedUserId] || "";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
describe() {
|
|
63
|
+
return {
|
|
64
|
+
id: "weixin",
|
|
65
|
+
variant: "legacy",
|
|
66
|
+
kind: "channel",
|
|
67
|
+
stateDir: config.stateDir,
|
|
68
|
+
baseUrl: config.weixinBaseUrl,
|
|
69
|
+
accountsDir: config.accountsDir,
|
|
70
|
+
syncBufferDir: config.syncBufferDir,
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
async login() {
|
|
74
|
+
await runLegacyLoginFlow(config);
|
|
75
|
+
},
|
|
76
|
+
printAccounts() {
|
|
77
|
+
const accounts = listWeixinAccounts(config);
|
|
78
|
+
if (!accounts.length) {
|
|
79
|
+
console.log("当前没有已保存的微信账号。先执行 `npm run login`。");
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
console.log("已保存账号:");
|
|
83
|
+
for (const account of accounts) {
|
|
84
|
+
console.log(`- ${account.accountId}`);
|
|
85
|
+
console.log(` userId: ${account.userId || "(unknown)"}`);
|
|
86
|
+
console.log(` baseUrl: ${account.baseUrl || config.weixinBaseUrl}`);
|
|
87
|
+
if (account.routeTag) {
|
|
88
|
+
console.log(` routeTag: ${account.routeTag}`);
|
|
89
|
+
}
|
|
90
|
+
console.log(` savedAt: ${account.savedAt || "(unknown)"}`);
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
resolveAccount() {
|
|
94
|
+
return ensureAccount();
|
|
95
|
+
},
|
|
96
|
+
getKnownContextTokens() {
|
|
97
|
+
return { ...ensureContextTokenCache() };
|
|
98
|
+
},
|
|
99
|
+
loadSyncBuffer() {
|
|
100
|
+
const account = ensureAccount();
|
|
101
|
+
return loadSyncBuffer(config, account.accountId);
|
|
102
|
+
},
|
|
103
|
+
saveSyncBuffer(buffer) {
|
|
104
|
+
const account = ensureAccount();
|
|
105
|
+
saveSyncBuffer(config, account.accountId, buffer);
|
|
106
|
+
},
|
|
107
|
+
rememberContextToken,
|
|
108
|
+
async getUpdates({ syncBuffer = "", timeoutMs = LONG_POLL_TIMEOUT_MS } = {}) {
|
|
109
|
+
const account = ensureAccount();
|
|
110
|
+
const response = await getUpdates({
|
|
111
|
+
baseUrl: account.baseUrl,
|
|
112
|
+
token: account.token,
|
|
113
|
+
get_updates_buf: syncBuffer,
|
|
114
|
+
timeoutMs,
|
|
115
|
+
});
|
|
116
|
+
if (typeof response?.get_updates_buf === "string" && response.get_updates_buf.trim()) {
|
|
117
|
+
this.saveSyncBuffer(response.get_updates_buf.trim());
|
|
118
|
+
}
|
|
119
|
+
const messages = Array.isArray(response?.msgs) ? response.msgs : [];
|
|
120
|
+
for (const message of messages) {
|
|
121
|
+
const userId = typeof message?.from_user_id === "string" ? message.from_user_id.trim() : "";
|
|
122
|
+
const contextToken = typeof message?.context_token === "string" ? message.context_token.trim() : "";
|
|
123
|
+
if (userId && contextToken) {
|
|
124
|
+
rememberContextToken(userId, contextToken);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return response;
|
|
128
|
+
},
|
|
129
|
+
normalizeIncomingMessage(message) {
|
|
130
|
+
const account = ensureAccount();
|
|
131
|
+
return normalizeWeixinIncomingMessage(message, config, account.accountId);
|
|
132
|
+
},
|
|
133
|
+
async sendText({ userId, text, contextToken = "", preserveBlock = false, trace = null }) {
|
|
134
|
+
const account = ensureAccount();
|
|
135
|
+
const resolvedToken = resolveContextToken(userId, contextToken);
|
|
136
|
+
if (!resolvedToken) {
|
|
137
|
+
throw new Error(`缺少 context_token,无法回复用户 ${userId}`);
|
|
138
|
+
}
|
|
139
|
+
const content = String(text || "");
|
|
140
|
+
const sendChunks = preserveBlock
|
|
141
|
+
? splitUtf8(compactPlainTextForWeixin(content) || "已完成。", MAX_WEIXIN_CHUNK)
|
|
142
|
+
: packChunksForWeixinDelivery(
|
|
143
|
+
chunkReplyTextForWeixin(content, WEIXIN_SEND_CHUNK_LIMIT).length
|
|
144
|
+
? chunkReplyTextForWeixin(content, WEIXIN_SEND_CHUNK_LIMIT)
|
|
145
|
+
: ["已完成。"],
|
|
146
|
+
WEIXIN_MAX_DELIVERY_MESSAGES,
|
|
147
|
+
MAX_WEIXIN_CHUNK
|
|
148
|
+
);
|
|
149
|
+
const traceContext = buildWeixinTraceContext(trace, {
|
|
150
|
+
enabled: config.weixinDeliveryTrace,
|
|
151
|
+
origin: "adapter.sendText",
|
|
152
|
+
variant: "legacy",
|
|
153
|
+
preserveBlock,
|
|
154
|
+
chunkTotal: sendChunks.length,
|
|
155
|
+
});
|
|
156
|
+
for (let index = 0; index < sendChunks.length; index += 1) {
|
|
157
|
+
const compactChunk = compactPlainTextForWeixin(sendChunks[index]) || "已完成。";
|
|
158
|
+
const clientId = crypto.randomUUID();
|
|
159
|
+
await sendLegacyTextChunk({
|
|
160
|
+
baseUrl: account.baseUrl,
|
|
161
|
+
token: account.token,
|
|
162
|
+
toUserId: userId,
|
|
163
|
+
text: compactChunk,
|
|
164
|
+
contextToken: resolvedToken,
|
|
165
|
+
clientId,
|
|
166
|
+
trace: {
|
|
167
|
+
...traceContext,
|
|
168
|
+
chunkIndex: index + 1,
|
|
169
|
+
chars: compactChunk.length,
|
|
170
|
+
textHash: hashTraceText(compactChunk),
|
|
171
|
+
clientId,
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
if (index < sendChunks.length - 1) {
|
|
175
|
+
await sleep(SEND_MESSAGE_CHUNK_INTERVAL_MS);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
async sendTyping({ userId, status = 1, contextToken = "" }) {
|
|
180
|
+
const account = ensureAccount();
|
|
181
|
+
const resolvedToken = resolveContextToken(userId, contextToken);
|
|
182
|
+
if (!resolvedToken) {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const configResponse = await getConfig({
|
|
186
|
+
baseUrl: account.baseUrl,
|
|
187
|
+
token: account.token,
|
|
188
|
+
ilinkUserId: userId,
|
|
189
|
+
contextToken: resolvedToken,
|
|
190
|
+
}).catch(() => null);
|
|
191
|
+
const typingTicket = typeof configResponse?.typing_ticket === "string"
|
|
192
|
+
? configResponse.typing_ticket.trim()
|
|
193
|
+
: "";
|
|
194
|
+
if (!typingTicket) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
await sendTyping({
|
|
198
|
+
baseUrl: account.baseUrl,
|
|
199
|
+
token: account.token,
|
|
200
|
+
body: {
|
|
201
|
+
ilink_user_id: userId,
|
|
202
|
+
typing_ticket: typingTicket,
|
|
203
|
+
status,
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
async sendFile({ userId, filePath, contextToken = "" }) {
|
|
208
|
+
const account = ensureAccount();
|
|
209
|
+
const resolvedToken = resolveContextToken(userId, contextToken);
|
|
210
|
+
if (!resolvedToken) {
|
|
211
|
+
throw new Error(`缺少 context_token,无法发送文件给用户 ${userId}`);
|
|
212
|
+
}
|
|
213
|
+
return sendWeixinMediaFile({
|
|
214
|
+
filePath,
|
|
215
|
+
to: userId,
|
|
216
|
+
contextToken: resolvedToken,
|
|
217
|
+
baseUrl: account.baseUrl,
|
|
218
|
+
token: account.token,
|
|
219
|
+
cdnBaseUrl: config.weixinCdnBaseUrl,
|
|
220
|
+
});
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function splitUtf8(text, maxRunes) {
|
|
226
|
+
const runes = Array.from(String(text || ""));
|
|
227
|
+
if (!runes.length || runes.length <= maxRunes) {
|
|
228
|
+
return [String(text || "")];
|
|
229
|
+
}
|
|
230
|
+
const chunks = [];
|
|
231
|
+
while (runes.length) {
|
|
232
|
+
chunks.push(runes.splice(0, maxRunes).join(""));
|
|
233
|
+
}
|
|
234
|
+
return chunks;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function compactPlainTextForWeixin(text) {
|
|
238
|
+
const normalized = String(text || "").replace(/\r\n/g, "\n");
|
|
239
|
+
return trimOuterBlankLines(normalized.replace(/\n\s*\n+/g, "\n"));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function chunkReplyText(text, limit = 3500) {
|
|
243
|
+
const normalized = trimOuterBlankLines(String(text || "").replace(/\r\n/g, "\n"));
|
|
244
|
+
if (!normalized.trim()) {
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const chunks = [];
|
|
249
|
+
let remaining = normalized;
|
|
250
|
+
while (remaining.length > limit) {
|
|
251
|
+
const candidate = remaining.slice(0, limit);
|
|
252
|
+
const splitIndex = Math.max(
|
|
253
|
+
candidate.lastIndexOf("\n\n"),
|
|
254
|
+
candidate.lastIndexOf("\n"),
|
|
255
|
+
candidate.lastIndexOf("。"),
|
|
256
|
+
candidate.lastIndexOf(". "),
|
|
257
|
+
candidate.lastIndexOf(" ")
|
|
258
|
+
);
|
|
259
|
+
const cut = splitIndex > limit * 0.4 ? splitIndex + (candidate[splitIndex] === "\n" ? 0 : 1) : limit;
|
|
260
|
+
const chunk = trimOuterBlankLines(remaining.slice(0, cut));
|
|
261
|
+
if (chunk.trim()) {
|
|
262
|
+
chunks.push(chunk);
|
|
263
|
+
}
|
|
264
|
+
remaining = trimOuterBlankLines(remaining.slice(cut));
|
|
265
|
+
}
|
|
266
|
+
if (remaining) {
|
|
267
|
+
chunks.push(remaining);
|
|
268
|
+
}
|
|
269
|
+
return chunks.filter(Boolean);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function chunkReplyTextForWeixin(text, limit = 80) {
|
|
273
|
+
const normalized = trimOuterBlankLines(String(text || "").replace(/\r\n/g, "\n"));
|
|
274
|
+
if (!normalized.trim()) {
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const boundaries = collectStreamingBoundaries(normalized);
|
|
279
|
+
if (!boundaries.length) {
|
|
280
|
+
return chunkReplyText(normalized, limit);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const units = [];
|
|
284
|
+
let start = 0;
|
|
285
|
+
for (const boundary of boundaries) {
|
|
286
|
+
if (boundary <= start) {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
const unit = trimOuterBlankLines(normalized.slice(start, boundary));
|
|
290
|
+
if (unit) {
|
|
291
|
+
units.push(unit);
|
|
292
|
+
}
|
|
293
|
+
start = boundary;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const tail = trimOuterBlankLines(normalized.slice(start));
|
|
297
|
+
if (tail) {
|
|
298
|
+
units.push(tail);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (!units.length) {
|
|
302
|
+
return chunkReplyText(normalized, limit);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const chunks = [];
|
|
306
|
+
for (const unit of units) {
|
|
307
|
+
if (unit.length <= limit) {
|
|
308
|
+
chunks.push(unit);
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
chunks.push(...chunkReplyText(unit, limit));
|
|
312
|
+
}
|
|
313
|
+
return chunks.filter(Boolean);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function packChunksForWeixinDelivery(chunks, maxMessages = 10, maxChunkChars = 3800) {
|
|
317
|
+
const normalizedChunks = Array.isArray(chunks)
|
|
318
|
+
? chunks.map((chunk) => compactPlainTextForWeixin(chunk)).filter(Boolean)
|
|
319
|
+
: [];
|
|
320
|
+
if (!normalizedChunks.length || normalizedChunks.length <= maxMessages) {
|
|
321
|
+
return normalizedChunks;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const packed = normalizedChunks.slice(0, Math.max(0, maxMessages - 1));
|
|
325
|
+
const tailChunks = normalizedChunks.slice(Math.max(0, maxMessages - 1));
|
|
326
|
+
if (!tailChunks.length) {
|
|
327
|
+
return packed;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const tailText = compactPlainTextForWeixin(tailChunks.join("\n")) || "已完成。";
|
|
331
|
+
if (tailText.length <= maxChunkChars) {
|
|
332
|
+
packed.push(tailText);
|
|
333
|
+
return packed;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const tailHardChunks = splitUtf8(tailText, maxChunkChars);
|
|
337
|
+
if (tailHardChunks.length === 1) {
|
|
338
|
+
packed.push(tailHardChunks[0]);
|
|
339
|
+
return packed;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const preserveCount = Math.max(0, maxMessages - tailHardChunks.length);
|
|
343
|
+
const preserved = normalizedChunks.slice(0, preserveCount);
|
|
344
|
+
const rebundledTail = normalizedChunks.slice(preserveCount);
|
|
345
|
+
const groupedTail = [];
|
|
346
|
+
let current = "";
|
|
347
|
+
for (const chunk of rebundledTail) {
|
|
348
|
+
const joined = current ? `${current}\n${chunk}` : chunk;
|
|
349
|
+
if (current && joined.length > maxChunkChars) {
|
|
350
|
+
groupedTail.push(current);
|
|
351
|
+
current = chunk;
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
current = joined;
|
|
355
|
+
}
|
|
356
|
+
if (current) {
|
|
357
|
+
groupedTail.push(current);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const normalizedGroupedTail = groupedTail.map((item) => compactPlainTextForWeixin(item) || "已完成。");
|
|
361
|
+
if (preserved.length + normalizedGroupedTail.length <= maxMessages) {
|
|
362
|
+
return preserved.concat(normalizedGroupedTail);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Never silently drop the tail of a long reply. If grouping by semantic
|
|
366
|
+
// chunk boundaries still overflows the per-message budget, fall back to hard
|
|
367
|
+
// UTF-8 splits of the already-joined tail so the full answer is still sent.
|
|
368
|
+
return preserved.concat(tailHardChunks.slice(0, Math.max(1, maxMessages - preserved.length)));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function collectStreamingBoundaries(text) {
|
|
372
|
+
const boundaries = new Set();
|
|
373
|
+
|
|
374
|
+
const regex = /\n\s*\n+/g;
|
|
375
|
+
let match = regex.exec(text);
|
|
376
|
+
while (match) {
|
|
377
|
+
boundaries.add(match.index + match[0].length);
|
|
378
|
+
match = regex.exec(text);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const listRegex = /\n(?:(?:[-*])\s+|(?:\d+\.)\s+)/g;
|
|
382
|
+
match = listRegex.exec(text);
|
|
383
|
+
while (match) {
|
|
384
|
+
boundaries.add(match.index + 1);
|
|
385
|
+
match = listRegex.exec(text);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
389
|
+
const char = text[index];
|
|
390
|
+
if (!/[。!?!?]/.test(char)) {
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
let end = index + 1;
|
|
395
|
+
while (end < text.length && /["'”’))\]」』】]/.test(text[end])) {
|
|
396
|
+
end += 1;
|
|
397
|
+
}
|
|
398
|
+
while (end < text.length && /[\t \n]/.test(text[end])) {
|
|
399
|
+
end += 1;
|
|
400
|
+
}
|
|
401
|
+
boundaries.add(end);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
return Array.from(boundaries).sort((left, right) => left - right);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function sendTextChunkWithRetry(send, { trace = null } = {}) {
|
|
408
|
+
let lastError = null;
|
|
409
|
+
for (let attempt = 0; attempt <= SEND_RETRY_DELAYS_MS.length; attempt += 1) {
|
|
410
|
+
const attemptNumber = attempt + 1;
|
|
411
|
+
try {
|
|
412
|
+
logWeixinSendTrace("attempt", {
|
|
413
|
+
...buildWeixinTraceContext(trace),
|
|
414
|
+
attempt: attemptNumber,
|
|
415
|
+
});
|
|
416
|
+
const result = await send();
|
|
417
|
+
logWeixinSendTrace("success", {
|
|
418
|
+
...buildWeixinTraceContext(trace),
|
|
419
|
+
attempt: attemptNumber,
|
|
420
|
+
});
|
|
421
|
+
return result;
|
|
422
|
+
} catch (error) {
|
|
423
|
+
lastError = error;
|
|
424
|
+
const retryable = isRetryableSendError(error);
|
|
425
|
+
logWeixinSendTrace("error", {
|
|
426
|
+
...buildWeixinTraceContext(trace),
|
|
427
|
+
attempt: attemptNumber,
|
|
428
|
+
retryable,
|
|
429
|
+
error: String(error?.message || error || ""),
|
|
430
|
+
});
|
|
431
|
+
if (!retryable || attempt >= SEND_RETRY_DELAYS_MS.length) {
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
await sleep(SEND_RETRY_DELAYS_MS[attempt]);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
throw lastError || new Error("sendText chunk failed");
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function sendLegacyTextChunk({
|
|
441
|
+
sendMessageImpl = sendMessage,
|
|
442
|
+
baseUrl,
|
|
443
|
+
token,
|
|
444
|
+
toUserId,
|
|
445
|
+
text,
|
|
446
|
+
contextToken,
|
|
447
|
+
clientId = "",
|
|
448
|
+
trace = null,
|
|
449
|
+
}) {
|
|
450
|
+
const stableClientId = String(clientId || "").trim() || crypto.randomUUID();
|
|
451
|
+
return sendTextChunkWithRetry(
|
|
452
|
+
() => sendMessageImpl({
|
|
453
|
+
baseUrl,
|
|
454
|
+
token,
|
|
455
|
+
body: {
|
|
456
|
+
msg: {
|
|
457
|
+
client_id: stableClientId,
|
|
458
|
+
from_user_id: "",
|
|
459
|
+
to_user_id: toUserId,
|
|
460
|
+
message_type: 2,
|
|
461
|
+
message_state: 2,
|
|
462
|
+
item_list: [
|
|
463
|
+
{
|
|
464
|
+
type: 1,
|
|
465
|
+
text_item: { text: String(text || "") },
|
|
466
|
+
},
|
|
467
|
+
],
|
|
468
|
+
context_token: contextToken,
|
|
469
|
+
},
|
|
470
|
+
},
|
|
471
|
+
}),
|
|
472
|
+
{
|
|
473
|
+
trace: buildWeixinTraceContext(trace, {
|
|
474
|
+
variant: "legacy",
|
|
475
|
+
clientId: stableClientId,
|
|
476
|
+
chars: String(text || "").length,
|
|
477
|
+
textHash: hashTraceText(text),
|
|
478
|
+
}),
|
|
479
|
+
}
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function isRetryableSendError(error) {
|
|
484
|
+
const message = String(error?.message || error || "");
|
|
485
|
+
// Legacy sendmessage shows the same live ambiguity as v2: `ret=-2` can mean
|
|
486
|
+
// "client saw an error even though WeChat already accepted the message".
|
|
487
|
+
// Do not auto-retry it, or one failed bridge turn can fan out into duplicate
|
|
488
|
+
// bubbles on the user side.
|
|
489
|
+
return message.includes("AbortError")
|
|
490
|
+
|| message.includes("aborted")
|
|
491
|
+
|| message.includes("fetch failed")
|
|
492
|
+
|| message.includes("ECONNRESET")
|
|
493
|
+
|| message.includes("ETIMEDOUT")
|
|
494
|
+
|| /http 5\d\d/.test(message);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function buildWeixinTraceContext(trace, defaults = {}) {
|
|
498
|
+
const normalizedTrace = normalizeTraceContext(trace);
|
|
499
|
+
return {
|
|
500
|
+
...defaults,
|
|
501
|
+
...normalizedTrace,
|
|
502
|
+
enabled: Boolean(normalizedTrace.enabled ?? defaults.enabled),
|
|
503
|
+
traceId: normalizeTraceText(normalizedTrace.traceId)
|
|
504
|
+
|| normalizeTraceText(defaults.traceId)
|
|
505
|
+
|| `wx-${crypto.randomUUID().slice(0, 8)}`,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function normalizeTraceContext(trace) {
|
|
510
|
+
if (!trace || typeof trace !== "object") {
|
|
511
|
+
return {};
|
|
512
|
+
}
|
|
513
|
+
return { ...trace };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function normalizeTraceText(value) {
|
|
517
|
+
return typeof value === "string" ? value.trim() : "";
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function logWeixinSendTrace(stage, trace) {
|
|
521
|
+
if (!Boolean(trace?.enabled)) {
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const parts = [
|
|
525
|
+
`[codeksei] weixin send trace stage=${stage}`,
|
|
526
|
+
`pid=${process.pid}`,
|
|
527
|
+
`trace=${trace.traceId || "(none)"}`,
|
|
528
|
+
`origin=${trace.origin || "adapter.sendText"}`,
|
|
529
|
+
`variant=${trace.variant || "legacy"}`,
|
|
530
|
+
trace.threadId ? `thread=${trace.threadId}` : "",
|
|
531
|
+
`turn=${trace.turnId || "(pending)"}`,
|
|
532
|
+
trace.mode ? `mode=${trace.mode}` : "",
|
|
533
|
+
trace.trigger ? `trigger=${trace.trigger}` : "",
|
|
534
|
+
`chunk=${trace.chunkIndex || 1}/${trace.chunkTotal || 1}`,
|
|
535
|
+
`preserveBlock=${trace.preserveBlock ? "1" : "0"}`,
|
|
536
|
+
`attempt=${trace.attempt || 1}`,
|
|
537
|
+
trace.retryable === undefined ? "" : `retryable=${trace.retryable ? "1" : "0"}`,
|
|
538
|
+
`clientId=${trace.clientId || "(none)"}`,
|
|
539
|
+
`chars=${trace.chars || 0}`,
|
|
540
|
+
`hash=${trace.textHash || hashTraceText("")}`,
|
|
541
|
+
].filter(Boolean);
|
|
542
|
+
if (trace.error) {
|
|
543
|
+
parts.push(`error=${JSON.stringify(String(trace.error || ""))}`);
|
|
544
|
+
console.error(parts.join(" "));
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
console.log(parts.join(" "));
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function hashTraceText(text) {
|
|
551
|
+
return crypto.createHash("sha1").update(String(text || ""), "utf8").digest("hex").slice(0, 12);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function trimOuterBlankLines(text) {
|
|
555
|
+
return String(text || "")
|
|
556
|
+
.replace(/^\s*\n+/g, "")
|
|
557
|
+
.replace(/\n+\s*$/g, "");
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function sleep(ms) {
|
|
561
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
module.exports = {
|
|
565
|
+
createLegacyWeixinChannelAdapter,
|
|
566
|
+
sendLegacyTextChunk,
|
|
567
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const qrcodeTerminal = require("qrcode-terminal");
|
|
2
|
+
const {
|
|
3
|
+
deleteWeixinAccount,
|
|
4
|
+
listWeixinAccounts,
|
|
5
|
+
saveWeixinAccount,
|
|
6
|
+
} = require("./account-store");
|
|
7
|
+
const { clearPersistedContextTokens } = require("./context-token-store");
|
|
8
|
+
|
|
9
|
+
const ACTIVE_LOGIN_TTL_MS = 5 * 60_000;
|
|
10
|
+
const MAX_QR_REFRESH_COUNT = 3;
|
|
11
|
+
|
|
12
|
+
function ensureTrailingSlash(url) {
|
|
13
|
+
return url.endsWith("/") ? url : `${url}/`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function printQrCode(url) {
|
|
17
|
+
try {
|
|
18
|
+
qrcodeTerminal.generate(url, { small: true });
|
|
19
|
+
console.log("如果二维码未能成功展示,请用浏览器打开以下链接扫码:");
|
|
20
|
+
console.log(url);
|
|
21
|
+
} catch {
|
|
22
|
+
console.log(url);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function cleanupStaleAccountsForUserId(config, activeAccount) {
|
|
27
|
+
const activeUserId = typeof activeAccount?.userId === "string" ? activeAccount.userId.trim() : "";
|
|
28
|
+
if (!activeUserId) {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
const staleAccounts = listWeixinAccounts(config).filter((account) => (
|
|
32
|
+
account.accountId !== activeAccount.accountId
|
|
33
|
+
&& typeof account.userId === "string"
|
|
34
|
+
&& account.userId.trim() === activeUserId
|
|
35
|
+
));
|
|
36
|
+
for (const staleAccount of staleAccounts) {
|
|
37
|
+
deleteWeixinAccount(config, staleAccount.accountId);
|
|
38
|
+
clearPersistedContextTokens(config, staleAccount.accountId);
|
|
39
|
+
console.log(`[codeksei] removed stale account ${staleAccount.accountId} for userId ${activeUserId}`);
|
|
40
|
+
}
|
|
41
|
+
return staleAccounts;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function finishWeixinLogin(config, result) {
|
|
45
|
+
const account = saveWeixinAccount(config, result.accountId, result);
|
|
46
|
+
cleanupStaleAccountsForUserId(config, account);
|
|
47
|
+
console.log("\n✅ 与微信连接成功!");
|
|
48
|
+
console.log(`accountId: ${account.accountId}`);
|
|
49
|
+
console.log(`userId: ${account.userId || "(unknown)"}`);
|
|
50
|
+
console.log(`baseUrl: ${account.baseUrl}`);
|
|
51
|
+
if (account.routeTag) {
|
|
52
|
+
console.log(`routeTag: ${account.routeTag}`);
|
|
53
|
+
}
|
|
54
|
+
return account;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = {
|
|
58
|
+
ACTIVE_LOGIN_TTL_MS,
|
|
59
|
+
MAX_QR_REFRESH_COUNT,
|
|
60
|
+
ensureTrailingSlash,
|
|
61
|
+
finishWeixinLogin,
|
|
62
|
+
printQrCode,
|
|
63
|
+
};
|