返回 CodeWhale
lib.mjs
1 import { createHash } from "node:crypto";
2 import path from "node:path";
3 import { setTimeout as delay } from "node:timers/promises";
4 import {
5 admitTurn, decideApproval, parseQuestionAnswers, questionText, readThreadEvents, splitAtCodePoint, splitMessage
6 } from "../../bridge-core/src/lib.mjs";
7
8 const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
9 const list = (value) => new Set(String(value || "").split(/[\s,]+/u).filter(Boolean));
10 const bool = (value, name) => {
11 if (value === undefined || value === "false") return false;
12 if (value === "true") return true;
13 throw new Error(`${name} must be true or false`);
14 };
15 const required = (env, name) => {
16 if (!env[name]?.trim()) throw new Error(`${name} is required`);
17 return env[name].trim();
18 };
19
20 export function readConfig(env = process.env) {
21 const runtime = new URL(required(env, "CODEWHALE_RUNTIME_URL"));
22 if (runtime.username || runtime.password || runtime.search || runtime.hash ||
23 (runtime.protocol !== "https:" && !(runtime.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(runtime.hostname)))) {
24 throw new Error("Runtime URL requires HTTPS or loopback HTTP without credentials, query or fragment");
25 }
26 const config = {
27 clientId: required(env, "DINGTALK_CLIENT_ID"), clientSecret: required(env, "DINGTALK_CLIENT_SECRET"),
28 tenants: list(required(env, "DINGTALK_TENANT_ALLOWLIST")), actors: list(required(env, "DINGTALK_ACTOR_ALLOWLIST")),
29 conversations: list(env.DINGTALK_CONVERSATION_ALLOWLIST), allowGroups: bool(env.DINGTALK_ALLOW_GROUPS, "DINGTALK_ALLOW_GROUPS"),
30 runtimeUrl: runtime.href.replace(/\/$/u, ""), runtimeToken: required(env, "CODEWHALE_RUNTIME_TOKEN"),
31 model: env.CODEWHALE_MODEL?.trim() || "auto", workspace: env.CODEWHALE_WORKSPACE?.trim() || null,
32 allowShell: bool(env.CODEWHALE_ALLOW_SHELL, "CODEWHALE_ALLOW_SHELL"),
33 statePath: path.resolve(env.DINGTALK_STATE_PATH || ".state/dingtalk.json"), runtimeRequestTimeoutMs: 15000
34 };
35 if (!config.tenants.size || !config.actors.size || (config.allowGroups && !config.conversations.size)) {
36 throw new Error("DingTalk requires nonempty tenant and actor allowlists, and an explicit conversation allowlist for groups");
37 }
38 return config;
39 }
40
41 export function authorized(config, identity) {
42 return Boolean(identity && config.tenants.has(identity.botTenant) && config.tenants.has(identity.senderTenant) &&
43 config.actors.has(`${identity.senderTenant}:${identity.staffId}`) &&
44 (identity.kind === "1" || (identity.kind === "2" && config.allowGroups && config.conversations.has(`${identity.botTenant}:${identity.conversationId}`))));
45 }
46
47 export function replyRoute(data, now = Date.now()) {
48 const url = new URL(data.sessionWebhook);
49 if (url.protocol !== "https:" || url.hostname !== "oapi.dingtalk.com" || url.port || url.username || url.password || url.hash ||
50 url.pathname !== "/robot/sendBySession" || !url.search || !Number.isSafeInteger(data.sessionWebhookExpiredTime) || data.sessionWebhookExpiredTime <= now) {
51 throw new Error("DingTalk reply route is invalid or expired");
52 }
53 return { url: url.href, expiresAt: data.sessionWebhookExpiredTime };
54 }
55
56 export function incoming(config, frame, now = Date.now()) {
57 if (typeof frame?.headers?.messageId !== "string" || typeof frame.data !== "string" || frame.data.length > 65536) return null;
58 const data = JSON.parse(frame.data);
59 const identity = {
60 botTenant: data.chatbotCorpId, senderTenant: data.senderCorpId, staffId: data.senderStaffId,
61 conversationId: data.conversationId, kind: data.conversationType
62 };
63 if (Object.values(identity).some((value) => typeof value !== "string" || !value || value.length > 512) || !authorized(config, identity) ||
64 (identity.kind === "2" && data.isInAtList !== true) || data.msgtype !== "text" || typeof data.msgId !== "string" || !data.msgId ||
65 typeof data.text?.content !== "string" || !data.text.content.trim() || data.text.content.length > 20000) return null;
66 const tuple = [config.clientId, identity.botTenant, identity.conversationId, identity.senderTenant, identity.staffId];
67 return {
68 chatId: digest(tuple), actorId: `dingtalk:${identity.senderTenant}:${identity.staffId}`, identity,
69 messageKey: digest([...tuple, data.msgId]), text: data.text.content.trim(), route: replyRoute(data, now)
70 };
71 }
72
73 export function createReplySender({ client, fetchImpl = fetch, now = Date.now }) {
74 return async (route, content) => {
75 replyRoute({ sessionWebhook: route.url, sessionWebhookExpiredTime: route.expiresAt }, now());
76 const token = await client.getAccessToken();
77 replyRoute({ sessionWebhook: route.url, sessionWebhookExpiredTime: route.expiresAt }, now());
78 const response = await fetchImpl(route.url, {
79 method: "POST", redirect: "error", signal: AbortSignal.timeout(15000),
80 headers: { "content-type": "application/json", "x-acs-dingtalk-access-token": token },
81 body: JSON.stringify({ msgtype: "text", text: { content } })
82 });
83 const result = await response.json();
84 if (!response.ok || result?.errcode !== 0) throw new Error("DingTalk delivery was not confirmed");
85 };
86 }
87
88 export class DingTalkBridge {
89 constructor({ config, store, runtimeJson, runtimeFetch, sendReply, now = Date.now, report = () => {} }) {
90 Object.assign(this, { config, store, runtimeJson, runtimeFetch, sendReply, now, report });
91 this.serial = Promise.resolve();
92 this.tasks = new Map();
93 this.again = new Map();
94 this.closed = false;
95 this.abort = new AbortController();
96 this.capabilities = {};
97 }
98
99 mutate(operation) {
100 const result = this.serial.then(operation);
101 this.serial = result.catch(() => {});
102 return result;
103 }
104
105 valid(state) {
106 return state?.clientId === this.config.clientId && state.runtimeUrl === this.config.runtimeUrl && authorized(this.config, state.identity) &&
107 state.actorId === `dingtalk:${state.identity.senderTenant}:${state.identity.staffId}`;
108 }
109
110 output(state, id, text) {
111 const outbox = state.outbox || [];
112 if (outbox.some((entry) => entry.id === id)) return outbox;
113 return [...outbox.filter((entry) => entry.status !== "sent").concat(outbox.filter((entry) => entry.status === "sent").slice(-100)),
114 { id, chunks: splitMessage(text || "Turn finished without a text response.", 2000), index: 0, status: "pending" }];
115 }
116
117 async start() {
118 this.capabilities = (await this.runtimeJson("/v1/runtime/info"))?.capabilities || {};
119 for (const [chatId] of this.store.listChats()) {
120 await this.mutate(async () => {
121 const state = await this.store.getChat(chatId);
122 if (!this.valid(state)) return;
123 let outbox = (state.outbox || []).map((entry) => entry.status === "sending" ? { ...entry, status: "uncertain" } : entry);
124 const interrupted = (state.inbox || []).filter((entry) => entry.processing);
125 for (const entry of interrupted) outbox = this.output({ outbox }, `${entry.messageKey}:uncertain`, "A previous command may have reached the Engine. Its result is uncertain; it was not repeated. Use /status to inspect the current turn.");
126 await this.store.patchChat(chatId, { outbox, inbox: (state.inbox || []).filter((entry) => !entry.processing) });
127 });
128 this.kick(chatId);
129 }
130 }
131
132 async accept(frame, acknowledge) {
133 let message;
134 try { message = incoming(this.config, frame, this.now()); } catch { message = null; }
135 if (!message) { acknowledge(); return false; }
136 await this.mutate(async () => {
137 const state = await this.store.getChat(message.chatId) || {};
138 if (state.clientId && !this.valid(state)) throw new Error("DingTalk binding no longer matches current policy");
139 const inbox = state.inbox || [];
140 if (inbox.some((entry) => entry.messageKey === message.messageKey) || state.pendingAdmission?.messageKey === message.messageKey) { await this.store.save(); return; }
141 if (inbox.length >= 100 || (state.outbox || []).filter((entry) => entry.status !== "sent").length >= 100) throw new Error("DingTalk durable queue is full");
142 await this.store.recordMessage(message.messageKey, message.chatId, {
143 clientId: this.config.clientId, runtimeUrl: this.config.runtimeUrl, identity: message.identity, actorId: message.actorId,
144 route: message.route, inbox: [...inbox, { messageKey: message.messageKey, text: message.text }]
145 });
146 await this.store.save();
147 });
148 acknowledge();
149 this.kick(message.chatId);
150 return true;
151 }
152
153 spawn(key, operation) {
154 if (this.closed) return;
155 if (this.tasks.has(key)) { this.again.set(key, operation); return; }
156 const task = Promise.resolve().then(operation).catch((error) => this.report(`DingTalk ${key} transport work retained for recovery: ${error?.stack || error?.message || String(error)}`))
157 .finally(() => {
158 this.tasks.delete(key);
159 const next = this.again.get(key);
160 this.again.delete(key);
161 if (next) this.spawn(key, next);
162 });
163 this.tasks.set(key, task);
164 }
165
166 kick(chatId) {
167 this.spawn(`inbox:${chatId}`, () => this.drain(chatId));
168 this.spawn(`turn:${chatId}`, () => this.runTurn(chatId));
169 this.spawn(`output:${chatId}`, () => this.flush(chatId));
170 }
171
172 async enqueue(chatId, id, text) {
173 await this.mutate(async () => {
174 const state = await this.store.getChat(chatId);
175 await this.store.patchChat(chatId, { outbox: this.output(state, id, text) });
176 });
177 this.spawn(`output:${chatId}`, () => this.flush(chatId));
178 }
179
180 async drain(chatId) {
181 for (;;) {
182 const entry = await this.mutate(async () => {
183 const state = await this.store.getChat(chatId);
184 if (!this.valid(state) || !state.inbox?.length) return null;
185 const entry = { ...state.inbox[0], processing: true };
186 await this.store.patchChat(chatId, { inbox: [entry, ...state.inbox.slice(1)] });
187 return entry;
188 });
189 if (!entry || this.closed) return;
190 try {
191 await this.handle(chatId, entry);
192 } catch {
193 await this.enqueue(chatId, `${entry.messageKey}:error`, "The request could not be confirmed. It will not be repeated automatically. Use /status to inspect the retained state.");
194 }
195 await this.mutate(async () => {
196 const state = await this.store.getChat(chatId);
197 await this.store.patchChat(chatId, { inbox: state.inbox.filter((item) => item.messageKey !== entry.messageKey) });
198 });
199 this.spawn(`turn:${chatId}`, () => this.runTurn(chatId));
200 }
201 }
202
203 async handle(chatId, entry) {
204 const state = await this.store.getChat(chatId);
205 const match = /^\/(\w+)(?:\s+([\s\S]*))?$/u.exec(entry.text);
206 const command = match?.[1]?.toLowerCase();
207 const argument = match?.[2]?.trim() || "";
208 const reply = (text) => this.enqueue(chatId, `${entry.messageKey}:reply`, text);
209 if (command === "help") return reply("Send a task, /status, /stop, /allow APPROVAL_ID, /deny APPROVAL_ID, or /answer QUESTION_ID followed by your answers. Group conversations require an @mention. Only the initiating human can act on a turn.");
210 if (command === "status") return reply(`Thread: ${state.threadId || "not created"}\nTurn: ${state.active?.turnId || "none"}\nAdmission: ${state.pendingAdmission ? "retained; reconciliation pending" : state.threadCreateSubmitted && !state.threadId ? "thread creation uncertain" : "none"}\nUncertain deliveries: ${(state.outbox || []).filter((item) => item.status === "uncertain").length}`);
211 if (["allow", "deny"].includes(command)) {
212 if (!argument || /\s/u.test(argument)) return reply("Specify one approval ID.");
213 await decideApproval(this.runtimeJson, { store: this.store, chatId, actorId: state.actorId, approvalId: argument, decision: command === "allow" ? "allow" : "deny", remember: false });
214 return reply("Approval decision recorded.");
215 }
216 if (["stop", "interrupt"].includes(command)) {
217 if (!state.active || this.store.turnOrigin(chatId, state.threadId, state.active.turnId)?.actorId !== state.actorId) return reply("No owned active turn to stop.");
218 await this.runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}/turns/${encodeURIComponent(state.active.turnId)}/interrupt`, { method: "POST" });
219 return reply("Stop requested.");
220 }
221 if (command === "answer" || (!command && state.active)) {
222 const detail = await this.runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`);
223 const inputId = argument.split(/\s/u)[0];
224 const inputs = (detail.pending_user_inputs || []).filter((input) => input.turn_id === state.active?.turnId &&
225 this.store.turnOrigin(chatId, state.threadId, input.turn_id)?.actorId === state.actorId);
226 const input = command === "answer" ? inputs.find((item) => (item.id || item.input_id) === inputId) : inputs.length === 1 ? inputs[0] : null;
227 if (input) {
228 const answerText = command === "answer" ? argument.slice(inputId.length).trim() : entry.text;
229 const answers = parseQuestionAnswers(input.request, answerText);
230 if (!answers) return reply(questionText(input.request));
231 await this.runtimeJson(`/v1/user-input/${encodeURIComponent(state.threadId)}/${encodeURIComponent(input.id || input.input_id)}`, { method: "POST", body: { answers } });
232 return reply("Answer recorded.");
233 }
234 if (command === "answer") return reply("That question is not pending for your current turn.");
235 }
236 if (command) return reply("Unknown command. Use /help.");
237 if (state.active || state.pendingAdmission) return reply("Your previous task is still active or awaiting reconciliation. Use /status or /stop.");
238 const operationKey = this.capabilities.turn_operation_idempotency === true && this.capabilities.turn_operation_lookup === true ? `dingtalk-${entry.messageKey}` : null;
239 const settings = { model: this.config.model, mode: "agent", allow_shell: this.config.allowShell, trust_mode: false, auto_approve: false };
240 const pending = {
241 messageKey: entry.messageKey, actorId: state.actorId, operationKey, threadId: state.threadId || null, submitted: false, sinceSeq: null,
242 threadRequest: { ...settings, workspace: this.config.workspace, archived: false },
243 request: { ...settings, prompt: entry.text, input_summary: entry.text, ...(operationKey ? { operation_key: operationKey } : {}) }
244 };
245 await this.mutate(async () => {
246 const current = await this.store.getChat(chatId);
247 await this.store.patchChat(chatId, { pendingAdmission: pending, inbox: current.inbox.filter((item) => item.messageKey !== entry.messageKey) });
248 });
249 }
250
251 async runTurn(chatId) {
252 while (!this.closed) {
253 let state = await this.store.getChat(chatId);
254 if (!this.valid(state)) return;
255 try {
256 if (state.pendingAdmission) {
257 const admission = await admitTurn({
258 runtimeJson: this.runtimeJson, pending: state.pendingAdmission, capabilities: this.capabilities,
259 persistPending: (pendingAdmission) => this.store.patchChat(chatId, { pendingAdmission }),
260 ensureThread: async (body) => {
261 const current = await this.store.getChat(chatId);
262 if (current.threadId) return current.threadId;
263 if (current.threadCreateSubmitted) throw new Error("Thread creation is uncertain");
264 await this.store.patchChat(chatId, { threadCreateSubmitted: true });
265 const thread = await this.runtimeJson("/v1/threads", { method: "POST", body });
266 if (typeof thread?.id !== "string" || !thread.id) throw new Error("Invalid Engine thread receipt");
267 await this.store.patchChat(chatId, { threadId: thread.id });
268 return thread.id;
269 }
270 });
271 if (!admission.turn) {
272 await this.enqueue(chatId, `${state.pendingAdmission.messageKey}:admission`, admission.uncertain ? "Task admission is uncertain and cannot be retried safely. An operator must reconcile the Engine receipt." : "Another turn is running in this Engine thread. Your task is retained until it finishes.");
273 if (admission.uncertain) return;
274 await delay(3000, undefined, { signal: this.abort.signal });
275 continue;
276 }
277 await this.store.recordTurnOrigin(chatId, admission.pending.threadId, admission.turn.id, admission.pending.actorId);
278 await this.store.patchChat(chatId, { pendingAdmission: null, active: { turnId: admission.turn.id, seq: admission.pending.sinceSeq, text: "" } });
279 state = await this.store.getChat(chatId);
280 }
281 if (!state.active) return;
282 const response = await this.runtimeFetch(`/v1/threads/${encodeURIComponent(state.threadId)}/events?since_seq=${state.active.seq}`, this.abort.signal);
283 if (!response.ok) throw new Error("Engine event stream unavailable");
284 for await (const record of readThreadEvents(response, state.threadId)) {
285 if (this.closed) return;
286 if (record.event === "stream.end") {
287 if (record.retryable === false) return;
288 break;
289 }
290 await this.consume(chatId, record);
291 if (!(await this.store.getChat(chatId)).active) return;
292 }
293 } catch {
294 if (this.closed) return;
295 const current = await this.store.getChat(chatId);
296 if (current.threadCreateSubmitted && !current.threadId) {
297 await this.enqueue(chatId, `${current.pendingAdmission.messageKey}:thread-uncertain`, "Engine thread creation is uncertain and will not be repeated. An operator must reconcile the original Engine request.");
298 return;
299 }
300 this.report("DingTalk Engine connection interrupted; retained receipts will be reconciled");
301 }
302 await delay(3000, undefined, { signal: this.abort.signal }).catch(() => {});
303 }
304 }
305
306 async consume(chatId, record) {
307 await this.mutate(async () => {
308 const state = await this.store.getChat(chatId);
309 if (!this.valid(state) || !state.active || !Number.isSafeInteger(record.seq) || record.seq <= state.active.seq) return;
310 const active = { ...state.active, seq: record.seq };
311 let outbox = state.outbox || [];
312 let terminal = false;
313 if (record.turn_id === active.turnId) {
314 const payload = record.payload || {};
315 const id = `${active.turnId}:${record.seq}`;
316 if (record.event === "item.delta" && payload.kind === "agent_message" && typeof payload.delta === "string" && !active.textTruncated) {
317 active.text += payload.delta;
318 if (active.text.length > 1_000_000) {
319 const [prefix] = splitAtCodePoint(active.text, 999_900);
320 active.text = `${prefix}\n[Response exceeds the bridge text limit; inspect the Engine transcript.]`;
321 active.textTruncated = true;
322 }
323 }
324 if (record.event === "approval.required") {
325 const approvalId = payload.id || payload.approval_id;
326 outbox = this.output({ outbox }, id, `Approval required: ${payload.tool_name || "tool"}\n${payload.description || ""}\n${approvalId ? `/allow ${approvalId}\n/deny ${approvalId}` : "No approval ID was provided; use the Engine client."}`);
327 }
328 if (record.event === "user_input.required") {
329 const inputId = payload.id || payload.input_id;
330 outbox = this.output({ outbox }, id, `${questionText(payload.request)}\n${inputId ? `/answer ${inputId} followed by your answers.` : "No question ID was provided; use the Engine client."}`);
331 }
332 terminal = record.event === "turn.completed" || (record.event === "turn.lifecycle" && ["failed", "canceled", "interrupted"].includes(payload.turn?.status || payload.status));
333 if (terminal) outbox = this.output({ outbox }, id, active.text || `Turn ${payload.turn?.status || payload.status || "completed"}.`);
334 }
335 await this.store.patchChat(chatId, { active: terminal ? null : active, outbox });
336 });
337 this.spawn(`output:${chatId}`, () => this.flush(chatId));
338 }
339
340 async flush(chatId) {
341 while (!this.closed) {
342 const next = await this.mutate(async () => {
343 const state = await this.store.getChat(chatId);
344 if (!this.valid(state)) return null;
345 const entry = (state.outbox || []).find((item) => item.status === "pending" || item.status === "awaiting_route");
346 if (!entry) return null;
347 try { replyRoute({ sessionWebhook: state.route?.url, sessionWebhookExpiredTime: state.route?.expiresAt }, this.now()); }
348 catch {
349 await this.store.patchChat(chatId, { outbox: state.outbox.map((item) => item.id === entry.id ? { ...item, status: "awaiting_route" } : item) });
350 return null;
351 }
352 await this.store.patchChat(chatId, { outbox: state.outbox.map((item) => item.id === entry.id ? { ...item, status: "sending" } : item) });
353 return { entry, route: state.route };
354 });
355 if (!next) return;
356 let confirmed = false;
357 try { await this.sendReply(next.route, next.entry.chunks[next.entry.index]); confirmed = true; } catch {}
358 await this.mutate(async () => {
359 const state = await this.store.getChat(chatId);
360 await this.store.patchChat(chatId, { outbox: state.outbox.map((item) => item.id !== next.entry.id ? item : {
361 ...item, index: confirmed ? item.index + 1 : item.index,
362 status: confirmed ? item.index + 1 === item.chunks.length ? "sent" : "pending" : "uncertain"
363 }) });
364 });
365 }
366 }
367
368 async stop() {
369 this.closed = true;
370 this.abort.abort();
371 await Promise.allSettled([...this.tasks.values()]);
372 await this.serial;
373 }
374 }
375
375 lines Plain Text