返回 CodeWhale
lib.mjs
1 import {
2 activeTurnBlock,
3 cleanEnvValue,
4 commandAction as coreCommandAction,
5 compactRuntimeError,
6 isPlaceholderValue,
7 latestRunningTurn,
8 parseApprovalDecisionArgs,
9 parseBool,
10 parseCommand,
11 parseList,
12 parseTextContent as coreParseTextContent,
13 preservedChatStateFields,
14 splitMessage,
15 stripGroupPrefix as coreStripGroupPrefix,
16 ThreadStore as CoreThreadStore
17 } from "../../bridge-core/src/lib.mjs";
18
19 export {
20 activeTurnBlock,
21 cleanEnvValue,
22 compactRuntimeError,
23 isPlaceholderValue,
24 latestRunningTurn,
25 parseApprovalDecisionArgs,
26 parseBool,
27 parseCommand,
28 parseList,
29 preservedChatStateFields,
30 splitMessage
31 };
32
33 export function requiredEnv(name) {
34 const value = process.env[name];
35 if (!value || !value.trim()) {
36 throw new Error(`${name} is required`);
37 }
38 return value.trim();
39 }
40
41 export function parseTextContent(content) {
42 return coreParseTextContent(content, ["text"]);
43 }
44
45 export function incomingIdentity(body) {
46 const from = body?.from || {};
47 const chatId = body.chatid || (body.chattype === "single" && from.userid ? `single:${from.userid}` : "");
48 return {
49 chatId,
50 messageId: body.msgid || "",
51 chatType: body.chattype || "single",
52 userId: from.userid || "",
53 aibotId: body.aibotid || ""
54 };
55 }
56
57 export function isAllowed(identity, allowlist, allowUnlisted = false) {
58 if (allowUnlisted) return true;
59 const allowed = new Set(allowlist);
60 return [identity.chatId, identity.userId].filter(Boolean).some((id) => allowed.has(id));
61 }
62
63 export function pairingRefusalText(identity) {
64 return [
65 "This chat is not in WECOM_CHAT_ALLOWLIST.",
66 `chat_id=${identity.chatId}`,
67 identity.userId ? `user_id=${identity.userId}` : ""
68 ]
69 .filter(Boolean)
70 .join("\n");
71 }
72
73 export function stripGroupPrefix(text, { chatType, requirePrefix, prefix }) {
74 return coreStripGroupPrefix(text, {
75 chatType,
76 requirePrefix,
77 prefix: prefix || "/ds",
78 directChatTypes: ["single"]
79 });
80 }
81
82 /** Reduce a provider-supplied filename to a safe single path component. */
83 export function sanitizeFilename(name, fallback = "upload.bin") {
84 const cleaned = String(name || "")
85 .replace(/[\\/]/g, "_")
86 // eslint-disable-next-line no-control-regex
87 .replace(/[\u0000-\u001f]/g, "")
88 .replace(/^[.\s]+/, "")
89 .replace(/[\s.]+$/, "")
90 .slice(0, 120);
91 return cleaned || fallback;
92 }
93
94 /**
95 * Render an error for a chat reply. WeCom SDK rejections arrive as plain
96 * objects ({errcode, errmsg}); String() on those yields "[object Object]".
97 */
98 export function formatPublicError(error) {
99 if (error && typeof error === "object") {
100 if (error.errmsg != null || error.errcode != null) {
101 return `errcode=${error.errcode}: ${error.errmsg || ""}`.trim();
102 }
103 if (error.message) return String(error.message);
104 try { return JSON.stringify(error).slice(0, 300); } catch { return "unknown error"; }
105 }
106 return String(error || "unknown error");
107 }
108
109 export function assertWecomAck(result) {
110 const ack = result?.body && typeof result.body === "object" ? result.body : result;
111 if (ack && typeof ack === "object" && ack.errcode != null && ack.errcode !== 0) {
112 throw ack;
113 }
114 return result;
115 }
116
117 /**
118 * Wrap client.replyStream with a WeCom stream lifetime policy. WeCom stream
119 * messages stop accepting updates after ~10 minutes (errcode 846608), so a
120 * long-running turn outlives its stream and every later update fails. This
121 * helper finalizes the current stream and opens a fresh one when it nears
122 * the cap, and reopens once on a rejected update.
123 */
124 export function createStreamReply(client, frame, { rotateMs = 8 * 60_000, now = Date.now, genId } = {}) {
125 let streamId = genId ? genId() : `stream-${Math.random().toString(36).slice(2)}`;
126 let openedAt = now();
127 async function send(id, text, finish) {
128 assertWecomAck(await client.replyStream(frame, id, text, finish));
129 }
130 return {
131 get streamId() { return streamId; },
132 async update(text, finish = false) {
133 if (!finish && now() - openedAt > rotateMs) {
134 try { await send(streamId, `${text}\n…(continued)`, true); } catch { /* expired already */ }
135 streamId = genId ? genId() : `stream-${Math.random().toString(36).slice(2)}`;
136 openedAt = now();
137 }
138 try {
139 await send(streamId, text, finish);
140 } catch {
141 streamId = genId ? genId() : `stream-${Math.random().toString(36).slice(2)}`;
142 openedAt = now();
143 try { await send(streamId, text, finish); }
144 catch (e) { console.error("stream update failed twice", e); throw e; }
145 }
146 }
147 };
148 }
149
150 /** Check if text is a natural-language approval response (Chinese or English). */
151 export function isApprovalResponse(text) {
152 const t = String(text || "").trim().toLowerCase();
153 // Single-word approvals
154 if (["允许", "可以", "好", "同意", "批准", "yes", "ok", "y", "approve", "allow"].includes(t)) return true;
155 // Two-char approvals
156 if (["好的", "可以", "没问题", "批准了", "同意"].includes(t)) return true;
157 return false;
158 }
159
160 /** Check if text is a natural-language deny response. */
161 export function isDenyResponse(text) {
162 const t = String(text || "").trim().toLowerCase();
163 if (["拒绝", "不行", "不要", "no", "n", "deny", "reject", "取消", "stop", "否"].includes(t)) return true;
164 if (["不可以", "不同意", "不要执行"].includes(t)) return true;
165 return false;
166 }
167
168 export function commandAction(command) {
169 return coreCommandAction(command);
170 }
171
172 export function helpText() {
173 return [
174 "CodeWhale 企业微信桥接命令:",
175 "/help - 显示帮助",
176 "/status - runtime 和工作区状态",
177 "/threads - 最近的 runtime 线程",
178 "/new - 为此聊天创建新线程",
179 "/resume <thread_id> - 绑定到此聊天的现有线程",
180 "/model <name|default> - 设置或重置聊天模型",
181 "/interrupt - 中断活动 turn",
182 "/compact - 压缩当前线程",
183 "/allow <approval_id> - 批准待处理的工具调用",
184 "/deny <approval_id> - 拒绝待处理的工具调用",
185 "",
186 "其他所有内容均作为 CodeWhale 提示发送。"
187 ].join("\n");
188 }
189
190 export class ThreadStore extends CoreThreadStore {
191 constructor(filePath) {
192 super(filePath, { privateMode: true });
193 }
194 }
195
196 export function validateBridgeConfig(env) {
197 const errors = [];
198 const warnings = [];
199 const info = [];
200 const add = (list, code, message) => list.push({ code, message });
201
202 for (const key of ["WECOM_BOT_ID", "WECOM_BOT_SECRET"]) {
203 const value = cleanEnvValue(env[key]);
204 if (!value) {
205 add(errors, "missing_required", `${key} is required`);
206 } else if (isPlaceholderValue(value)) {
207 add(errors, "placeholder_value", `${key} still contains a placeholder value`);
208 }
209 }
210
211 const runtimeUrl = cleanEnvValue(env.CODEWHALE_RUNTIME_URL || "http://127.0.0.1:7878");
212 try {
213 const parsed = new URL(runtimeUrl);
214 if (!["http:", "https:"].includes(parsed.protocol)) {
215 add(errors, "invalid_runtime_url", "CODEWHALE_RUNTIME_URL must use http or https");
216 }
217 } catch {
218 add(errors, "invalid_runtime_url", "CODEWHALE_RUNTIME_URL is not a valid URL");
219 }
220
221 const runtimeToken = cleanEnvValue(env.CODEWHALE_RUNTIME_TOKEN);
222 if (!runtimeToken) {
223 add(errors, "missing_runtime_token", "CODEWHALE_RUNTIME_TOKEN is required");
224 } else if (isPlaceholderValue(runtimeToken)) {
225 add(errors, "placeholder_runtime_token", "CODEWHALE_RUNTIME_TOKEN is still a placeholder");
226 }
227
228 const allowUnlisted = parseBool(env.WECOM_ALLOW_UNLISTED, false);
229 const allowlist = parseList(env.WECOM_CHAT_ALLOWLIST);
230
231 if (!allowlist.length && allowUnlisted) {
232 add(warnings, "pairing_mode_open", "WECOM_ALLOW_UNLISTED=true leaves first-pairing mode open");
233 } else if (!allowlist.length) {
234 add(warnings, "not_paired", "WECOM_CHAT_ALLOWLIST is empty; all chats will be refused");
235 }
236
237 return { ok: errors.length === 0, errors, warnings, info };
238 }
239
240 export function formatValidationReport(result) {
241 const lines = ["WeCom bridge config validation"];
242 for (const item of result.errors) lines.push(`[fail] ${item.message}`);
243 for (const item of result.warnings) lines.push(`[warn] ${item.message}`);
244 for (const item of result.info) lines.push(`[info] ${item.message}`);
245 if (result.ok) lines.push("[ok] No blocking config errors found");
246 return lines.join("\n");
247 }
248
248 lines Plain Text