| 1 | import * as Lark from "@larksuiteoapi/node-sdk"; |
| 2 | |
| 3 | import { |
| 4 | activeTurnBlock, |
| 5 | commandAction, |
| 6 | envFirst, |
| 7 | helpText, |
| 8 | incomingIdentity, |
| 9 | isAllowed, |
| 10 | latestRunningTurn, |
| 11 | pairingRefusalText, |
| 12 | parseBool, |
| 13 | parseCommand, |
| 14 | parseList, |
| 15 | parseApprovalDecisionArgs, |
| 16 | parseTextContent, |
| 17 | patchTurnCursor, |
| 18 | preservedChatStateFields, |
| 19 | splitMessage, |
| 20 | FEISHU_MAX_TEXT_CHARS, |
| 21 | stripGroupPrefix |
| 22 | } from "./lib.mjs"; |
| 23 | import { |
| 24 | ApprovalOwnershipError, |
| 25 | createdByBridge, |
| 26 | createRuntimeClient, |
| 27 | decideApproval as decideRuntimeApproval, |
| 28 | listOwnedThreads, |
| 29 | settleLegacyOwners, |
| 30 | THREAD_NOT_OWNED_MESSAGE, |
| 31 | ThreadOwnershipError, |
| 32 | ThreadStore as CoreThreadStore, |
| 33 | splitAtCodePoint, |
| 34 | observeTurn, |
| 35 | turnOutcomeText |
| 36 | } from "../../bridge-core/src/lib.mjs"; |
| 37 | |
| 38 | class ThreadStore extends CoreThreadStore { |
| 39 | constructor(filePath) { |
| 40 | super(filePath, { messageLimit: 200 }); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | const config = { |
| 45 | appId: requiredEnv("FEISHU_APP_ID"), |
| 46 | appSecret: requiredEnv("FEISHU_APP_SECRET"), |
| 47 | domain: process.env.FEISHU_DOMAIN || "feishu", |
| 48 | runtimeUrl: (envFirst(process.env, "CODEWHALE_RUNTIME_URL", "DEEPSEEK_RUNTIME_URL") || "http://127.0.0.1:7878").replace(/\/+$/, ""), |
| 49 | runtimeToken: envFirst(process.env, "CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN") || requiredEnv("CODEWHALE_RUNTIME_TOKEN"), |
| 50 | workspace: envFirst(process.env, "CODEWHALE_WORKSPACE", "DEEPSEEK_WORKSPACE") || process.cwd(), |
| 51 | model: envFirst(process.env, "CODEWHALE_MODEL", "DEEPSEEK_MODEL") || "auto", |
| 52 | mode: envFirst(process.env, "CODEWHALE_MODE", "DEEPSEEK_MODE") || "agent", |
| 53 | allowShell: parseBool(envFirst(process.env, "CODEWHALE_ALLOW_SHELL", "DEEPSEEK_ALLOW_SHELL"), true), |
| 54 | trustMode: parseBool(envFirst(process.env, "CODEWHALE_TRUST_MODE", "DEEPSEEK_TRUST_MODE"), false), |
| 55 | autoApprove: parseBool(envFirst(process.env, "CODEWHALE_AUTO_APPROVE", "DEEPSEEK_AUTO_APPROVE"), false), |
| 56 | allowlist: parseList(envFirst(process.env, "CODEWHALE_CHAT_ALLOWLIST", "DEEPSEEK_CHAT_ALLOWLIST")), |
| 57 | allowUnlisted: parseBool(envFirst(process.env, "CODEWHALE_ALLOW_UNLISTED", "DEEPSEEK_ALLOW_UNLISTED"), false), |
| 58 | threadMapPath: |
| 59 | process.env.FEISHU_THREAD_MAP_PATH || |
| 60 | "/var/lib/codewhale-feishu-bridge/thread-map.json", |
| 61 | allowGroups: parseBool(process.env.FEISHU_ALLOW_GROUPS, false), |
| 62 | requirePrefixInGroup: parseBool(process.env.FEISHU_REQUIRE_PREFIX_IN_GROUP, true), |
| 63 | groupPrefix: process.env.FEISHU_GROUP_PREFIX || "/ds", |
| 64 | maxReplyChars: clampReplyChars(process.env.FEISHU_MAX_REPLY_CHARS, 3500, FEISHU_MAX_TEXT_CHARS), |
| 65 | turnTimeoutMs: Number(envFirst(process.env, "CODEWHALE_TURN_TIMEOUT_MS", "DEEPSEEK_TURN_TIMEOUT_MS") || 900000) |
| 66 | }; |
| 67 | |
| 68 | const { runtimeJson, authHeaders } = createRuntimeClient(config); |
| 69 | |
| 70 | const sdkConfig = { |
| 71 | appId: config.appId, |
| 72 | appSecret: config.appSecret, |
| 73 | domain: resolveLarkDomain(config.domain) |
| 74 | }; |
| 75 | |
| 76 | const client = new Lark.Client(sdkConfig); |
| 77 | const wsClient = new Lark.WSClient({ |
| 78 | ...sdkConfig, |
| 79 | loggerLevel: Lark.LoggerLevel?.info |
| 80 | }); |
| 81 | |
| 82 | const FEISHU_SYSTEM_PROMPT = |
| 83 | "You are being controlled from a Feishu/Lark phone chat. Keep status updates concise. Ask for tool approvals when needed; do not assume mobile messages imply blanket approval."; |
| 84 | |
| 85 | const threadStore = await ThreadStore.open(config.threadMapPath); |
| 86 | const activeTurnTasks = new Map(); |
| 87 | await settleLegacyOwners( |
| 88 | threadStore, |
| 89 | runtimeJson, |
| 90 | (thread) => createdByBridge(thread, { systemPrompt: FEISHU_SYSTEM_PROMPT, workspace: config.workspace }), |
| 91 | { onSettled: (settledThreadIds) => reattachActiveTurns(settledThreadIds) } |
| 92 | ); |
| 93 | |
| 94 | const dispatcher = new Lark.EventDispatcher({}).register({ |
| 95 | "im.message.receive_v1": async (data) => { |
| 96 | void handleIncomingMessage(data).catch((error) => { |
| 97 | console.error("failed to handle incoming Feishu message", error); |
| 98 | }); |
| 99 | } |
| 100 | }); |
| 101 | |
| 102 | console.log("Starting Codewhale Feishu bridge"); |
| 103 | console.log(`Runtime: ${config.runtimeUrl}`); |
| 104 | console.log(`Workspace: ${config.workspace}`); |
| 105 | if (!config.allowlist.length && !config.allowUnlisted) { |
| 106 | console.log("No allowlist configured. Incoming chats will receive their IDs and be refused."); |
| 107 | } |
| 108 | |
| 109 | wsClient.start({ eventDispatcher: dispatcher }); |
| 110 | void reattachActiveTurns().catch((error) => { |
| 111 | console.error("failed to reattach active Feishu bridge turns", error); |
| 112 | }); |
| 113 | |
| 114 | async function handleIncomingMessage(event) { |
| 115 | const identity = incomingIdentity(event); |
| 116 | if (!identity.chatId || !identity.messageId) return; |
| 117 | |
| 118 | if (identity.messageType && identity.messageType !== "text") { |
| 119 | await sendText(identity.chatId, "Only text messages are supported in this first bridge."); |
| 120 | return; |
| 121 | } |
| 122 | |
| 123 | const rawText = parseTextContent(event.message?.content || ""); |
| 124 | const scoped = stripGroupPrefix(rawText, { |
| 125 | chatType: identity.chatType, |
| 126 | requirePrefix: config.requirePrefixInGroup, |
| 127 | prefix: config.groupPrefix |
| 128 | }); |
| 129 | if (!scoped.accepted) return; |
| 130 | |
| 131 | await threadStore.handleMessageOnce(identity.messageId, async () => { |
| 132 | if (identity.chatType !== "p2p" && !config.allowGroups) { |
| 133 | await sendText( |
| 134 | identity.chatId, |
| 135 | "Group chat control is disabled for this bridge. DM the bot, or set FEISHU_ALLOW_GROUPS=true and allowlist this chat." |
| 136 | ); |
| 137 | return; |
| 138 | } |
| 139 | |
| 140 | if (!isAllowed(identity, config.allowlist, config.allowUnlisted)) { |
| 141 | await sendText(identity.chatId, pairingRefusalText(identity)); |
| 142 | return; |
| 143 | } |
| 144 | |
| 145 | // Only an admitted sender may change delivery/recovery provenance. |
| 146 | const { chatId, chatType, openId, unionId, userId } = identity; |
| 147 | await threadStore.patchChat(chatId, { |
| 148 | authorizedIdentity: { chatId, chatType, openId, unionId, userId }, |
| 149 | replyToMessageId: identity.messageId, |
| 150 | updatedAt: new Date().toISOString() |
| 151 | }); |
| 152 | |
| 153 | const command = parseCommand(scoped.text); |
| 154 | try { |
| 155 | await handleCommand(identity.chatId, command, identity); |
| 156 | } catch (error) { |
| 157 | if (!(error instanceof ThreadOwnershipError)) throw error; |
| 158 | await sendText(identity.chatId, THREAD_NOT_OWNED_MESSAGE); |
| 159 | } |
| 160 | }, () => sendText(identity.chatId, "The bridge was interrupted while handling this message. Check /status before sending it again.")); |
| 161 | } |
| 162 | |
| 163 | async function handleCommand(chatId, command, identity) { |
| 164 | const action = commandAction(command); |
| 165 | switch (action.kind) { |
| 166 | case "help": |
| 167 | await sendText(chatId, helpText()); |
| 168 | return; |
| 169 | case "status": |
| 170 | await sendStatus(chatId); |
| 171 | return; |
| 172 | case "threads": |
| 173 | await sendThreads(chatId); |
| 174 | return; |
| 175 | case "new_thread": { |
| 176 | const state = await ensureThread(chatId, { forceNew: true }); |
| 177 | await sendText(chatId, `Created thread ${state.threadId}`); |
| 178 | return; |
| 179 | } |
| 180 | case "resume": |
| 181 | await resumeThread(chatId, action.threadId); |
| 182 | return; |
| 183 | case "interrupt": |
| 184 | await interruptActiveTurn(chatId); |
| 185 | return; |
| 186 | case "compact": |
| 187 | await compactThread(chatId); |
| 188 | return; |
| 189 | case "approval": |
| 190 | await decideApproval(chatId, action, identity); |
| 191 | return; |
| 192 | case "set_model": |
| 193 | await setChatModel(chatId, action.modelName); |
| 194 | return; |
| 195 | case "prompt": |
| 196 | await runPrompt(chatId, action.prompt, identity); |
| 197 | return; |
| 198 | default: |
| 199 | await sendText(chatId, helpText()); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | async function ensureThread(chatId, { forceNew = false } = {}) { |
| 204 | const existing = await threadStore.getChat(chatId); |
| 205 | if (existing?.threadId && !forceNew) { |
| 206 | threadStore.requireOwnedThread(chatId, existing.threadId); |
| 207 | return existing; |
| 208 | } |
| 209 | |
| 210 | // Use per-chat model if set, fall back to bridge-level default. |
| 211 | // / 优先使用 per-chat 模型(/model 命令设置),否则用桥接级别的默认模型。 |
| 212 | const effectiveModel = existing?.model || config.model; |
| 213 | |
| 214 | const thread = await runtimeJson("/v1/threads", { |
| 215 | method: "POST", |
| 216 | body: { |
| 217 | model: effectiveModel, |
| 218 | workspace: config.workspace, |
| 219 | mode: config.mode, |
| 220 | allow_shell: config.allowShell, |
| 221 | trust_mode: config.trustMode, |
| 222 | auto_approve: config.autoApprove, |
| 223 | archived: false, |
| 224 | system_prompt: FEISHU_SYSTEM_PROMPT |
| 225 | } |
| 226 | }); |
| 227 | |
| 228 | const state = { |
| 229 | ...preservedChatStateFields(existing), |
| 230 | threadId: thread.id, |
| 231 | lastSeq: 0, |
| 232 | activeTurnId: null, |
| 233 | activeReplyToMessageId: null, |
| 234 | responseText: "", |
| 235 | updatedAt: new Date().toISOString() |
| 236 | }; |
| 237 | await threadStore.recordThreadOwner(chatId, thread.id); |
| 238 | await threadStore.setChat(chatId, state); |
| 239 | return state; |
| 240 | } |
| 241 | |
| 242 | function turnActor(identity) { |
| 243 | for (const kind of ["openId", "userId", "unionId"]) { |
| 244 | if (identity?.[kind]) return `feishu-${kind}:${identity[kind]}`; |
| 245 | } |
| 246 | return ""; |
| 247 | } |
| 248 | |
| 249 | async function runPrompt(chatId, prompt, identity) { |
| 250 | const replyTarget = identity?.messageId || null; |
| 251 | if (!prompt.trim()) { |
| 252 | await sendText(chatId, helpText(), replyTarget ? { replyToMessageId: replyTarget } : undefined); |
| 253 | return; |
| 254 | } |
| 255 | const actorId = turnActor(identity); |
| 256 | if (!actorId) throw new ApprovalOwnershipError("turn needs its initiating human"); |
| 257 | const hasTasks = typeof activeTurnTasks !== "undefined"; |
| 258 | if (hasTasks && activeTurnTasks.has(chatId)) { |
| 259 | await sendText( |
| 260 | chatId, |
| 261 | "This chat already has an active turn or pending reply delivery. Wait for it to finish or send /interrupt.", |
| 262 | replyTarget ? { replyToMessageId: replyTarget } : undefined |
| 263 | ); |
| 264 | return; |
| 265 | } |
| 266 | const task = { chatId }; |
| 267 | if (hasTasks) activeTurnTasks.set(chatId, task); |
| 268 | try { |
| 269 | const state = await ensureThread(chatId); |
| 270 | const turnReplyToMessageId = replyTarget || state?.replyToMessageId || null; |
| 271 | const deliveryOptions = { replyToMessageId: turnReplyToMessageId }; |
| 272 | if (state?.activeTurnId) { |
| 273 | await sendText( |
| 274 | chatId, |
| 275 | `Thread already has active turn ${state.activeTurnId} pending delivery. Wait for it to finish or send /interrupt.`, |
| 276 | deliveryOptions |
| 277 | ); |
| 278 | return; |
| 279 | } |
| 280 | // Use per-chat model for this turn (may differ from the thread's |
| 281 | // creation model if the user ran /model after the thread was created). |
| 282 | // / 使用 per-chat 模型执行本轮对话(如果用户在创建线程后切换过模型)。 |
| 283 | const effectiveModel = state?.model || config.model; |
| 284 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`); |
| 285 | const activeBlock = activeTurnBlock(detail, state); |
| 286 | if (activeBlock) { |
| 287 | await sendText(chatId, activeBlock.message, deliveryOptions); |
| 288 | return; |
| 289 | } |
| 290 | const sinceSeq = Number(detail.latest_seq || state.lastSeq || 0); |
| 291 | |
| 292 | const turnResponse = await runtimeJson( |
| 293 | `/v1/threads/${encodeURIComponent(state.threadId)}/turns`, |
| 294 | { |
| 295 | method: "POST", |
| 296 | body: { |
| 297 | prompt, |
| 298 | input_summary: prompt.slice(0, 200), |
| 299 | model: effectiveModel, |
| 300 | mode: config.mode, |
| 301 | allow_shell: config.allowShell, |
| 302 | trust_mode: config.trustMode, |
| 303 | auto_approve: config.autoApprove |
| 304 | } |
| 305 | } |
| 306 | ); |
| 307 | |
| 308 | const turnId = turnResponse.turn?.id; |
| 309 | // A turn the Runtime accepted keeps streaming even when its origin cannot be |
| 310 | // recorded; its approvals then fail closed and are decided from the TUI. |
| 311 | if (turnId && actorId) { |
| 312 | await threadStore.recordTurnOrigin(chatId, state.threadId, turnId, actorId); |
| 313 | } |
| 314 | await threadStore.patchChat(chatId, { |
| 315 | activeTurnId: turnId || null, |
| 316 | activeReplyToMessageId: turnReplyToMessageId, |
| 317 | lastSeq: sinceSeq, |
| 318 | responseText: "", |
| 319 | updatedAt: new Date().toISOString() |
| 320 | }); |
| 321 | await sendText(chatId, `Started turn ${turnId || "(unknown)"}`, deliveryOptions); |
| 322 | |
| 323 | if (await streamTurnEvents(chatId, state.threadId, turnId, sinceSeq, deliveryOptions)) { |
| 324 | await threadStore.finishObservedTurn(chatId, state.threadId, turnId); |
| 325 | } |
| 326 | } finally { |
| 327 | if (hasTasks && activeTurnTasks.get(chatId) === task) activeTurnTasks.delete(chatId); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | async function reattachActiveTurns(onlyThreadIds = null) { |
| 332 | const tasks = typeof activeTurnTasks === "undefined" ? null : activeTurnTasks; |
| 333 | for (const [chatId, state] of threadStore.listChats()) { |
| 334 | if (!state?.threadId || !state.activeTurnId) continue; |
| 335 | if (onlyThreadIds && !onlyThreadIds.has(state.threadId)) continue; |
| 336 | const identity = state.authorizedIdentity; |
| 337 | if (!identity || identity.chatId !== chatId || |
| 338 | !["p2p", "group"].includes(identity.chatType) || |
| 339 | (identity.chatType !== "p2p" && !config.allowGroups) || |
| 340 | !isAllowed(identity, config.allowlist, config.allowUnlisted)) continue; |
| 341 | if (threadStore.ownershipPending(chatId, state.threadId)) continue; |
| 342 | if (!threadStore.ownsThread(chatId, state.threadId)) { |
| 343 | await patchTurnCursor(threadStore, chatId, state.threadId, state.activeTurnId, { |
| 344 | activeTurnId: null, |
| 345 | activeReplyToMessageId: null |
| 346 | }); |
| 347 | continue; |
| 348 | } |
| 349 | if (tasks?.has(chatId)) continue; |
| 350 | |
| 351 | const threadId = state.threadId; |
| 352 | const turnId = state.activeTurnId; |
| 353 | const sinceSeq = Number(state.lastSeq || 0); |
| 354 | const replyToMessageId = state.activeReplyToMessageId ?? state.replyToMessageId ?? null; |
| 355 | const deliveryOptions = { replyToMessageId }; |
| 356 | const task = { threadId, turnId }; |
| 357 | tasks?.set(chatId, task); |
| 358 | try { |
| 359 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`); |
| 360 | const turns = Array.isArray(detail?.turns) ? detail.turns : null; |
| 361 | const savedTurn = turns ? turns.find((turn) => turn?.id === turnId) || null : null; |
| 362 | if (turns && !savedTurn) { |
| 363 | await sendText( |
| 364 | chatId, |
| 365 | `Bridge restarted. Recorded turn ${turnId} was not found on ${threadId}.`, |
| 366 | deliveryOptions |
| 367 | ); |
| 368 | await patchTurnCursor(threadStore, chatId, threadId, turnId, { |
| 369 | activeTurnId: null, |
| 370 | activeReplyToMessageId: null, |
| 371 | lastSeq: Number(detail.latest_seq || sinceSeq || 0), |
| 372 | responseText: "" |
| 373 | }); |
| 374 | continue; |
| 375 | } |
| 376 | |
| 377 | const isRunning = !savedTurn || ["queued", "in_progress"].includes(savedTurn.status); |
| 378 | if (isRunning) { |
| 379 | await sendText( |
| 380 | chatId, |
| 381 | `Bridge restarted. Reattaching to active turn ${turnId} from seq ${sinceSeq}.`, |
| 382 | deliveryOptions |
| 383 | ); |
| 384 | } |
| 385 | |
| 386 | const latestSeq = detail?.latest_seq != null ? Number(detail.latest_seq) : null; |
| 387 | const hasReplayEvents = isRunning || latestSeq === null || latestSeq > sinceSeq; |
| 388 | let completed = false; |
| 389 | if (hasReplayEvents) { |
| 390 | completed = await streamTurnEvents(chatId, threadId, turnId, sinceSeq, deliveryOptions); |
| 391 | } |
| 392 | if (!completed && savedTurn && !isRunning) { |
| 393 | const current = await threadStore.getChat(chatId); |
| 394 | if (current?.threadId === threadId && current?.activeTurnId === turnId) { |
| 395 | const fallbackText = turnOutcomeText({ |
| 396 | status: savedTurn.status, |
| 397 | text: current.responseText || "", |
| 398 | error: savedTurn.error || "" |
| 399 | }); |
| 400 | await sendText(chatId, fallbackText, deliveryOptions); |
| 401 | completed = true; |
| 402 | } |
| 403 | } |
| 404 | if (completed) { |
| 405 | await patchTurnCursor(threadStore, chatId, threadId, turnId, { |
| 406 | activeTurnId: null, |
| 407 | activeReplyToMessageId: null, |
| 408 | responseText: "" |
| 409 | }); |
| 410 | } |
| 411 | } catch (error) { |
| 412 | console.error(`failed to reattach Feishu turn ${turnId} for ${chatId}`, error); |
| 413 | } finally { |
| 414 | if (tasks?.get(chatId) === task) tasks.delete(chatId); |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | async function streamTurnEvents(chatId, threadId, turnId, sinceSeq, options = {}) { |
| 420 | let sentProgressAt = Date.now(); |
| 421 | let terminalDelivered = false; |
| 422 | const current = await threadStore.getChat(chatId); |
| 423 | const replyToMessageId = Object.prototype.hasOwnProperty.call(options || {}, "replyToMessageId") |
| 424 | ? (options.replyToMessageId || null) |
| 425 | : (current?.activeReplyToMessageId ?? current?.replyToMessageId ?? null); |
| 426 | const deliveryOptions = { replyToMessageId }; |
| 427 | const initialResponseText = |
| 428 | current?.threadId === threadId && current?.activeTurnId === turnId |
| 429 | ? (current.responseText || "") |
| 430 | : ""; |
| 431 | return observeTurn({ |
| 432 | fetchEvents: (seq, signal) => fetch( |
| 433 | `${config.runtimeUrl}/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=${seq}`, |
| 434 | { headers: authHeaders(), signal } |
| 435 | ), |
| 436 | threadId, |
| 437 | turnId, |
| 438 | sinceSeq, |
| 439 | responseText: initialResponseText, |
| 440 | timeoutMs: config.turnTimeoutMs, |
| 441 | saveCursor: (cursor) => patchTurnCursor( |
| 442 | threadStore, |
| 443 | chatId, |
| 444 | threadId, |
| 445 | turnId, |
| 446 | terminalDelivered |
| 447 | ? { ...cursor, activeTurnId: null, activeReplyToMessageId: null } |
| 448 | : cursor |
| 449 | ), |
| 450 | onDelta: async (text) => { |
| 451 | const now = Date.now(); |
| 452 | if (text.length <= config.maxReplyChars || now - sentProgressAt <= 15000) return text; |
| 453 | const [head, rest] = splitAtCodePoint(text, config.maxReplyChars); |
| 454 | await sendText(chatId, head, deliveryOptions); |
| 455 | sentProgressAt = now; |
| 456 | return rest; |
| 457 | }, |
| 458 | onApproval: (approval) => sendText( |
| 459 | chatId, |
| 460 | [ |
| 461 | "Approval required", |
| 462 | `tool=${approval.tool_name || "unknown"}`, |
| 463 | `approval_id=${approval.approval_id || approval.id}`, |
| 464 | approval.description || "", |
| 465 | "", |
| 466 | `Reply /allow ${approval.approval_id || approval.id}`, |
| 467 | `Reply /deny ${approval.approval_id || approval.id}` |
| 468 | ] |
| 469 | .filter(Boolean) |
| 470 | .join("\n"), |
| 471 | deliveryOptions |
| 472 | ), |
| 473 | onTerminal: async (outcome) => { |
| 474 | await sendText(chatId, turnOutcomeText(outcome), deliveryOptions); |
| 475 | terminalDelivered = true; |
| 476 | }, |
| 477 | onTimeout: () => sendText( |
| 478 | chatId, |
| 479 | `Turn observation timed out after ${Math.round(config.turnTimeoutMs / 1000)}s.`, |
| 480 | deliveryOptions |
| 481 | ) |
| 482 | }); |
| 483 | } |
| 484 | |
| 485 | async function sendStatus(chatId) { |
| 486 | const [health, runtimeInfo, workspace] = await Promise.all([ |
| 487 | runtimeJson("/health", { auth: false }), |
| 488 | runtimeJson("/v1/runtime/info"), |
| 489 | runtimeJson("/v1/workspace/status") |
| 490 | ]); |
| 491 | await sendText( |
| 492 | chatId, |
| 493 | [ |
| 494 | `runtime=${health.status || "unknown"}`, |
| 495 | `version=${runtimeInfo.version || "unknown"}`, |
| 496 | `bind=${runtimeInfo.bind_host}:${runtimeInfo.port}`, |
| 497 | `auth_required=${runtimeInfo.auth_required}`, |
| 498 | `workspace=${workspace.workspace}`, |
| 499 | `git_repo=${workspace.git_repo}`, |
| 500 | workspace.branch ? `branch=${workspace.branch}` : "", |
| 501 | `staged=${workspace.staged} unstaged=${workspace.unstaged} untracked=${workspace.untracked}` |
| 502 | ] |
| 503 | .filter(Boolean) |
| 504 | .join("\n") |
| 505 | ); |
| 506 | } |
| 507 | |
| 508 | async function sendThreads(chatId) { |
| 509 | const threads = await listOwnedThreads(threadStore, runtimeJson, chatId); |
| 510 | if (!threads.length) { |
| 511 | await sendText(chatId, "No threads started by this chat yet."); |
| 512 | return; |
| 513 | } |
| 514 | await sendText( |
| 515 | chatId, |
| 516 | threads |
| 517 | .map((thread) => { |
| 518 | const status = thread.latest_turn_status || "none"; |
| 519 | return `${thread.id} [${status}] ${thread.title || thread.preview || ""}`; |
| 520 | }) |
| 521 | .join("\n") |
| 522 | ); |
| 523 | } |
| 524 | |
| 525 | async function resumeThread(chatId, args) { |
| 526 | const threadId = args.trim(); |
| 527 | if (!threadId) { |
| 528 | await sendText(chatId, "Usage: /resume <thread_id>"); |
| 529 | return; |
| 530 | } |
| 531 | if (!threadStore.ownsThread(chatId, threadId)) { |
| 532 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 533 | return; |
| 534 | } |
| 535 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`); |
| 536 | const existing = await threadStore.getChat(chatId); |
| 537 | await threadStore.setChat(chatId, { |
| 538 | ...preservedChatStateFields(existing), |
| 539 | threadId, |
| 540 | lastSeq: Number(detail.latest_seq || 0), |
| 541 | activeTurnId: null, |
| 542 | activeReplyToMessageId: null, |
| 543 | responseText: "", |
| 544 | updatedAt: new Date().toISOString() |
| 545 | }); |
| 546 | await sendText(chatId, `Resumed thread ${threadId}`); |
| 547 | } |
| 548 | |
| 549 | async function interruptActiveTurn(chatId) { |
| 550 | const state = await threadStore.getChat(chatId); |
| 551 | if (!state?.threadId) { |
| 552 | await sendText(chatId, "No runtime thread recorded for this chat."); |
| 553 | return; |
| 554 | } |
| 555 | threadStore.requireOwnedThread(chatId, state.threadId); |
| 556 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`); |
| 557 | const runningTurn = latestRunningTurn(detail); |
| 558 | const turnId = state.activeTurnId || runningTurn?.id; |
| 559 | if (!turnId) { |
| 560 | await sendText(chatId, "No active turn recorded for this chat."); |
| 561 | return; |
| 562 | } |
| 563 | await runtimeJson( |
| 564 | `/v1/threads/${encodeURIComponent(state.threadId)}/turns/${encodeURIComponent( |
| 565 | turnId |
| 566 | )}/interrupt`, |
| 567 | { method: "POST" } |
| 568 | ); |
| 569 | await threadStore.patchChat(chatId, { |
| 570 | activeTurnId: turnId, |
| 571 | updatedAt: new Date().toISOString() |
| 572 | }); |
| 573 | await sendText(chatId, `Interrupt requested for ${turnId}`); |
| 574 | } |
| 575 | |
| 576 | async function compactThread(chatId) { |
| 577 | const state = await ensureThread(chatId); |
| 578 | const result = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}/compact`, { |
| 579 | method: "POST", |
| 580 | body: { reason: "phone bridge request" } |
| 581 | }); |
| 582 | await sendText(chatId, `Compaction started: ${result.turn?.id || "unknown turn"}`); |
| 583 | } |
| 584 | |
| 585 | async function decideApproval(chatId, action, identity) { |
| 586 | const decision = action.decision; |
| 587 | const { approvalId, remember } = |
| 588 | action.approvalId != null ? action : parseApprovalDecisionArgs(action.args); |
| 589 | if (!approvalId) { |
| 590 | await sendText(chatId, `Usage: /${decision} <approval_id>${decision === "allow" ? " [remember]" : ""}`); |
| 591 | return; |
| 592 | } |
| 593 | try { |
| 594 | await decideRuntimeApproval(runtimeJson, { store: threadStore, chatId, actorId: turnActor(identity), approvalId, decision, remember, ownsThread: (threadId) => threadStore.ownsThread(chatId, threadId) }); |
| 595 | } catch (error) { |
| 596 | if (error instanceof ThreadOwnershipError) { |
| 597 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 598 | return; |
| 599 | } |
| 600 | if (!(error instanceof ApprovalOwnershipError)) throw error; |
| 601 | await sendText(chatId, `Approval ${approvalId} is not waiting in this chat.`); |
| 602 | return; |
| 603 | } |
| 604 | await sendText(chatId, `Approval ${approvalId}: ${decision}${remember ? " and remember" : ""}`); |
| 605 | } |
| 606 | |
| 607 | async function setChatModel(chatId, modelName) { |
| 608 | // /model <name> — set per-chat model; "default" or empty resets to bridge default. |
| 609 | // / /model "default" 或空参数 — 恢复桥接级别的默认模型。 |
| 610 | if (!modelName || modelName === "default") { |
| 611 | await threadStore.patchChat(chatId, { |
| 612 | model: null, |
| 613 | updatedAt: new Date().toISOString() |
| 614 | }); |
| 615 | await sendText(chatId, `Reset per-chat model. Using bridge default: ${config.model}`); |
| 616 | return; |
| 617 | } |
| 618 | await threadStore.patchChat(chatId, { |
| 619 | model: modelName, |
| 620 | updatedAt: new Date().toISOString() |
| 621 | }); |
| 622 | await sendText(chatId, `Per-chat model set to: ${modelName}`); |
| 623 | } |
| 624 | |
| 625 | async function sendText(chatId, text, options = {}) { |
| 626 | // Try reply API first — keeps bot responses inside the same Feishu |
| 627 | // thread/topic instead of spawning new standalone topics. |
| 628 | // / 优先使用 reply API,确保 bot 回复留在话题群的同一条话题内。 |
| 629 | const hasExplicitReplyTarget = Object.prototype.hasOwnProperty.call(options || {}, "replyToMessageId"); |
| 630 | const state = hasExplicitReplyTarget ? null : await threadStore.getChat(chatId); |
| 631 | const replyToMessageId = hasExplicitReplyTarget |
| 632 | ? (options.replyToMessageId || null) |
| 633 | : (state?.replyToMessageId || null); |
| 634 | |
| 635 | const replyMessage = |
| 636 | replyToMessageId |
| 637 | ? client.im?.v1?.message?.reply?.bind(client.im.v1.message) || |
| 638 | client.im?.message?.reply?.bind(client.im.message) |
| 639 | : null; |
| 640 | const createMessage = |
| 641 | client.im?.v1?.message?.create?.bind(client.im.v1.message) || |
| 642 | client.im?.message?.create?.bind(client.im.message); |
| 643 | if (!createMessage) { |
| 644 | throw new Error("Lark SDK client does not expose im message create API"); |
| 645 | } |
| 646 | |
| 647 | let canReply = Boolean(replyMessage); |
| 648 | for (const chunk of splitMessage(text, config.maxReplyChars)) { |
| 649 | const body = { |
| 650 | msg_type: "text", |
| 651 | content: JSON.stringify({ text: chunk }) |
| 652 | }; |
| 653 | if (canReply) { |
| 654 | try { |
| 655 | const result = await replyMessage({ |
| 656 | path: { message_id: replyToMessageId }, |
| 657 | data: body |
| 658 | }); |
| 659 | if (result?.code) { |
| 660 | throw new Error(`Feishu message reply failed (${result.code})`); |
| 661 | } |
| 662 | continue; |
| 663 | } catch (error) { |
| 664 | canReply = false; |
| 665 | console.warn("Feishu reply API failed; falling back to message create", error); |
| 666 | } |
| 667 | } |
| 668 | const result = await createMessage({ |
| 669 | params: { receive_id_type: "chat_id" }, |
| 670 | data: { ...body, receive_id: chatId } |
| 671 | }); |
| 672 | if (result?.code) { |
| 673 | throw new Error(`Feishu message create failed (${result.code})`); |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | function clampReplyChars(raw, fallback, max) { |
| 679 | const parsed = Number(raw || fallback); |
| 680 | if (!Number.isFinite(parsed) || parsed <= 0) return fallback; |
| 681 | return Math.min(Math.floor(parsed), max); |
| 682 | } |
| 683 | |
| 684 | function requiredEnv(name) { |
| 685 | const value = process.env[name]; |
| 686 | if (!value || !value.trim()) { |
| 687 | throw new Error(`${name} is required`); |
| 688 | } |
| 689 | return value.trim(); |
| 690 | } |
| 691 | |
| 692 | function resolveLarkDomain(domain) { |
| 693 | const normalized = String(domain || "feishu").toLowerCase(); |
| 694 | if (normalized === "lark") return Lark.Domain?.Lark || "https://open.larksuite.com"; |
| 695 | if (normalized === "feishu") return Lark.Domain?.Feishu || "https://open.feishu.cn"; |
| 696 | return domain; |
| 697 | } |
| 698 |