返回 CodeWhale
index.mjs
1 import { WSClient, generateReqId } from "@wecom/aibot-node-sdk";
2 import { mkdir, writeFile } from "node:fs/promises";
3 import path from "node:path";
4
5 import {
6 activeTurnBlock,
7 assertWecomAck,
8 commandAction,
9 createStreamReply,
10 formatPublicError,
11 helpText,
12 incomingIdentity,
13 isAllowed,
14 latestRunningTurn,
15 pairingRefusalText,
16 parseBool,
17 parseCommand,
18 parseList,
19 sanitizeFilename,
20 parseApprovalDecisionArgs,
21 isApprovalResponse,
22 isDenyResponse,
23 preservedChatStateFields,
24 requiredEnv,
25 splitMessage,
26 stripGroupPrefix,
27 ThreadStore
28 } from "./lib.mjs";
29 import {
30 ApprovalOwnershipError,
31 createRuntimeClient,
32 decideApproval as decideRuntimeApproval,
33 createdByBridge,
34 listOwnedThreads,
35 settleLegacyOwners,
36 THREAD_NOT_OWNED_MESSAGE,
37 ThreadOwnershipError,
38 observeTurn,
39 turnOutcomeText
40 } from "../../bridge-core/src/lib.mjs";
41
42 /** Map of chatId -> latest pending approval info for natural-language approval. */
43 const pendingApprovals = new Map();
44
45 const config = {
46 botId: requiredEnv("WECOM_BOT_ID"),
47 botSecret: requiredEnv("WECOM_BOT_SECRET"),
48 runtimeUrl: (process.env.CODEWHALE_RUNTIME_URL || "http://127.0.0.1:7878").replace(/\/+$/, ""),
49 runtimeToken: requiredEnv("CODEWHALE_RUNTIME_TOKEN"),
50 workspace: process.env.CODEWHALE_WORKSPACE || process.cwd(),
51 mediaDir: process.env.WECOM_MEDIA_DIR || "",
52 model: process.env.CODEWHALE_MODEL || "auto",
53 mode: process.env.CODEWHALE_MODE || "agent",
54 allowShell: parseBool(process.env.CODEWHALE_ALLOW_SHELL, true),
55 trustMode: parseBool(process.env.CODEWHALE_TRUST_MODE, false),
56 autoApprove: parseBool(process.env.CODEWHALE_AUTO_APPROVE, false),
57 allowlist: parseList(process.env.WECOM_CHAT_ALLOWLIST),
58 allowUnlisted: parseBool(process.env.WECOM_ALLOW_UNLISTED, false),
59 threadMapPath: process.env.WECOM_THREAD_MAP_PATH || "/var/lib/codewhale-wecom-bridge/thread-map.json",
60 maxReplyChars: Number(process.env.WECOM_MAX_REPLY_CHARS || 3500),
61 maxReplyBytes: Number(process.env.WECOM_MAX_REPLY_BYTES || 3800),
62 turnTimeoutMs: Number(process.env.CODEWHALE_TURN_TIMEOUT_MS || 900000),
63 approvalTimeoutMs: Number(process.env.CODEWHALE_APPROVAL_TIMEOUT_MS || 300000)
64 };
65
66 if (!(config.approvalTimeoutMs > 0)) {
67 throw new Error("CODEWHALE_APPROVAL_TIMEOUT_MS must be a positive number of milliseconds");
68 }
69
70 setInterval(() => {
71 const now = Date.now();
72 for (const [chatId, approval] of pendingApprovals) {
73 if (now - approval.timestamp > config.approvalTimeoutMs) pendingApprovals.delete(chatId);
74 }
75 }, Math.min(120_000, config.approvalTimeoutMs));
76
77 const { runtimeJson, authHeaders } = createRuntimeClient(config);
78
79 const WECOM_SYSTEM_PROMPT =
80 "You are being controlled from a WeCom (企业微信) phone chat. Keep status updates concise. Ask for tool approvals when needed; do not assume mobile messages imply blanket approval.";
81
82 const threadStore = await ThreadStore.open(config.threadMapPath);
83 await settleLegacyOwners(threadStore, runtimeJson, (thread) => createdByBridge(thread, { systemPrompt: WECOM_SYSTEM_PROMPT, workspace: config.workspace }));
84
85 const client = new WSClient({
86 botId: config.botId,
87 secret: config.botSecret
88 });
89
90 client.on("message", async (frame) => {
91 try {
92 await handleIncomingMessage(frame);
93 } catch (error) {
94 await reportHandlerError(frame, "Failed to handle WeCom message", error);
95 }
96 });
97
98 client.on("event", async (frame) => {
99 try {
100 await handleEvent(frame);
101 } catch (error) {
102 await reportHandlerError(frame, "Failed to handle WeCom event", error);
103 }
104 });
105
106 client.on("error", (error) => {
107 console.error("WeCom client error:", error);
108 });
109
110 console.log("Starting CodeWhale WeCom bridge");
111 console.log(`Runtime: ${config.runtimeUrl}`);
112 console.log(`Workspace: ${config.workspace}`);
113 if (!config.allowlist.length && !config.allowUnlisted) {
114 console.log("No allowlist configured. Incoming chats will receive their IDs and be refused.");
115 }
116
117 client.connect();
118
119 function splitReply(text) {
120 // WeCom caps one message at 4096 UTF-8 bytes; without the byte cap a
121 // char-split chunk of CJK text is truncated silently.
122 return splitMessage(text, config.maxReplyChars, config.maxReplyBytes);
123 }
124
125 function replyChunks(frame, chunks) {
126 return chunks.reduce(
127 (chain, chunk) => chain.then(async () => assertWecomAck(await client.replyStream(frame, generateReqId("stream"), chunk, true))),
128 Promise.resolve()
129 );
130 }
131
132 function replyText(frame, text) {
133 return replyChunks(frame, splitReply(text));
134 }
135
136 function isMediaMessage(msgtype) {
137 return msgtype === "video" || msgtype === "file" || msgtype === "image";
138 }
139
140 function mediaStorageDir() {
141 return config.mediaDir || path.join(config.workspace, "media");
142 }
143
144 async function handleMediaMessage(frame, body, identity) {
145 const kind = body.msgtype;
146 const content = body.video || body.file || body.image || {};
147 if (!content.url) {
148 await replyText(frame, "The media message carried no downloadable URL.");
149 return;
150 }
151 const zh = kind === "video" ? "video" : kind === "image" ? "image" : "file";
152 // Download URLs stay valid for ~5 minutes; tell the user before starting.
153 await replyText(frame, `Received ${zh}, downloading (the link is valid for ~5 minutes)…`);
154 try {
155 const { buffer, filename } = await client.downloadFile(content.url, content.aeskey);
156 const dir = mediaStorageDir();
157 await mkdir(dir, { recursive: true });
158 const fallbackExt = kind === "image" ? "jpg" : kind === "video" ? "mp4" : "bin";
159 const name = sanitizeFilename(filename, `upload-${Date.now()}.${fallbackExt}`);
160 let target = path.join(dir, name);
161 try {
162 await writeFile(target, buffer, { flag: "wx" });
163 } catch (error) {
164 if (error?.code !== "EEXIST") throw error;
165 target = path.join(dir, `${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${name}`);
166 await writeFile(target, buffer, { flag: "wx" });
167 }
168 await replyText(
169 frame,
170 `Saved ${path.basename(target)} (${(buffer.length / 1048576).toFixed(1)} MB) to ${target}\n` +
171 `Send follow-up instructions in chat to use it.`
172 );
173 } catch (error) {
174 await replyText(
175 frame,
176 `Download failed (links expire after ~5 minutes; large files should be re-sent promptly): ${error?.errmsg || error?.message || error}`
177 );
178 }
179 }
180
181 async function reportHandlerError(frame, context, error) {
182 console.error(context, error);
183 try {
184 await replyText(frame, `${context}: ${publicBridgeError(error)}`);
185 } catch (replyError) {
186 console.error("Failed to report WeCom bridge error", replyError);
187 }
188 }
189
190 function publicBridgeError(error) {
191 const message = formatPublicError(error);
192 return message.replaceAll(config.runtimeToken, "<redacted>").slice(0, 500);
193 }
194
195 async function handleIncomingMessage(frame) {
196 const body = frame.body || {};
197 const identity = incomingIdentity(body);
198 console.log(`Incoming message: chatId=${identity.chatId} userId=${identity.userId} chatType=${identity.chatType}`);
199 if (!identity.chatId || !identity.messageId) return;
200
201 if (body.msgtype && body.msgtype !== "text" && body.msgtype !== "voice" &&
202 !isMediaMessage(body.msgtype)) {
203 await replyText(frame, `Only text, voice, image, video and file messages are supported (got ${body.msgtype}).`);
204 return;
205 }
206
207 const textContent = body.msgtype === "voice" ? (body.voice?.content || "") : (body.text?.content || "");
208 // Media frames carry no text and must not go through the group-prefix
209 // filter, which rejects empty text and would drop them silently.
210 const scoped = isMediaMessage(body.msgtype)
211 ? { accepted: true, text: "" }
212 : stripGroupPrefix(textContent, {
213 chatType: identity.chatType,
214 requirePrefix: identity.chatType === "group",
215 prefix: "/ds"
216 });
217 if (!scoped.accepted) return;
218
219 if (!isAllowed(identity, config.allowlist, config.allowUnlisted)) {
220 await replyText(frame, pairingRefusalText(identity));
221 return;
222 }
223
224 if (isMediaMessage(body.msgtype)) {
225 await handleMediaMessage(frame, body, identity);
226 return;
227 }
228
229 const command = parseCommand(scoped.text);
230 try {
231 await handleCommand(identity.chatId, command, frame);
232 } catch (error) {
233 if (!(error instanceof ThreadOwnershipError)) throw error;
234 await replyText(frame, THREAD_NOT_OWNED_MESSAGE);
235 }
236 }
237
238 async function handleEvent(frame) {
239 const body = frame.body || {};
240 const eventType = body.event?.eventtype || "";
241 if (eventType === "enter_chat") {
242 const chatId = body.chatid;
243 if (chatId) {
244 assertWecomAck(await client.replyWelcome(frame, { msgtype: "text", text: { content: "欢迎使用 CodeWhale!发送 /help 查看可用命令。" } }));
245 }
246 }
247 }
248
249 async function handleCommand(chatId, command, frame) {
250 const action = commandAction(command);
251 switch (action.kind) {
252 case "help":
253 await replyText(frame, helpText());
254 return;
255 case "status":
256 await sendStatus(chatId, frame);
257 return;
258 case "threads":
259 await sendThreads(chatId, frame);
260 return;
261 case "new_thread": {
262 const state = await ensureThread(chatId, { forceNew: true });
263 await replyText(frame, `Created thread ${state.threadId}`);
264 return;
265 }
266 case "resume":
267 await resumeThread(chatId, action.threadId, frame);
268 return;
269 case "interrupt":
270 await interruptActiveTurn(chatId, frame);
271 return;
272 case "compact":
273 await compactThread(chatId, frame);
274 return;
275 case "approval":
276 await decideApproval(chatId, action, frame);
277 return;
278 case "set_model":
279 await setChatModel(chatId, action.modelName, frame);
280 return;
281 case "prompt":
282 // Check if this is a natural-language approval/deny response
283 // This map supplies an approval id for convenience only. Runtime's
284 // pending turn and its durable initiating human still decide authority.
285 if (pendingApprovals.has(chatId)) {
286 const pending = pendingApprovals.get(chatId);
287 if (Date.now() - pending.timestamp < config.approvalTimeoutMs) {
288 if (isApprovalResponse(action.prompt)) {
289 const action2 = { kind: "approval", decision: "allow", approvalId: pending.approvalId };
290 if (await decideApproval(chatId, action2, frame)) pendingApprovals.delete(chatId);
291 return;
292 }
293 if (isDenyResponse(action.prompt)) {
294 const action2 = { kind: "approval", decision: "deny", approvalId: pending.approvalId };
295 if (await decideApproval(chatId, action2, frame)) pendingApprovals.delete(chatId);
296 return;
297 }
298 }
299 }
300 await runPrompt(chatId, action.prompt, frame);
301 return;
302 default:
303 await replyText(frame, helpText());
304 }
305 }
306
307 async function ensureThread(chatId, { forceNew = false } = {}) {
308 const existing = await threadStore.getChat(chatId);
309 if (existing?.threadId && !forceNew) {
310 threadStore.requireOwnedThread(chatId, existing.threadId);
311 return existing;
312 }
313
314 const effectiveModel = existing?.model || config.model;
315
316 const thread = await runtimeJson("/v1/threads", {
317 method: "POST",
318 body: {
319 model: effectiveModel,
320 workspace: config.workspace,
321 mode: config.mode,
322 allow_shell: config.allowShell,
323 trust_mode: config.trustMode,
324 auto_approve: config.autoApprove,
325 archived: false,
326 system_prompt: WECOM_SYSTEM_PROMPT
327 }
328 });
329
330 const state = {
331 ...preservedChatStateFields(existing),
332 threadId: thread.id,
333 lastSeq: 0,
334 activeTurnId: null,
335 updatedAt: new Date().toISOString()
336 };
337 await threadStore.recordThreadOwner(chatId, thread.id);
338 await threadStore.setChat(chatId, state);
339 return state;
340 }
341
342 function turnActor(identity) {
343 return identity?.userId ? `wecom-user:${identity.userId}` : "";
344 }
345
346 async function runPrompt(chatId, prompt, frame) {
347 if (!prompt.trim()) {
348 await replyText(frame, helpText());
349 return;
350 }
351 const actorId = turnActor(incomingIdentity(frame.body));
352 if (!actorId) throw new ApprovalOwnershipError("turn needs its initiating human");
353 const state = await ensureThread(chatId);
354 const effectiveModel = state?.model || config.model;
355 const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`);
356 const activeBlock = activeTurnBlock(detail, state);
357 if (activeBlock) {
358 await threadStore.patchChat(chatId, {
359 activeTurnId: activeBlock.turnId,
360 updatedAt: new Date().toISOString()
361 });
362 // The turn is still running: forward the message as steering guidance
363 // instead of dropping it. The steer may be dropped by the engine if the
364 // turn moved on first; the Runtime reports that verdict.
365 try {
366 await runtimeJson(
367 `/v1/threads/${encodeURIComponent(state.threadId)}/turns/${encodeURIComponent(activeBlock.turnId)}/steer`,
368 { method: "POST", body: { prompt } }
369 );
370 await replyText(frame, `[running] forwarded to the active turn: ${prompt.slice(0, 80)}`);
371 } catch {
372 await replyText(frame, activeBlock.message);
373 }
374 return;
375 }
376 if (state.activeTurnId) {
377 await threadStore.patchChat(chatId, { activeTurnId: null });
378 }
379 const sinceSeq = Number(detail.latest_seq || state.lastSeq || 0);
380
381 const turnResponse = await runtimeJson(
382 `/v1/threads/${encodeURIComponent(state.threadId)}/turns`,
383 {
384 method: "POST",
385 body: {
386 prompt,
387 input_summary: prompt.slice(0, 200),
388 model: effectiveModel,
389 mode: config.mode,
390 allow_shell: config.allowShell,
391 trust_mode: config.trustMode,
392 auto_approve: config.autoApprove
393 }
394 }
395 );
396
397 const turnId = turnResponse.turn?.id;
398 // A turn the Runtime accepted keeps streaming even when its origin cannot be
399 // recorded; its approvals then fail closed and are decided from the TUI.
400 if (turnId && actorId) {
401 await threadStore.recordTurnOrigin(chatId, state.threadId, turnId, actorId);
402 }
403 await threadStore.patchChat(chatId, {
404 activeTurnId: turnId || null,
405 lastSeq: sinceSeq,
406 responseText: "",
407 updatedAt: new Date().toISOString()
408 });
409 await replyText(frame, `Started turn ${turnId || "(unknown)"}`);
410
411 if (await streamTurnEvents(chatId, frame, state.threadId, turnId, sinceSeq)) {
412 await threadStore.finishObservedTurn(chatId, state.threadId, turnId);
413 }
414 }
415
416 async function finishStream(streamer, frame, text) {
417 const [first = "", ...rest] = splitReply(text);
418 try {
419 await streamer.update(first, true);
420 } catch {
421 return replyText(frame, text);
422 }
423 await replyChunks(frame, rest);
424 }
425
426 async function streamTurnEvents(chatId, frame, threadId, turnId, sinceSeq) {
427 const streamer = createStreamReply(client, frame, { genId: () => generateReqId("stream") });
428 let previewLimitReached = false;
429 return observeTurn({
430 fetchEvents: (seq, signal) => fetch(
431 `${config.runtimeUrl}/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=${seq}`,
432 { headers: authHeaders(), signal }
433 ),
434 threadId,
435 turnId,
436 sinceSeq,
437 responseText: (await threadStore.getChat(chatId))?.responseText || "",
438 timeoutMs: config.turnTimeoutMs,
439 saveCursor: (cursor) => threadStore.patchChat(chatId, cursor),
440 onDelta: async (text) => {
441 if (!previewLimitReached) {
442 previewLimitReached = splitReply(text).length > 1;
443 if (!previewLimitReached) await streamer.update(text, false).catch(() => {});
444 }
445 return text;
446 },
447 onApproval: async (approval) => {
448 const approvalId = approval.approval_id || approval.id;
449 if (approvalId) {
450 pendingApprovals.set(chatId, {
451 approvalId,
452 toolName: approval.tool_name || "unknown",
453 description: approval.description || "",
454 timestamp: Date.now()
455 });
456 }
457 await replyText(
458 frame,
459 [
460 "审批请求",
461 `tool=${approval.tool_name || "unknown"}`,
462 `approval_id=${approvalId}`,
463 approval.description || "",
464 "",
465 `回复 /allow ${approvalId}`,
466 `回复 /deny ${approvalId}`,
467 "也可以直接回复「允许」或「拒绝」"
468 ]
469 .filter(Boolean)
470 .join("\n")
471 );
472 },
473 onTerminal: (outcome) => finishStream(streamer, frame, turnOutcomeText(outcome)),
474 onTimeout: (text) => {
475 const notice = `Turn observation timed out after ${Math.round(config.turnTimeoutMs / 1000)}s.`;
476 return finishStream(streamer, frame, [text, notice].filter(Boolean).join("\n\n"));
477 }
478 });
479 }
480
481 async function sendStatus(chatId, frame) {
482 const [health, runtimeInfo, workspace] = await Promise.all([
483 runtimeJson("/health", { auth: false }),
484 runtimeJson("/v1/runtime/info"),
485 runtimeJson("/v1/workspace/status")
486 ]);
487 await replyText(
488 frame,
489 [
490 `runtime=${health.status || "unknown"}`,
491 `version=${runtimeInfo.version || "unknown"}`,
492 `bind=${runtimeInfo.bind_host}:${runtimeInfo.port}`,
493 `auth_required=${runtimeInfo.auth_required}`,
494 `workspace=${workspace.workspace}`,
495 `git_repo=${workspace.git_repo}`,
496 workspace.branch ? `branch=${workspace.branch}` : "",
497 `staged=${workspace.staged} unstaged=${workspace.unstaged} untracked=${workspace.untracked}`
498 ]
499 .filter(Boolean)
500 .join("\n")
501 );
502 }
503
504 async function sendThreads(chatId, frame) {
505 const threads = await listOwnedThreads(threadStore, runtimeJson, chatId);
506 if (!threads.length) {
507 await replyText(frame, "No threads started by this chat yet.");
508 return;
509 }
510 await replyText(
511 frame,
512 threads
513 .map((thread) => {
514 const status = thread.latest_turn_status || "none";
515 return `${thread.id} [${status}] ${thread.title || thread.preview || ""}`;
516 })
517 .join("\n")
518 );
519 }
520
521 async function resumeThread(chatId, args, frame) {
522 const threadId = args.trim();
523 if (!threadId) {
524 await replyText(frame, "Usage: /resume <thread_id>");
525 return;
526 }
527 if (!threadStore.ownsThread(chatId, threadId)) {
528 await replyText(frame, THREAD_NOT_OWNED_MESSAGE);
529 return;
530 }
531 const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`);
532 const existing = await threadStore.getChat(chatId);
533 await threadStore.setChat(chatId, {
534 ...preservedChatStateFields(existing),
535 threadId,
536 lastSeq: Number(detail.latest_seq || 0),
537 activeTurnId: null,
538 updatedAt: new Date().toISOString()
539 });
540 await replyText(frame, `Resumed thread ${threadId}`);
541 }
542
543 async function interruptActiveTurn(chatId, frame) {
544 const state = await threadStore.getChat(chatId);
545 if (!state?.threadId) {
546 await replyText(frame, "No runtime thread recorded for this chat.");
547 return;
548 }
549 threadStore.requireOwnedThread(chatId, state.threadId);
550 const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`);
551 const runningTurn = latestRunningTurn(detail);
552 const turnId = state.activeTurnId || runningTurn?.id;
553 if (!turnId) {
554 await replyText(frame, "No active turn recorded for this chat.");
555 return;
556 }
557 await runtimeJson(
558 `/v1/threads/${encodeURIComponent(state.threadId)}/turns/${encodeURIComponent(turnId)}/interrupt`,
559 { method: "POST" }
560 );
561 await threadStore.patchChat(chatId, {
562 activeTurnId: turnId,
563 updatedAt: new Date().toISOString()
564 });
565 await replyText(frame, `Interrupt requested for ${turnId}`);
566 }
567
568 async function compactThread(chatId, frame) {
569 const state = await ensureThread(chatId);
570 const result = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}/compact`, {
571 method: "POST",
572 body: { reason: "phone bridge request" }
573 });
574 await replyText(frame, `Compaction started: ${result.turn?.id || "unknown turn"}`);
575 }
576
577 async function decideApproval(chatId, action, frame) {
578 const decision = action.decision;
579 // WeCom approvals are text: a session-wide "remember" is never taken from
580 // a chat message.
581 const { approvalId } =
582 action.approvalId != null ? action : parseApprovalDecisionArgs(action.args);
583 const remember = false;
584 if (!approvalId) {
585 await replyText(frame, `Usage: /${decision} <approval_id>`);
586 return false;
587 }
588 try {
589 await decideRuntimeApproval(runtimeJson, { store: threadStore, chatId, actorId: turnActor(incomingIdentity(frame.body)), approvalId, decision, remember, ownsThread: (threadId) => threadStore.ownsThread(chatId, threadId) });
590 } catch (error) {
591 if (error instanceof ThreadOwnershipError) {
592 await replyText(frame, THREAD_NOT_OWNED_MESSAGE);
593 return false;
594 }
595 if (!(error instanceof ApprovalOwnershipError)) throw error;
596 await replyText(frame, `Approval ${approvalId} is not waiting in this chat.`);
597 return false;
598 }
599
600 // Clear activeTurnId so the user can send follow-up messages
601 // immediately instead of being blocked by activeTurnBlock
602 // while the SSE stream processes the turn cancellation.
603 await threadStore.patchChat(chatId, {
604 activeTurnId: null,
605 updatedAt: new Date().toISOString()
606 });
607
608 await replyText(frame, `Approval ${approvalId}: ${decision}${remember ? " and remember" : ""}`);
609 return true;
610 }
611
612 async function setChatModel(chatId, modelName, frame) {
613 if (!modelName || modelName === "default") {
614 await threadStore.patchChat(chatId, {
615 model: null,
616 updatedAt: new Date().toISOString()
617 });
618 await replyText(frame, `Reset per-chat model. Using bridge default: ${config.model}`);
619 return;
620 }
621 await threadStore.patchChat(chatId, {
622 model: modelName,
623 updatedAt: new Date().toISOString()
624 });
625 await replyText(frame, `Per-chat model set to: ${modelName}`);
626 }
627
627 lines Plain Text