返回 CodeWhale
index.mjs
1 import fs from "node:fs/promises";
2 import fsSync from "node:fs";
3 import path from "node:path";
4 import crypto from "node:crypto";
5
6 import {
7 getLoginQR,
8 waitForLogin,
9 getUpdates,
10 sendMessage,
11 sendTyping,
12 getConfig,
13 notifyStart,
14 notifyStop,
15 ILinkLoginBase,
16 parseList,
17 parseBool,
18 envFirst,
19 extractText,
20 parseWeixinCommand,
21 commandAction,
22 preservedChatStateFields,
23 splitMessage,
24 compactRuntimeError,
25 latestRunningTurn,
26 helpText,
27 processUpdateBatch,
28 isContinueReply,
29 isSessionExpired,
30 mintCode,
31 parseApprovalReply,
32 approvalText,
33 questionText,
34 parseQuestionAnswers,
35 } from "./lib.mjs";
36 import { renderQrToText } from "./qr.mjs";
37 import { ThreadStore as CoreThreadStore, THREAD_NOT_OWNED_MESSAGE, ThreadOwnershipError, createdByBridge, listOwnedThreads, settleLegacyOwners, readJsonSafe, readThreadEvents, writeFileDurable, ApprovalOwnershipError, decideApproval as decideRuntimeApproval } from "../../bridge-core/src/lib.mjs";
38
39 // ============================================================================
40 // 账号持久化
41 // ============================================================================
42
43 function resolveAccountPath(stateDir) {
44 return path.join(stateDir, "account.json");
45 }
46
47 async function loadAccount(stateDir) {
48 const p = resolveAccountPath(stateDir);
49 try {
50 const raw = await fs.readFile(p, "utf8");
51 return JSON.parse(raw);
52 } catch (error) {
53 if (error.code !== "ENOENT") throw error;
54 return null;
55 }
56 }
57
58 async function saveAccount(stateDir, account) {
59 const p = resolveAccountPath(stateDir);
60 await fs.mkdir(path.dirname(p), { recursive: true, mode: 0o700 });
61 await writeFileDurable(p, `${JSON.stringify(account, null, 2)}\n`, { mode: 0o600 });
62 }
63
64 // ============================================================================
65 // 配置
66 // ============================================================================
67
68 function requiredEnv(name) {
69 const value = process.env[name];
70 if (!value || !value.trim()) {
71 console.error(`Missing required env: ${name}`);
72 process.exit(1);
73 }
74 return value.trim();
75 }
76
77 function requiredEnvFirst(...names) {
78 const value = envFirst(process.env, ...names);
79 if (!value) {
80 console.error(`Missing required env: one of ${names.join(", ")}`);
81 process.exit(1);
82 }
83 return value;
84 }
85
86 // WEIXIN_* is the canonical spelling; the historical WEXIN_* typo names are
87 // still honored as deprecated aliases (each warns once per process).
88 const warnedEnvAliases = new Set();
89
90 function weixinEnv(name) {
91 const legacy = `WEXIN_${name.slice("WEIXIN_".length)}`;
92 const primary = envFirst(process.env, name);
93 if (primary) return primary;
94 const fallback = envFirst(process.env, legacy);
95 if (fallback && !warnedEnvAliases.has(legacy)) {
96 warnedEnvAliases.add(legacy);
97 console.warn(`${legacy} is deprecated; rename it to ${name}.`);
98 }
99 return fallback;
100 }
101
102 const config = {
103 runtimeUrl: (
104 envFirst(process.env, "CODEWHALE_RUNTIME_URL", "DEEPSEEK_RUNTIME_URL") ||
105 "http://127.0.0.1:7878"
106 ).replace(/\/+$/, ""),
107 runtimeToken: requiredEnvFirst(
108 "CODEWHALE_RUNTIME_TOKEN",
109 "DEEPSEEK_RUNTIME_TOKEN"
110 ),
111 workspace:
112 envFirst(process.env, "CODEWHALE_WORKSPACE", "DEEPSEEK_WORKSPACE") ||
113 process.cwd(),
114 model:
115 envFirst(process.env, "CODEWHALE_MODEL", "DEEPSEEK_MODEL") || "auto",
116 mode:
117 envFirst(process.env, "CODEWHALE_MODE", "DEEPSEEK_MODE") || "agent",
118 allowShell: parseBool(
119 envFirst(
120 process.env,
121 "CODEWHALE_ALLOW_SHELL",
122 "DEEPSEEK_ALLOW_SHELL"
123 ),
124 true
125 ),
126 trustMode: parseBool(
127 envFirst(
128 process.env,
129 "CODEWHALE_TRUST_MODE",
130 "DEEPSEEK_TRUST_MODE"
131 ),
132 false
133 ),
134 autoApprove: parseBool(
135 envFirst(
136 process.env,
137 "CODEWHALE_AUTO_APPROVE",
138 "DEEPSEEK_AUTO_APPROVE"
139 ),
140 false
141 ),
142 allowlist: parseList(
143 weixinEnv("WEIXIN_CHAT_ALLOWLIST") ||
144 envFirst(
145 process.env,
146 "CODEWHALE_CHAT_ALLOWLIST",
147 "DEEPSEEK_CHAT_ALLOWLIST"
148 )
149 ),
150 allowUnlisted: parseBool(
151 weixinEnv("WEIXIN_ALLOW_UNLISTED") ||
152 envFirst(
153 process.env,
154 "CODEWHALE_ALLOW_UNLISTED",
155 "DEEPSEEK_ALLOW_UNLISTED"
156 ),
157 false
158 ),
159 stateDir:
160 weixinEnv("WEIXIN_STATE_DIR") ||
161 "/var/lib/codewhale-weixin-bot-bridge",
162 // Defaults inside stateDir rather than to a second absolute path: setting
163 // only WEIXIN_STATE_DIR must not leave the thread map pointing at /var/lib,
164 // which fails with EACCES on every incoming message and silently drops it.
165 threadMapPath:
166 weixinEnv("WEIXIN_THREAD_MAP_PATH") ||
167 path.join(
168 weixinEnv("WEIXIN_STATE_DIR") || "/var/lib/codewhale-weixin-bot-bridge",
169 "thread-map.json"
170 ),
171 maxReplyChars: Number(weixinEnv("WEIXIN_MAX_REPLY_CHARS") || 3500),
172 maxSendsPerMessage: Math.max(2, Number(weixinEnv("WEIXIN_MAX_SENDS_PER_MESSAGE") || 8)),
173 longPollTimeoutMs: Number(
174 weixinEnv("WEIXIN_LONGPOLL_TIMEOUT_MS") || 35000
175 ),
176 turnTimeoutMs: Number(
177 envFirst(
178 process.env,
179 "CODEWHALE_TURN_TIMEOUT_MS",
180 "DEEPSEEK_TURN_TIMEOUT_MS"
181 ) || 900000
182 ),
183 };
184
185 // ============================================================================
186 // Runtime API 工具
187 // ============================================================================
188
189 function authHeaders() {
190 return {
191 Authorization: `Bearer ${config.runtimeToken}`,
192 "Content-Type": "application/json",
193 };
194 }
195
196 async function runtimeJson(subPath, { method = "GET", body = null, auth = true } = {}) {
197 const url = `${config.runtimeUrl}${subPath}`;
198 const options = { method, headers: auth ? authHeaders() : {}, signal: AbortSignal.timeout(10000) };
199 if (body) options.body = JSON.stringify(body);
200 const response = await fetch(url, options);
201 const result = await readJsonSafe(response, { jsonOnly: true });
202 if (!response.ok) {
203 const error = new Error(compactRuntimeError(response.status, result));
204 error.status = response.status;
205 throw error;
206 }
207 return result;
208 }
209
210 // ============================================================================
211 // 消息发送 — 通过 iLink sendMessage
212 // ============================================================================
213
214 const WEIXIN_SYSTEM_PROMPT =
215 "You are being controlled from WeChat on a phone through iLink Bot. Keep answers short and plain: no wide tables, and long code only when asked. Ask for tool approvals when needed; do not assume mobile messages imply blanket approval.";
216 const REPLY_WINDOW_MS = 23.5 * 60 * 60 * 1000;
217 const SEND_GAP_MS = 1000;
218 const SESSION_PAUSE_MS = 60 * 60 * 1000;
219 const RATE_LIMIT_BACKOFF_MS = { first: 60_000, max: 15 * 60_000 };
220 const APPROVAL_CODE_TTL_MS = 30 * 60 * 1000;
221 const SETTLED_OUTPUTS = new Set(["accepted", "unconfirmed", "skipped"]);
222
223 let lastSendAt = 0;
224 let sessionPausedUntil = 0;
225
226 function sessionPaused() {
227 return Date.now() < sessionPausedUntil;
228 }
229
230 function pauseSession(source) {
231 sessionPausedUntil = Date.now() + SESSION_PAUSE_MS;
232 console.error(`iLink reported an expired WeChat session (errcode -14, ${source}). Pausing all iLink calls until ${new Date(sessionPausedUntil).toISOString()}; if it does not recover, delete account.json and scan a new QR code.`);
233 }
234
235 function replyWindow(state) {
236 const since = Date.parse(state?.replyWindow?.since || "");
237 return { since: Number.isFinite(since) ? since : null, sends: Number(state?.replyWindow?.sends) || 0 };
238 }
239
240 function sendAllowance(state) {
241 const { since, sends } = replyWindow(state);
242 if (since !== null && Date.now() - since > REPLY_WINDOW_MS) return 0;
243 return Math.max(0, config.maxSendsPerMessage - sends);
244 }
245
246 async function deliverChunk(chatId, text, { clientId, contextToken } = {}) {
247 if (!botAccount) throw new Error("Bot account unavailable");
248 if (sessionPaused()) throw Object.assign(new Error("The WeChat session is paused"), { deliveryStatus: "paused" });
249 const state = await threadStore.getChat(chatId);
250 if (sendAllowance(state) <= 0) throw Object.assign(new Error("WeChat's reply window or per-message budget is used up"), { deliveryStatus: "held" });
251 const { since, sends } = replyWindow(state);
252 await threadStore.patchChat(chatId, { replyWindow: { since: new Date(since ?? Date.now()).toISOString(), sends: sends + 1 } });
253 const wait = lastSendAt + SEND_GAP_MS - Date.now();
254 if (wait > 0) await sleep(wait);
255 lastSendAt = Date.now();
256 try {
257 return await sendMessage({
258 baseUrl: botAccount.baseUrl,
259 token: botAccount.token,
260 body: {
261 msg: {
262 to_user_id: chatId,
263 client_id: clientId || crypto.randomUUID(),
264 message_type: 2, // BOT
265 message_state: 2, // FINISH
266 item_list: [{ type: 1, text_item: { text } }],
267 context_token: contextToken ?? (await getContextToken(chatId)),
268 },
269 },
270 });
271 } catch (error) {
272 if (error.sessionExpired) pauseSession("sendmessage");
273 throw error;
274 }
275 }
276
277 async function sendText(chatId, text, { clientId, contextToken } = {}) {
278 const chunks = splitMessage(text, config.maxReplyChars);
279 try {
280 for (const [index, chunk] of chunks.entries()) {
281 await deliverChunk(chatId, chunk, { clientId: clientId ? `${clientId}-${index}` : undefined, contextToken });
282 }
283 } catch (error) {
284 if (!["held", "paused", "rejected"].includes(error.deliveryStatus)) throw error;
285 console.warn(`WeChat reply not sent (${error.deliveryStatus}): ${error.message}`);
286 }
287 }
288
289 async function getContextToken(chatId) {
290 const state = await threadStore.getChat(chatId);
291 // Legacy tokens without an account identity are ambiguous; the next inbound
292 // message stores a fresh token bound to the active bot account.
293 return state?.contextTokenAccountId === accountIdentity()
294 ? state.contextToken || undefined
295 : undefined;
296 }
297
298 // ============================================================================
299 // 命令处理(与 feishu/telegram/wechat bridge 一致)
300 // ============================================================================
301
302 async function handleCommand(chatId, command, inbound = {}) {
303 const action = commandAction(command);
304 switch (action.kind) {
305 case "help":
306 await sendText(chatId, helpText());
307 return;
308 case "status":
309 await sendStatus(chatId);
310 return;
311 case "threads":
312 await sendThreads(chatId);
313 return;
314 case "new_thread": {
315 try {
316 const state = await ensureThread(chatId, { forceNew: true });
317 if (inbound.contextToken) {
318 await threadStore.patchChat(chatId, {
319 contextToken: inbound.contextToken,
320 contextTokenAccountId: accountIdentity(),
321 });
322 }
323 await sendText(chatId, `Created thread ${state.threadId}`);
324 } catch (error) {
325 await sendText(chatId, `New conversation failed: ${error.message}`);
326 }
327 return;
328 }
329 case "resume":
330 await resumeThread(chatId, action.threadId);
331 return;
332 case "interrupt":
333 await interruptActiveTurn(chatId);
334 return;
335 case "compact":
336 await compactThread(chatId);
337 return;
338 case "approval":
339 await decideApproval(chatId, action);
340 return;
341 case "set_model":
342 await setChatModel(chatId, action.modelName);
343 return;
344 case "prompt":
345 await runPrompt(chatId, action.prompt, inbound);
346 return;
347 default:
348 await sendText(chatId, helpText());
349 }
350 }
351
352 async function ensureThread(chatId, { forceNew = false, threadRequest } = {}) {
353 let existing = await threadStore.getChat(chatId);
354 const previousAccounts = new Set([existing?.bindingAccountId, existing?.pendingAdmission?.accountId, existing?.turnDelivery?.accountId].filter(Boolean));
355 const replacingAccount = forceNew && previousAccounts.size === 1 && !previousAccounts.has(accountIdentity());
356 if (forceNew && hasPendingWork(existing) && !replacingAccount) throw new Error("This chat still has a pending turn or retained reply. Use /status first.");
357 if (existing?.threadId && !forceNew) {
358 if (existing.bindingAccountId !== accountIdentity()) throw new Error("This thread belongs to another or unverified bot account. Use /new to create an explicit binding.");
359 if (!ownsThread(chatId, existing.threadId)) throw new ThreadOwnershipError();
360 return existing;
361 }
362
363 if (replacingAccount) {
364 // Explicit /new retires the previous account's private receipt before any
365 // new side effect. It remains in this store, outside automatic recovery.
366 const { retiredAccountStates = {}, ...retired } = existing;
367 const receipt = crypto.createHash("sha256").update(JSON.stringify(retired)).digest("hex");
368 const retained = { ...retiredAccountStates, [receipt]: retired };
369 // Fail before creating a new thread; never evict an uncertain submission
370 // or reply merely to make room. Existing over-limit stores remain intact.
371 if (Object.keys(retained).length > threadStore.options.actionLimit || Buffer.byteLength(JSON.stringify(retained), "utf8") > 1024 * 1024) {
372 throw new Error("Retired account receipt storage is full. Ask the local operator to stop the bridge, back up thread-map.json, and reconcile retiredAccountStates before retrying /new.");
373 }
374 await threadStore.patchChat(chatId, { retiredAccountStates: retained });
375 existing = await threadStore.getChat(chatId);
376 }
377
378 const effectiveModel = existing?.model || config.model;
379
380 const thread = await runtimeJson("/v1/threads", {
381 method: "POST",
382 body: threadRequest || {
383 model: effectiveModel,
384 workspace: config.workspace,
385 mode: config.mode,
386 allow_shell: config.allowShell,
387 trust_mode: config.trustMode,
388 auto_approve: config.autoApprove,
389 archived: false,
390 system_prompt: WEIXIN_SYSTEM_PROMPT,
391 },
392 });
393
394 const state = {
395 ...preservedChatStateFields(existing, replacingAccount
396 ? ["model", "retiredAccountStates"]
397 : ["model", "authorizedIdentity", "contextToken", "contextTokenAccountId", "pendingAdmission", "retiredAccountStates"]),
398 threadId: thread.id,
399 bindingAccountId: accountIdentity(),
400 lastSeq: 0,
401 activeTurnId: null,
402 updatedAt: new Date().toISOString(),
403 };
404 await threadStore.recordThreadOwner(chatId, thread.id, turnActor(chatId));
405 await threadStore.setChat(chatId, state);
406 return state;
407 }
408
409 function accountIdentity() {
410 return typeof botAccount?.accountId === "string" ? botAccount.accountId.trim() : "";
411 }
412
413 function weixinActorId(accountId, chatId) {
414 return accountId && chatId ? `weixin-account:${accountId}:user:${chatId}` : "";
415 }
416
417 function turnActor(chatId) {
418 return weixinActorId(accountIdentity(), chatId);
419 }
420
421 function ownsThread(chatId, threadId) {
422 const scope = turnActor(chatId);
423 return Boolean(scope) && threadStore.ownsThread(chatId, threadId, scope);
424 }
425
426 function ownershipPending(chatId, threadId) {
427 const scope = turnActor(chatId);
428 return Boolean(scope) && threadStore.ownershipPending(chatId, threadId, scope);
429 }
430
431 function inboundKey(msg) {
432 const id = msg.message_id;
433 if (!accountIdentity() || !msg.from_user_id || id === undefined || id === null || String(id).trim() === "") return null;
434 return JSON.stringify([accountIdentity(), msg.from_user_id, String(id)]);
435 }
436
437 function hasPendingWork(state) {
438 return Boolean(state?.pendingAdmission || state?.activeTurnId || state?.turnDelivery?.outputs?.some((entry) => !SETTLED_OUTPUTS.has(entry.status)));
439 }
440
441 function ownsRecovery(chatId, state) {
442 const pending = state?.pendingAdmission || state?.turnDelivery;
443 return pending?.accountId === accountIdentity() && pending?.actorId === turnActor(chatId) && isAllowed(chatId);
444 }
445
446 function supportsAdmissionRecovery() {
447 return runtimeCapabilities.turn_operation_idempotency === true && runtimeCapabilities.turn_operation_lookup === true;
448 }
449
450 async function runPrompt(chatId, prompt, { messageKey } = {}) {
451 if (!prompt.trim()) return sendText(chatId, helpText());
452 const current = await threadStore.getChat(chatId);
453 if (hasPendingWork(current)) {
454 startChatRecovery(chatId);
455 return sendText(chatId, "This chat has a pending turn or retained reply. Use /status or /interrupt.");
456 }
457 if (current?.threadId && current.bindingAccountId !== accountIdentity()) return sendText(chatId, "This conversation belongs to another or unverified bot account. Use /new to create a new conversation.");
458 if (current?.threadId && !ownsThread(chatId, current.threadId)) return sendText(chatId, THREAD_NOT_OWNED_MESSAGE);
459 if (!messageKey || !turnActor(chatId)) throw new Error("A stable incoming message identity is required.");
460 const request = {
461 prompt, input_summary: prompt.slice(0, 200), model: current?.model || config.model,
462 mode: config.mode, allow_shell: config.allowShell, trust_mode: config.trustMode, auto_approve: config.autoApprove,
463 };
464 // Retain the frozen request before any admission side effect or poll acknowledgement.
465 const operationKey = supportsAdmissionRecovery() ? crypto.createHash("sha256").update(messageKey).digest("hex") : null;
466 if (operationKey) request.operation_key = operationKey;
467 await threadStore.patchChat(chatId, { pendingAdmission: {
468 accountId: accountIdentity(), actorId: turnActor(chatId), messageKey, request, operationKey,
469 threadId: current?.threadId || null, submitted: false, sinceSeq: null,
470 threadRequest: { model: request.model, workspace: config.workspace, mode: request.mode, allow_shell: request.allow_shell,
471 trust_mode: request.trust_mode, auto_approve: request.auto_approve, archived: false,
472 system_prompt: WEIXIN_SYSTEM_PROMPT },
473 } });
474 startChatRecovery(chatId);
475 }
476
477 async function reconcileAdmission(chatId) {
478 let state = await threadStore.getChat(chatId);
479 let pending = state?.pendingAdmission;
480 if (!pending || !ownsRecovery(chatId, state)) return;
481 if (pending.threadId && !pending.submitted && !ownsThread(chatId, pending.threadId)) {
482 if (ownershipPending(chatId, pending.threadId)) return;
483 await threadStore.patchChat(chatId, { pendingAdmission: null });
484 await sendText(chatId, THREAD_NOT_OWNED_MESSAGE);
485 return;
486 }
487 if (!pending.threadId) {
488 const thread = await ensureThread(chatId, { threadRequest: pending.threadRequest });
489 // ensureThread replaces chat state only for a new thread; retain the admission.
490 pending = { ...pending, threadId: thread.threadId };
491 await threadStore.patchChat(chatId, { pendingAdmission: pending });
492 }
493 if (pending.sinceSeq === null) {
494 const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}`);
495 if (latestRunningTurn(detail)) {
496 await threadStore.patchChat(chatId, { pendingAdmission: { ...pending, blocked: true } });
497 return;
498 }
499 pending = { ...pending, sinceSeq: Number(detail.latest_seq || 0), blocked: false };
500 await threadStore.patchChat(chatId, { pendingAdmission: pending });
501 }
502 let turn;
503 if (pending.submitted) {
504 if (!pending.operationKey || !supportsAdmissionRecovery()) return;
505 try {
506 turn = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}/turn-operations/${encodeURIComponent(pending.operationKey)}`);
507 } catch (error) {
508 // 409 is an incomplete durable admission, not permission to create another turn.
509 if (error.status !== 404) throw error;
510 }
511 }
512 if (!turn) {
513 pending = { ...pending, submitted: true };
514 await threadStore.patchChat(chatId, { pendingAdmission: pending });
515 const result = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}/turns`, { method: "POST", body: pending.request });
516 turn = result?.turn;
517 }
518 if (!turn?.id || turn.thread_id !== pending.threadId) throw new Error("Invalid Engine admission receipt");
519 await threadStore.recordTurnOrigin(chatId, pending.threadId, turn.id, pending.actorId);
520 await threadStore.patchChat(chatId, {
521 pendingAdmission: null, activeTurnId: turn.id, lastSeq: pending.sinceSeq,
522 turnDelivery: { accountId: pending.accountId, actorId: pending.actorId, threadId: pending.threadId,
523 turnId: turn.id, messageKey: pending.messageKey, nextSeq: pending.sinceSeq, responseText: "", outputs: [], terminal: false },
524 });
525 }
526
527 function queueOutput(delivery, key, text) {
528 if (!text || delivery.outputs.some((entry) => entry.key === key)) return;
529 // Persist one independently acknowledged chunk per API call. A stable client ID
530 // helps reconciliation but iLink does not promise exactly-once recipient delivery.
531 for (const [index, chunk] of splitMessage(text, config.maxReplyChars).entries()) {
532 const chunkKey = `${key}:${index}`;
533 if (delivery.outputs.some((entry) => entry.key === chunkKey)) continue;
534 delivery.outputs.push({ key: chunkKey, text: chunk, status: "queued",
535 clientId: crypto.createHash("sha256").update(`${delivery.accountId}:${delivery.turnId}:${chunkKey}`).digest("hex") });
536 }
537 }
538
539 function hasOutput(delivery, key) {
540 return delivery.outputs.some((entry) => entry.key.startsWith(`${key}:`));
541 }
542
543 function mintApprovalCode(delivery, approvalId) {
544 const codes = { ...(delivery.approvalCodes || {}) };
545 let code;
546 do code = mintCode(); while (codes[code]);
547 codes[code] = { approvalId, expiresAt: new Date(Date.now() + APPROVAL_CODE_TTL_MS).toISOString() };
548 delivery.approvalCodes = Object.fromEntries(Object.entries(codes).slice(-100));
549 return code;
550 }
551
552 function queueApproval(delivery, approval, fallbackKey) {
553 const approvalId = approval.approval_id || approval.id;
554 if (!approvalId) {
555 queueOutput(delivery, `approval:${fallbackKey}`, "需要你的批准,请在 Codewhale 中处理。/ An approval is waiting; decide it in Codewhale.");
556 return;
557 }
558 const key = `approval:${approvalId}`;
559 if (hasOutput(delivery, key)) return;
560 queueOutput(delivery, key, approvalText(approval, mintApprovalCode(delivery, approvalId)));
561 }
562
563 function queueQuestion(delivery, input) {
564 const inputId = input?.input_id || input?.id;
565 if (!inputId || !input.request) return;
566 delivery.pendingQuestion = { inputId, request: input.request };
567 queueOutput(delivery, `question:${inputId}`, questionText(input.request));
568 }
569
570 function applyTurnEvent(delivery, record, seq) {
571 const payload = record.payload || {};
572 if (record.event === "item.delta" && payload.kind === "agent_message") delivery.responseText += payload.delta || "";
573 if (record.event === "approval.required") queueApproval(delivery, payload, seq);
574 if (record.event === "user_input.required") queueQuestion(delivery, payload);
575 if ((record.event === "user_input.answered" || record.event === "user_input.canceled")
576 && delivery.pendingQuestion?.inputId === (payload.input_id || payload.id)) delivery.pendingQuestion = null;
577 const status = payload.turn?.status || payload.status;
578 if (record.event === "turn.completed") finishDelivery(delivery, status || "completed");
579 if (record.event === "turn.lifecycle" && ["failed", "canceled", "interrupted"].includes(status)) finishDelivery(delivery, status);
580 }
581
582 function finishDelivery(delivery, status) {
583 if (delivery.terminal) return;
584 delivery.terminal = true;
585 delivery.status = status;
586 delivery.pendingQuestion = null;
587 const text = delivery.responseText.trim();
588 queueOutput(delivery, "result", [text, status !== "completed" ? `Turn ${status}.` : (!text ? "Turn completed." : "")].filter(Boolean).join("\n\n"));
589 }
590
591 async function saveDelivery(chatId, delivery) {
592 await threadStore.patchChat(chatId, { turnDelivery: delivery, lastSeq: delivery.nextSeq });
593 }
594
595 async function updateDelivery(chatId, change) {
596 const state = await threadStore.getChat(chatId);
597 if (!state?.turnDelivery) return null;
598 const delivery = structuredClone(state.turnDelivery);
599 if (change(delivery)) await saveDelivery(chatId, delivery);
600 return delivery;
601 }
602
603 function holdQueued(delivery, fromIndex) {
604 for (const entry of delivery.outputs.slice(fromIndex)) if (entry.status === "queued") entry.status = "held";
605 }
606
607 function insertContinueNotice(delivery, index) {
608 const remaining = delivery.outputs.slice(index).filter((entry) => entry.status === "queued").length;
609 holdQueued(delivery, index);
610 const key = `continue:${crypto.randomUUID()}`;
611 delivery.outputs.splice(index, 0, { key: `${key}:0`, status: "queued",
612 text: `(还有 ${remaining} 条,回复「继续」查看 / Reply 继续 for ${remaining} more)`,
613 clientId: crypto.createHash("sha256").update(`${delivery.accountId}:${delivery.turnId}:${key}`).digest("hex") });
614 }
615
616 async function flushOutputs(chatId) {
617 for (;;) {
618 const state = await threadStore.getChat(chatId);
619 if (!state?.turnDelivery || !ownsRecovery(chatId, state)) return;
620 if (threadStore.turnOrigin(chatId, state.turnDelivery.threadId, state.turnDelivery.turnId)?.actorId !== state.turnDelivery.actorId) return;
621 if (sessionPaused()) return;
622 const allowance = sendAllowance(state);
623 let target = null;
624 const delivery = await updateDelivery(chatId, (draft) => {
625 let changed = false;
626 for (const entry of draft.outputs) if (entry.status === "sending") { entry.status = "uncertain"; changed = true; }
627 if (draft.releaseHeld) {
628 for (const entry of draft.outputs) if (entry.status === "held") entry.status = "queued";
629 draft.releaseHeld = false;
630 changed = true;
631 }
632 const index = draft.outputs.findIndex((entry) => entry.status === "queued");
633 if (index < 0 || Date.parse(draft.outputs[index].retryAt || "") > Date.now()) return changed;
634 if (allowance <= 0) {
635 holdQueued(draft, index);
636 return true;
637 }
638 if (allowance === 1 && draft.outputs.slice(index + 1).some((entry) => entry.status === "queued")) insertContinueNotice(draft, index);
639 target = draft.outputs[index];
640 target.status = "sending";
641 return true;
642 });
643 if (!target) {
644 if (delivery?.terminal && delivery.outputs.every((entry) => SETTLED_OUTPUTS.has(entry.status))) {
645 await threadStore.patchChat(chatId, { activeTurnId: null });
646 }
647 return;
648 }
649 let outcome;
650 try {
651 const response = await deliverChunk(chatId, target.text, { clientId: `${target.clientId}-0` });
652 outcome = response?.message_id ? { status: "accepted", serverMessageId: String(response.message_id) } : { status: "unconfirmed" };
653 if (!response?.message_id) console.warn("WeChat accepted a reply without a message_id; Tencent may be filtering this account's messages.");
654 } catch (error) {
655 if (error.deliveryStatus === "paused" || error.sessionExpired) outcome = { status: "queued" };
656 else if (error.rateLimited) outcome = { status: "queued", rateLimited: true };
657 else if (error.deliveryStatus === "held" || error.deliveryStatus === "rejected") outcome = { status: "held", holdRest: true };
658 else outcome = { status: "uncertain" };
659 }
660 await updateDelivery(chatId, (draft) => {
661 const index = draft.outputs.findIndex((entry) => entry.key === target.key);
662 if (index < 0) return false;
663 const entry = draft.outputs[index];
664 entry.status = outcome.status;
665 if (outcome.serverMessageId) entry.serverMessageId = outcome.serverMessageId;
666 if (outcome.rateLimited) {
667 draft.rateLimitBackoffMs = Math.min(draft.rateLimitBackoffMs ? draft.rateLimitBackoffMs * 2 : RATE_LIMIT_BACKOFF_MS.first, RATE_LIMIT_BACKOFF_MS.max);
668 entry.retryAt = new Date(Date.now() + draft.rateLimitBackoffMs).toISOString();
669 } else if (outcome.status !== "queued") {
670 draft.rateLimitBackoffMs = 0;
671 delete entry.retryAt;
672 }
673 if (outcome.holdRest) holdQueued(draft, index);
674 return true;
675 });
676 if (outcome.status !== "accepted" && outcome.status !== "unconfirmed") return;
677 }
678 }
679
680 function queuedWaitMs(delivery) {
681 const queued = delivery.outputs.filter((entry) => entry.status === "queued");
682 if (!queued.length) return null;
683 const retryAt = Math.min(...queued.map((entry) => Date.parse(entry.retryAt || "") || 0));
684 return Math.max(1000, sessionPausedUntil - Date.now(), retryAt - Date.now());
685 }
686
687 async function reconcileSnapshot(chatId) {
688 const state = await threadStore.getChat(chatId);
689 if (!state?.turnDelivery || !ownsRecovery(chatId, state)) return;
690 const { threadId, turnId } = state.turnDelivery;
691 const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`);
692 const turn = detail.turns?.find((entry) => entry.id === turnId && entry.thread_id === threadId);
693 if (!turn) throw new Error("Accepted Engine turn is unavailable");
694 const items = (detail.items || []).filter((item) => item.turn_id === turnId && item.kind === "agent_message");
695 if (items.some((item) => typeof item.detail !== "string")) throw new Error("Engine snapshot lacks full assistant output");
696 const inputs = (detail.pending_user_inputs || []).filter((input) => input.turn_id === turnId);
697 await updateDelivery(chatId, (delivery) => {
698 if (delivery.turnId !== turnId) return false;
699 if (items.length) delivery.responseText = items.map((item) => item.detail).join("\n\n");
700 delivery.nextSeq = Math.max(delivery.nextSeq, Number(detail.latest_seq || 0));
701 for (const approval of detail.pending_approvals || []) {
702 if (approval.turn_id === turnId) queueApproval(delivery, approval, approval.id);
703 }
704 for (const input of inputs) queueQuestion(delivery, input);
705 if (delivery.pendingQuestion && !inputs.some((input) => input.id === delivery.pendingQuestion.inputId)) delivery.pendingQuestion = null;
706 if (["completed", "failed", "canceled", "interrupted"].includes(turn.status)) finishDelivery(delivery, turn.status);
707 return true;
708 });
709 }
710
711 const typingStates = new Map();
712
713 function startTyping(chatId) {
714 if (typingStates.has(chatId) || !botAccount || sessionPaused()) return;
715 const typing = { ticket: null, timer: null };
716 typingStates.set(chatId, typing);
717 const tick = async () => {
718 try {
719 if (sessionPaused()) return;
720 if (!typing.ticket) {
721 const accountConfig = await getConfig({ baseUrl: botAccount.baseUrl, token: botAccount.token, ilinkUserId: chatId, contextToken: await getContextToken(chatId) });
722 typing.ticket = accountConfig?.typing_ticket || "";
723 }
724 if (typing.ticket && typingStates.get(chatId) === typing) {
725 await sendTyping({ baseUrl: botAccount.baseUrl, token: botAccount.token, ilinkUserId: chatId, typingTicket: typing.ticket, status: 1 });
726 }
727 } catch {
728 if (typingStates.get(chatId) === typing) stopTyping(chatId, false);
729 }
730 };
731 typing.timer = setInterval(tick, 5000);
732 typing.timer.unref?.();
733 tick();
734 }
735
736 function stopTyping(chatId, cancel = true) {
737 const typing = typingStates.get(chatId);
738 if (!typing) return;
739 clearInterval(typing.timer);
740 typingStates.delete(chatId);
741 if (cancel && typing.ticket && botAccount && !sessionPaused()) {
742 sendTyping({ baseUrl: botAccount.baseUrl, token: botAccount.token, ilinkUserId: chatId, typingTicket: typing.ticket, status: 2 }).catch(() => {});
743 }
744 }
745
746 async function streamTurnEvents(chatId, controller) {
747 const start = (await threadStore.getChat(chatId)).turnDelivery;
748 // Bound headers and streaming together; this never interrupts the Engine turn.
749 const timeout = setTimeout(() => controller.abort(), config.turnTimeoutMs);
750 try {
751 const response = await fetch(`${config.runtimeUrl}/v1/threads/${encodeURIComponent(start.threadId)}/events?since_seq=${start.nextSeq}`,
752 { headers: authHeaders(), signal: controller.signal });
753 if (!response.ok) throw new Error("Engine event observation unavailable");
754 for await (const record of readThreadEvents(response, start.threadId)) {
755 if (record.event === "stream.end") {
756 if (record.payload?.retryable === false || record.retryable === false) return false;
757 break;
758 }
759 const seq = Number(record.seq || 0);
760 // Cursor, accumulator and pending output are committed together before send.
761 const delivery = await updateDelivery(chatId, (draft) => {
762 if (draft.turnId !== start.turnId || seq <= draft.nextSeq) return false;
763 draft.nextSeq = seq;
764 if (record.turn_id === draft.turnId) applyTurnEvent(draft, record, seq);
765 return true;
766 });
767 if (!delivery || delivery.turnId !== start.turnId) return true;
768 if (record.turn_id === start.turnId) {
769 if (record.event === "item.delta") startTyping(chatId);
770 if (record.event === "approval.required" || record.event === "user_input.required") stopTyping(chatId);
771 }
772 await flushOutputs(chatId);
773 if (delivery.terminal) return true;
774 if (stopping) break;
775 }
776 return true;
777 } finally {
778 clearTimeout(timeout);
779 controller.abort();
780 stopTyping(chatId);
781 }
782 }
783
784 function startChatRecovery(chatId) {
785 if (stopping || recoveryTasks.has(chatId)) return;
786 const task = (async () => {
787 while (!stopping) {
788 let state = await threadStore.getChat(chatId);
789 if (!ownsRecovery(chatId, state)) return;
790 try {
791 if (state.pendingAdmission) {
792 await reconcileAdmission(chatId);
793 state = await threadStore.getChat(chatId);
794 if (state.pendingAdmission) {
795 if (state.pendingAdmission.submitted && !state.pendingAdmission.operationKey) return;
796 await sleep(1000);
797 continue;
798 }
799 }
800 if (!state.turnDelivery) return;
801 if (!state.turnDelivery.terminal) await reconcileSnapshot(chatId);
802 await flushOutputs(chatId);
803 state = await threadStore.getChat(chatId);
804 if (state.turnDelivery?.terminal) {
805 const wait = queuedWaitMs(state.turnDelivery);
806 if (wait === null) return;
807 await sleep(wait);
808 continue;
809 }
810 const controller = new AbortController();
811 recoveryControllers.set(chatId, controller);
812 const retryable = await streamTurnEvents(chatId, controller);
813 recoveryControllers.delete(chatId);
814 if (retryable === false) return;
815 } catch {
816 if (stopping) return;
817 console.warn("Turn observation interrupted; retaining the accepted turn for recovery.");
818 }
819 await sleep(1000);
820 }
821 })().finally(() => { recoveryTasks.delete(chatId); recoveryControllers.delete(chatId); });
822 recoveryTasks.set(chatId, task);
823 }
824
825 async function reissueApprovalCodes(chatId) {
826 const state = await threadStore.getChat(chatId);
827 const delivery = state?.turnDelivery;
828 if (!delivery || delivery.terminal || !ownsRecovery(chatId, state)) return [];
829 const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(delivery.threadId)}`);
830 const pending = (detail.pending_approvals || []).filter((approval) => approval.turn_id === delivery.turnId);
831 const lines = [];
832 await updateDelivery(chatId, (draft) => {
833 if (draft.turnId !== delivery.turnId) return false;
834 for (const approval of pending) lines.push(approvalText(approval, mintApprovalCode(draft, approval.approval_id || approval.id)));
835 return lines.length > 0;
836 });
837 return lines;
838 }
839
840 async function decideByCode(chatId, { decision, code }) {
841 const state = await threadStore.getChat(chatId);
842 const entry = ownsRecovery(chatId, state) ? state?.turnDelivery?.approvalCodes?.[code] : null;
843 if (!entry || entry.usedAt) return sendText(chatId, "没有找到等待中的这个批准码。/ No approval is waiting with that code.");
844 if (Date.parse(entry.expiresAt) <= Date.now()) return sendText(chatId, "这个批准码已过期,发送 /status 获取新的。/ That code expired; send /status for a new one.");
845 try {
846 await decideRuntimeApproval(runtimeJson, { store: threadStore, chatId, actorId: turnActor(chatId), approvalId: entry.approvalId, decision, remember: false, ownsThread: (threadId) => ownsThread(chatId, threadId) });
847 } catch (error) {
848 if (error instanceof ThreadOwnershipError) return sendText(chatId, THREAD_NOT_OWNED_MESSAGE);
849 if (error instanceof ApprovalOwnershipError || error.status === 404) return sendText(chatId, "这个批准已不在等待中。/ That approval is no longer waiting.");
850 return sendText(chatId, `Approval failed: ${error.message}`);
851 }
852 await updateDelivery(chatId, (draft) => {
853 if (!draft.approvalCodes?.[code]) return false;
854 draft.approvalCodes[code].usedAt = new Date().toISOString();
855 return true;
856 });
857 await sendText(chatId, decision === "allow" ? "已允许 / Allowed" : "已拒绝 / Denied");
858 }
859
860 async function answerQuestion(chatId, text) {
861 const state = await threadStore.getChat(chatId);
862 const delivery = state?.turnDelivery;
863 const question = delivery?.pendingQuestion;
864 const answers = parseQuestionAnswers(question?.request, text);
865 if (!answers) return sendText(chatId, "没能对上这个回答,请回复选项编号或文字。/ That did not match; reply with an option number or in words.");
866 try {
867 await runtimeJson(`/v1/user-input/${encodeURIComponent(delivery.threadId)}/${encodeURIComponent(question.inputId)}`, { method: "POST", body: { answers } });
868 } catch (error) {
869 if (error.status !== 404) return sendText(chatId, `Answer failed: ${error.message}`);
870 await updateDelivery(chatId, (draft) => {
871 if (draft.pendingQuestion?.inputId !== question.inputId) return false;
872 draft.pendingQuestion = null;
873 return true;
874 });
875 return sendText(chatId, "这个问题已不在等待中。/ That question is no longer waiting.");
876 }
877 await updateDelivery(chatId, (draft) => {
878 if (draft.pendingQuestion?.inputId !== question.inputId) return false;
879 draft.pendingQuestion = null;
880 return true;
881 });
882 await sendText(chatId, "已回答 / Answer sent");
883 }
884
885 async function sendStatus(chatId) {
886 try {
887 const state = await threadStore.getChat(chatId);
888 const [health, runtimeInfo, workspace] = await Promise.all([
889 runtimeJson("/health", { auth: false }),
890 runtimeJson("/v1/runtime/info"),
891 runtimeJson("/v1/workspace/status"),
892 ]);
893 const outputs = ownsRecovery(chatId, state) ? state?.turnDelivery?.outputs || [] : [];
894 const held = outputs.filter((entry) => entry.status === "held").length;
895 const unconfirmed = outputs.filter((entry) => entry.status === "unconfirmed").length;
896 const approvals = await reissueApprovalCodes(chatId);
897 await sendText(
898 chatId,
899 [
900 `user_id=${chatId}`,
901 state?.pendingAdmission ? "Turn admission is pending; its original request is retained." : "",
902 state?.activeTurnId && ownsRecovery(chatId, state) ? `accepted_turn=${state.activeTurnId}` : "",
903 outputs.some((entry) => entry.status === "uncertain") ? "A reply has unconfirmed API acceptance. It is retained for review and will not be resent automatically." : "",
904 held ? `还有 ${held} 条回复未发送,回复「继续」查看。/ ${held} replies are waiting; reply 继续.` : "",
905 unconfirmed ? `微信接受了 ${unconfirmed} 条回复但没有返回消息 ID,可能没有显示。/ WeChat accepted ${unconfirmed} replies without a message ID; they may not have been shown.` : "",
906 ownsRecovery(chatId, state) && state?.turnDelivery?.pendingQuestion ? "Codewhale 正在等你回答上面的问题。/ Codewhale is waiting for your answer to its question." : "",
907 ...approvals,
908 `runtime=${health.status || "unknown"}`,
909 `version=${runtimeInfo.version || "unknown"}`,
910 `bind=${runtimeInfo.bind_host}:${runtimeInfo.port}`,
911 `auth_required=${runtimeInfo.auth_required}`,
912 `workspace=${workspace.workspace}`,
913 `git_repo=${workspace.git_repo}`,
914 workspace.branch ? `branch=${workspace.branch}` : "",
915 `staged=${workspace.staged} unstaged=${workspace.unstaged} untracked=${workspace.untracked}`,
916 ]
917 .filter(Boolean)
918 .join("\n")
919 );
920 } catch (error) {
921 await sendText(chatId, `Status check failed: ${error.message}`);
922 }
923 }
924
925 async function sendThreads(chatId) {
926 try {
927 const scope = turnActor(chatId);
928 const threads = scope ? await listOwnedThreads(threadStore, runtimeJson, chatId, scope) : [];
929 if (!threads.length) {
930 await sendText(chatId, "No recent runtime threads owned by this account and chat.");
931 return;
932 }
933 await sendText(
934 chatId,
935 threads
936 .map((thread) => {
937 const status = thread.latest_turn_status || "none";
938 return `${thread.id} [${status}] ${thread.title || thread.preview || ""}`;
939 })
940 .join("\n")
941 );
942 } catch (error) {
943 await sendText(chatId, `Thread listing failed: ${error.message}`);
944 }
945 }
946
947 async function resumeThread(chatId, args) {
948 const threadId = args.trim();
949 if (!threadId) {
950 await sendText(chatId, "Usage: /resume <thread_id>");
951 return;
952 }
953 try {
954 const existing = await threadStore.getChat(chatId);
955 if (hasPendingWork(existing)) throw new Error("This chat still has a pending turn or retained reply. Use /status first.");
956 if (!ownsThread(chatId, threadId)) throw new ApprovalOwnershipError("Thread is not owned by this account and chat");
957 const detail = await runtimeJson(
958 `/v1/threads/${encodeURIComponent(threadId)}`
959 );
960 await threadStore.setChat(chatId, {
961 ...preservedChatStateFields(existing, ["model", "authorizedIdentity", "contextToken", "contextTokenAccountId", "retiredAccountStates"]),
962 threadId,
963 bindingAccountId: accountIdentity(),
964 lastSeq: Number(detail.latest_seq || 0),
965 activeTurnId: null,
966 updatedAt: new Date().toISOString(),
967 });
968 await sendText(chatId, `Resumed thread ${threadId}`);
969 } catch (error) {
970 await sendText(chatId, `Resume failed: ${error.message}`);
971 }
972 }
973
974 async function interruptActiveTurn(chatId) {
975 const state = await threadStore.getChat(chatId);
976 if (!state?.threadId) {
977 await sendText(chatId, "No runtime thread recorded for this chat.");
978 return;
979 }
980 try {
981 const detail = await runtimeJson(
982 `/v1/threads/${encodeURIComponent(state.threadId)}`
983 );
984 const turnId = state.activeTurnId;
985 if (!turnId) {
986 await sendText(chatId, "No active turn recorded for this chat.");
987 return;
988 }
989 if (state.turnDelivery?.accountId !== accountIdentity() || threadStore.turnOrigin(chatId, state.threadId, turnId)?.actorId !== turnActor(chatId)) throw new ApprovalOwnershipError("Turn is not owned by this account and chat");
990 await runtimeJson(
991 `/v1/threads/${encodeURIComponent(state.threadId)}/turns/${encodeURIComponent(turnId)}/interrupt`,
992 { method: "POST" }
993 );
994 await threadStore.patchChat(chatId, {
995 activeTurnId: turnId,
996 updatedAt: new Date().toISOString(),
997 });
998 await sendText(chatId, `Interrupt requested for ${turnId}`);
999 } catch (error) {
1000 await sendText(chatId, `Interrupt failed: ${error.message}`);
1001 }
1002 }
1003
1004 async function compactThread(chatId) {
1005 try {
1006 const state = await ensureThread(chatId);
1007 const result = await runtimeJson(
1008 `/v1/threads/${encodeURIComponent(state.threadId)}/compact`,
1009 {
1010 method: "POST",
1011 body: { reason: "weixin-bot bridge request" },
1012 }
1013 );
1014 await sendText(
1015 chatId,
1016 `Compaction started: ${result.turn?.id || "unknown turn"}`
1017 );
1018 } catch (error) {
1019 await sendText(chatId, error instanceof ThreadOwnershipError ? THREAD_NOT_OWNED_MESSAGE : `Compact failed: ${error.message}`);
1020 }
1021 }
1022
1023 async function decideApproval(chatId, action) {
1024 const decision = action.decision;
1025 const { approvalId, remember } = action;
1026 if (!approvalId) {
1027 await sendText(
1028 chatId,
1029 `Usage: /${decision} <approval_id>${decision === "allow" ? " [remember]" : ""}`
1030 );
1031 return;
1032 }
1033 try {
1034 await decideRuntimeApproval(runtimeJson, { store: threadStore, chatId, actorId: turnActor(chatId), approvalId, decision, remember, ownsThread: (threadId) => ownsThread(chatId, threadId) });
1035 await sendText(
1036 chatId,
1037 `Approval ${approvalId}: ${decision}${remember ? " and remember" : ""}`
1038 );
1039 } catch (error) {
1040 if (error instanceof ThreadOwnershipError) {
1041 await sendText(chatId, THREAD_NOT_OWNED_MESSAGE);
1042 return;
1043 }
1044 if (error instanceof ApprovalOwnershipError) {
1045 await sendText(chatId, `Approval ${approvalId} is not waiting in this chat.`);
1046 return;
1047 }
1048 await sendText(chatId, `Approval failed: ${error.message}`);
1049 }
1050 }
1051
1052 async function setChatModel(chatId, modelName) {
1053 if (!modelName || modelName === "default") {
1054 await threadStore.patchChat(chatId, {
1055 model: null,
1056 updatedAt: new Date().toISOString(),
1057 });
1058 await sendText(
1059 chatId,
1060 `Reset per-chat model. Using bridge default: ${config.model}`
1061 );
1062 return;
1063 }
1064 await threadStore.patchChat(chatId, {
1065 model: modelName,
1066 updatedAt: new Date().toISOString(),
1067 });
1068 await sendText(chatId, `Per-chat model set to: ${modelName}`);
1069 }
1070
1071 // ============================================================================
1072 // 主循环 — 长轮询 getUpdates
1073 // ============================================================================
1074
1075 let botAccount = null;
1076 let stopping = false;
1077 let threadStore;
1078 const recoveryTasks = new Map();
1079 const recoveryControllers = new Map();
1080 let runtimeCapabilities = {};
1081
1082 function resolveSyncBufPath(stateDir) {
1083 return path.join(stateDir, "sync-buf.txt");
1084 }
1085
1086 async function loadSyncBuf(stateDir) {
1087 const p = resolveSyncBufPath(stateDir);
1088 try {
1089 return await fs.readFile(p, "utf8");
1090 } catch {
1091 return "";
1092 }
1093 }
1094
1095 async function saveSyncBuf(stateDir, buf) {
1096 const p = resolveSyncBufPath(stateDir);
1097 // The state dir may not exist yet on a first run whose first persisted write
1098 // is the poll cursor rather than account.json.
1099 await fs.mkdir(path.dirname(p), { recursive: true, mode: 0o700 });
1100 await writeFileDurable(p, buf, { mode: 0o600 });
1101 }
1102
1103 const refusedSenders = new Set();
1104
1105 async function refuseSender(msg) {
1106 const fromUser = msg.from_user_id;
1107 if (!fromUser || !msg.context_token || refusedSenders.has(fromUser) || refusedSenders.size >= 100 || sessionPaused()) return;
1108 refusedSenders.add(fromUser);
1109 console.warn(`Refused a chat from an unlisted WeChat user (user_id=${fromUser}).`);
1110 try {
1111 await sendMessage({
1112 baseUrl: botAccount.baseUrl,
1113 token: botAccount.token,
1114 body: { msg: { to_user_id: fromUser, client_id: crypto.randomUUID(), message_type: 2, message_state: 2,
1115 item_list: [{ type: 1, text_item: { text: `此微信未获授权使用这个 Codewhale。/ This WeChat is not allowed to use this Codewhale. (user_id=${fromUser})` } }],
1116 context_token: msg.context_token } },
1117 });
1118 } catch (error) {
1119 if (error.sessionExpired) pauseSession("sendmessage");
1120 }
1121 }
1122
1123 async function settleHeldReplies(chatId, text) {
1124 const state = await threadStore.getChat(chatId);
1125 const delivery = state?.turnDelivery;
1126 if (!delivery || !ownsRecovery(chatId, state) || !delivery.outputs.some((entry) => entry.status === "held")) return "none";
1127 if (isContinueReply(text)) {
1128 await updateDelivery(chatId, (draft) => { draft.releaseHeld = true; return true; });
1129 startChatRecovery(chatId);
1130 return "consumed";
1131 }
1132 const command = commandAction(parseWeixinCommand(text));
1133 if (!delivery.terminal || command.kind !== "prompt" || parseApprovalReply(text)) {
1134 await updateDelivery(chatId, (draft) => { draft.releaseHeld = true; return true; });
1135 startChatRecovery(chatId);
1136 return "released";
1137 }
1138 const seen = delivery.outputs.some((entry) => entry.status === "accepted" || entry.status === "unconfirmed");
1139 if (seen) {
1140 const settled = await updateDelivery(chatId, (draft) => {
1141 for (const entry of draft.outputs) if (entry.status === "held") entry.status = "skipped";
1142 return true;
1143 });
1144 if (settled?.outputs.every((entry) => SETTLED_OUTPUTS.has(entry.status))) await threadStore.patchChat(chatId, { activeTurnId: null });
1145 return "skipped";
1146 }
1147 await updateDelivery(chatId, (draft) => {
1148 const index = draft.outputs.findIndex((entry) => entry.status === "held");
1149 const key = `waiting:${crypto.randomUUID()}`;
1150 draft.outputs.splice(index, 0, { key: `${key}:0`, status: "held",
1151 text: "你有一条之前的回复(下一条)。你刚才的消息还没有发给 Codewhale,看完后请重新发送。/ You have an earlier answer (next message). Your new message was not run yet; send it again after reading.",
1152 clientId: crypto.createHash("sha256").update(`${draft.accountId}:${draft.turnId}:${key}`).digest("hex") });
1153 draft.releaseHeld = true;
1154 return true;
1155 });
1156 startChatRecovery(chatId);
1157 return "consumed";
1158 }
1159
1160 /** One durably claimed inbound message; agent observation runs separately. */
1161 async function handleInbound(msg) {
1162 const fromUser = msg.from_user_id || "";
1163 if (msg.message_type !== undefined && msg.message_type !== 1) return;
1164 if (!isAllowed(fromUser)) return refuseSender(msg);
1165 await threadStore.patchChat(fromUser, { replyWindow: { since: new Date().toISOString(), sends: 0 } });
1166 const text = extractText(msg.item_list);
1167 if (msg.context_token) {
1168 const state = await threadStore.getChat(fromUser);
1169 // A pending admission already owns its context before a thread is bound.
1170 // Preserve foreign or unattributed receipts until /new retires them.
1171 if ((!state?.bindingAccountId || state.bindingAccountId === accountIdentity())
1172 && (!state?.pendingAdmission || state.pendingAdmission.accountId === accountIdentity())
1173 && (!state?.turnDelivery || state.turnDelivery.accountId === accountIdentity())) {
1174 await threadStore.patchChat(fromUser, {
1175 contextToken: msg.context_token,
1176 contextTokenAccountId: accountIdentity(),
1177 });
1178 }
1179 }
1180 if (!text) return sendText(fromUser, "仅支持文本和语音消息。图片/视频/文件暂不支持。/ Only text and voice messages are supported.");
1181 if ((await settleHeldReplies(fromUser, text)) === "consumed") return;
1182 const approvalReply = parseApprovalReply(text);
1183 if (approvalReply) return decideByCode(fromUser, approvalReply);
1184 const command = parseWeixinCommand(text);
1185 const state = await threadStore.getChat(fromUser);
1186 if (command.name === "prompt" && state?.turnDelivery?.pendingQuestion && !state.turnDelivery.terminal && ownsRecovery(fromUser, state)) {
1187 return answerQuestion(fromUser, text);
1188 }
1189 await handleCommand(fromUser, command, {
1190 messageKey: inboundKey(msg),
1191 contextToken: msg.context_token,
1192 });
1193 }
1194
1195 async function monitorLoop() {
1196 const { baseUrl, token } = botAccount;
1197 let getUpdatesBuf = await loadSyncBuf(config.stateDir);
1198 let nextTimeoutMs = config.longPollTimeoutMs;
1199 let consecutiveFailures = 0;
1200
1201 console.log(`Monitor started: baseUrl=${baseUrl} timeoutMs=${nextTimeoutMs}`);
1202
1203 while (!stopping) {
1204 if (sessionPaused()) {
1205 await sleep(Math.min(5000, sessionPausedUntil - Date.now()));
1206 continue;
1207 }
1208 try {
1209 const abortController = new AbortController();
1210 const timer = setTimeout(
1211 () => abortController.abort(),
1212 nextTimeoutMs + 5000
1213 );
1214
1215 const resp = await getUpdates({
1216 baseUrl,
1217 token,
1218 get_updates_buf: getUpdatesBuf,
1219 timeoutMs: nextTimeoutMs,
1220 signal: abortController.signal,
1221 });
1222
1223 clearTimeout(timer);
1224
1225 if (resp.longpolling_timeout_ms) {
1226 nextTimeoutMs = resp.longpolling_timeout_ms;
1227 }
1228
1229 // 检查错误
1230 const isApiError =
1231 (resp.ret !== undefined && resp.ret !== 0) ||
1232 (resp.errcode !== undefined && resp.errcode !== 0);
1233
1234 if (isApiError && isSessionExpired(resp)) {
1235 pauseSession("getupdates");
1236 consecutiveFailures = 0;
1237 continue;
1238 }
1239
1240 if (isApiError) {
1241 consecutiveFailures += 1;
1242 console.error(
1243 `getUpdates error: ret=${resp.ret} errcode=${resp.errcode} errmsg=${resp.errmsg}`
1244 );
1245 if (consecutiveFailures >= 3) {
1246 console.error("3 consecutive failures, backing off 30s");
1247 await sleep(30000);
1248 consecutiveFailures = 0;
1249 } else {
1250 await sleep(2000);
1251 }
1252 continue;
1253 }
1254
1255 consecutiveFailures = 0;
1256
1257 await processUpdateBatch({
1258 messages: resp.msgs,
1259 nextCursor: resp.get_updates_buf,
1260 store: threadStore,
1261 keyOf: (msg) => {
1262 const key = inboundKey(msg);
1263 if (!key) console.warn("Ignored inbound message without a stable account/peer/message identity.");
1264 return key;
1265 },
1266 handle: handleInbound,
1267 interrupted: async (msg) => {
1268 const key = inboundKey(msg);
1269 const state = await threadStore.getChat(msg.from_user_id);
1270 if (state?.pendingAdmission?.messageKey === key || state?.turnDelivery?.messageKey === key) {
1271 startChatRecovery(msg.from_user_id);
1272 } else if (commandAction(parseWeixinCommand(extractText(msg.item_list))).kind === "prompt" && !parseApprovalReply(extractText(msg.item_list))) {
1273 // Prompt admission always persists before side effects. No receipt
1274 // means this claim crashed before admission, so it can be handled.
1275 await handleInbound(msg);
1276 } else if (isAllowed(msg.from_user_id)) {
1277 await sendText(msg.from_user_id, "The bridge restarted while handling this command. Its effect is uncertain; check /status before repeating it.");
1278 }
1279 },
1280 commitCursor: async (cursor) => {
1281 await saveSyncBuf(config.stateDir, cursor);
1282 getUpdatesBuf = cursor;
1283 },
1284 });
1285 for (const [chatId, state] of threadStore.listChats()) {
1286 if (hasPendingWork(state)) startChatRecovery(chatId);
1287 }
1288 } catch (error) {
1289 if (error.name === "AbortError" || error.message?.includes("abort")) {
1290 // 长轮询超时是正常的,立即重试
1291 continue;
1292 }
1293 if (stopping) break;
1294
1295 consecutiveFailures += 1;
1296 console.error(
1297 `getUpdates exception (${consecutiveFailures}/3):`,
1298 error.message
1299 );
1300 if (consecutiveFailures >= 3) {
1301 console.error("3 consecutive exceptions, backing off 30s");
1302 await sleep(30000);
1303 consecutiveFailures = 0;
1304 } else {
1305 await sleep(2000);
1306 }
1307 }
1308 }
1309 }
1310
1311 function isAllowed(fromUser) {
1312 if (!fromUser) return false;
1313 if (config.allowUnlisted) return true;
1314 if (config.allowlist.length) return config.allowlist.includes(fromUser);
1315 return Boolean(botAccount?.userId) && fromUser === botAccount.userId;
1316 }
1317
1318 function processAlive(pid) {
1319 try {
1320 process.kill(pid, 0);
1321 return true;
1322 } catch (error) {
1323 return error.code === "EPERM";
1324 }
1325 }
1326
1327 async function acquireStateLock(stateDir) {
1328 const lockPath = path.join(stateDir, "bridge.lock");
1329 for (let attempt = 0; attempt < 2; attempt += 1) {
1330 try {
1331 const handle = await fs.open(lockPath, "wx", 0o600);
1332 await handle.writeFile(String(process.pid));
1333 await handle.close();
1334 process.once("exit", () => {
1335 try {
1336 if (fsSync.readFileSync(lockPath, "utf8").trim() === String(process.pid)) fsSync.rmSync(lockPath, { force: true });
1337 } catch {}
1338 });
1339 return;
1340 } catch (error) {
1341 if (error.code !== "EEXIST") throw error;
1342 const owner = Number((await fs.readFile(lockPath, "utf8").catch(() => "")).trim());
1343 if (owner && owner !== process.pid && processAlive(owner)) {
1344 throw new Error(`Another Weixin bridge (pid ${owner}) is using ${stateDir}. One state directory serves one bridge; stop it first.`);
1345 }
1346 await fs.rm(lockPath, { force: true });
1347 }
1348 }
1349 throw new Error(`Could not lock the state directory ${stateDir}.`);
1350 }
1351
1352 function sleep(ms) {
1353 return new Promise((resolve) => setTimeout(resolve, ms));
1354 }
1355
1356 // ============================================================================
1357 // 启动流程 — QR 登录 → 长轮询
1358 // ============================================================================
1359
1360 async function main() {
1361 console.log("Starting CodeWhale Weixin Bot Bridge");
1362 console.log(`Runtime: ${config.runtimeUrl}`);
1363 console.log(`Workspace: ${config.workspace}`);
1364 console.log(`State dir: ${config.stateDir}`);
1365 console.log(`Thread map: ${config.threadMapPath}`);
1366
1367 // 初始化 ThreadStore。`open()` 只读,真正的写入发生在第一条消息到达时;
1368 // 那时失败会被 getUpdates 的 catch 吞掉,表现为“微信没有回应”。所以这里
1369 // 先建目录并真实写一次探针文件,把问题在启动时就暴露出来。
1370 try {
1371 const dir = path.dirname(config.threadMapPath);
1372 await fs.mkdir(dir, { recursive: true, mode: 0o700 });
1373 const probe = path.join(dir, ".write-probe");
1374 await fs.writeFile(probe, "", { mode: 0o600 });
1375 await fs.rm(probe, { force: true });
1376 } catch (error) {
1377 console.error(
1378 `Thread map directory is not writable: ${path.dirname(config.threadMapPath)} (${error.message})`
1379 );
1380 console.error(
1381 "Set WEIXIN_STATE_DIR (or WEIXIN_THREAD_MAP_PATH) to a writable directory."
1382 );
1383 process.exit(1);
1384 }
1385 try {
1386 await fs.mkdir(config.stateDir, { recursive: true, mode: 0o700 });
1387 await acquireStateLock(config.stateDir);
1388 } catch (error) {
1389 console.error(error.message);
1390 process.exit(1);
1391 }
1392 threadStore = await CoreThreadStore.open(config.threadMapPath, {
1393 messageLimit: 500,
1394 privateMode: true,
1395 legacyOwnerScope: (chatId, state) => (state.bindingAccountId ? weixinActorId(state.bindingAccountId, chatId) : null)
1396 });
1397
1398 // 尝试加载已有账号
1399 botAccount = await loadAccount(config.stateDir);
1400
1401 if (botAccount?.token) {
1402 console.log("Loaded existing bot account, trying to resume...");
1403 console.log(` accountId: ${botAccount.accountId}`);
1404 console.log(` baseUrl: ${botAccount.baseUrl}`);
1405 } else {
1406 // QR 登录
1407 console.log("No bot account found. Starting QR login...");
1408 console.log("");
1409
1410 const { qrcodeUrl, sessionKey } = await getLoginQR();
1411 console.log("请用微信扫描以下二维码登录:");
1412 // Render the login URL as a scannable terminal QR. The URL is printed too,
1413 // so a terminal that mangles the half-block glyphs still has a way through.
1414 try {
1415 if (qrcodeUrl) console.log(renderQrToText(qrcodeUrl));
1416 } catch (error) {
1417 console.warn(`Could not render QR in terminal: ${error.message}`);
1418 }
1419 console.log(qrcodeUrl);
1420 console.log("");
1421
1422 const result = await waitForLogin({ sessionKey, timeoutMs: 300_000 });
1423
1424 if (!result.connected) {
1425 console.error(`Login failed: ${result.message}`);
1426 process.exit(1);
1427 }
1428
1429 botAccount = {
1430 accountId: result.accountId,
1431 token: result.botToken,
1432 baseUrl: result.baseUrl,
1433 userId: result.userId,
1434 };
1435
1436 await saveAccount(config.stateDir, botAccount);
1437 console.log(`✅ Login successful! accountId=${botAccount.accountId}`);
1438 }
1439
1440 if (!accountIdentity()) throw new Error("The saved bot account has no stable account identity; pair again before receiving messages.");
1441 try { runtimeCapabilities = (await runtimeJson("/v1/runtime/info"))?.capabilities || {}; } catch { console.warn("Engine recovery capabilities unavailable; uncertain admissions will remain retained."); }
1442 await settleLegacyOwners(threadStore, runtimeJson, (thread) => createdByBridge(thread, { systemPrompt: WEIXIN_SYSTEM_PROMPT, workspace: config.workspace }));
1443 for (const [chatId, state] of threadStore.listChats()) {
1444 if (hasPendingWork(state)) startChatRecovery(chatId);
1445 }
1446
1447 // 通知上线
1448 try {
1449 const startResp = await notifyStart({
1450 baseUrl: botAccount.baseUrl,
1451 token: botAccount.token,
1452 });
1453 if (isSessionExpired(startResp)) {
1454 pauseSession("notifystart");
1455 } else if (startResp.ret && startResp.ret !== 0) {
1456 console.warn(`notifyStart: ret=${startResp.ret} errmsg=${startResp.errmsg}`);
1457 } else {
1458 console.log("notifyStart: OK");
1459 }
1460 } catch (error) {
1461 console.error("notifyStart failed:", error.message);
1462 }
1463
1464 // 信号处理
1465 process.once("SIGINT", shutdown);
1466 process.once("SIGTERM", shutdown);
1467
1468 if (!config.allowlist.length && !config.allowUnlisted) {
1469 console.log(botAccount.userId
1470 ? `No allowlist configured; only the WeChat user who scanned the login QR (user_id=${botAccount.userId}) may use this bridge. Other chats are refused once with their user ID.`
1471 : "No allowlist configured and the saved login has no scanner ID. Incoming chats are refused once with their user ID; set WEIXIN_CHAT_ALLOWLIST or scan a new QR code.");
1472 }
1473
1474 // 进入长轮询循环
1475 await monitorLoop();
1476
1477 console.log("Bridge stopped.");
1478 }
1479
1480 async function shutdown() {
1481 if (stopping) return;
1482 stopping = true;
1483 console.log("Shutting down...");
1484 for (const controller of recoveryControllers.values()) controller.abort();
1485 for (const chatId of [...typingStates.keys()]) stopTyping(chatId);
1486
1487 if (botAccount?.token) {
1488 try {
1489 const stopResp = await notifyStop({
1490 baseUrl: botAccount.baseUrl,
1491 token: botAccount.token,
1492 });
1493 console.log(
1494 `notifyStop: ret=${stopResp.ret} errmsg=${stopResp.errmsg ?? "OK"}`
1495 );
1496 } catch (error) {
1497 console.error("notifyStop failed:", error.message);
1498 }
1499 }
1500
1501 setTimeout(() => process.exit(0), 2000);
1502 }
1503
1504 main().catch((error) => {
1505 console.error("Fatal error:", error);
1506 process.exit(1);
1507 });
1508
1508 lines Plain Text