| 1 | import { createHash } from "node:crypto"; |
| 2 | import { |
| 3 | activeTurnKeyboard, |
| 4 | approvalKeyboard, |
| 5 | callbackAction, |
| 6 | commandAction, |
| 7 | compactRuntimeError, |
| 8 | controlKeyboard, |
| 9 | envFirst, |
| 10 | helpText, |
| 11 | isAllowed, |
| 12 | isGroupChat, |
| 13 | isPermanentTelegramError, |
| 14 | isTelegramMarkdownParseError, |
| 15 | latestRunningTurn, |
| 16 | looksLikePollingConflict, |
| 17 | pairingRefusalText, |
| 18 | parseBool, |
| 19 | parseCommand, |
| 20 | parseList, |
| 21 | preservedChatStateFields, |
| 22 | splitMessage, |
| 23 | stripGroupPrefix, |
| 24 | threadListKeyboard, |
| 25 | telegramIdentity, |
| 26 | telegramMessageBody, |
| 27 | telegramPollingConflictDelayMs, |
| 28 | telegramRetryDelayMs, |
| 29 | telegramSendRetryDelayMs |
| 30 | } from "./lib.mjs"; |
| 31 | import { |
| 32 | admitTurn, |
| 33 | questionText, |
| 34 | parseQuestionAnswers, |
| 35 | createdByBridge, |
| 36 | createRuntimeClient, |
| 37 | listOwnedThreads, |
| 38 | readJsonSafe, |
| 39 | readThreadEvents, |
| 40 | settleLegacyOwners, |
| 41 | THREAD_NOT_OWNED_MESSAGE, |
| 42 | ThreadOwnershipError, |
| 43 | ThreadStore as CoreThreadStore, |
| 44 | ApprovalOwnershipError, |
| 45 | decideApproval as decideRuntimeApproval, |
| 46 | settleStoredApproval, |
| 47 | splitAtCodePoint |
| 48 | } from "../../bridge-core/src/lib.mjs"; |
| 49 | |
| 50 | const TYPING_INTERVAL_MS = 2000; |
| 51 | const TYPING_TIMEOUT_MS = 1500; |
| 52 | const LAST_SEQ_FLUSH_INTERVAL_MS = 2000; |
| 53 | |
| 54 | class ThreadStore extends CoreThreadStore { |
| 55 | constructor(filePath) { |
| 56 | super(filePath, { messageLimit: 500, actions: true }); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | const config = { |
| 61 | botToken: requiredEnv("TELEGRAM_BOT_TOKEN"), |
| 62 | apiBase: (process.env.TELEGRAM_API_BASE || "https://api.telegram.org").replace(/\/+$/, ""), |
| 63 | runtimeUrl: (envFirst(process.env, "CODEWHALE_RUNTIME_URL", "DEEPSEEK_RUNTIME_URL") || "http://127.0.0.1:7878").replace(/\/+$/, ""), |
| 64 | runtimeToken: requiredEnvFirst("CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN"), |
| 65 | workspace: envFirst(process.env, "CODEWHALE_WORKSPACE", "DEEPSEEK_WORKSPACE") || process.cwd(), |
| 66 | model: envFirst(process.env, "CODEWHALE_MODEL", "DEEPSEEK_MODEL") || "auto", |
| 67 | mode: envFirst(process.env, "CODEWHALE_MODE", "DEEPSEEK_MODE") || "agent", |
| 68 | allowShell: parseBool(envFirst(process.env, "CODEWHALE_ALLOW_SHELL", "DEEPSEEK_ALLOW_SHELL"), true), |
| 69 | trustMode: parseBool(envFirst(process.env, "CODEWHALE_TRUST_MODE", "DEEPSEEK_TRUST_MODE"), false), |
| 70 | autoApprove: parseBool(envFirst(process.env, "CODEWHALE_AUTO_APPROVE", "DEEPSEEK_AUTO_APPROVE"), false), |
| 71 | allowlist: parseList( |
| 72 | envFirst(process.env, "TELEGRAM_CHAT_ALLOWLIST", "CODEWHALE_CHAT_ALLOWLIST", "DEEPSEEK_CHAT_ALLOWLIST") |
| 73 | ), |
| 74 | allowUnlisted: parseBool( |
| 75 | envFirst(process.env, "TELEGRAM_ALLOW_UNLISTED", "CODEWHALE_ALLOW_UNLISTED", "DEEPSEEK_ALLOW_UNLISTED"), |
| 76 | false |
| 77 | ), |
| 78 | threadMapPath: |
| 79 | process.env.TELEGRAM_THREAD_MAP_PATH || |
| 80 | "/var/lib/codewhale-telegram-bridge/thread-map.json", |
| 81 | allowGroups: parseBool(process.env.TELEGRAM_ALLOW_GROUPS, false), |
| 82 | requirePrefixInGroup: parseBool(process.env.TELEGRAM_REQUIRE_PREFIX_IN_GROUP, true), |
| 83 | groupPrefix: process.env.TELEGRAM_GROUP_PREFIX || "/cw", |
| 84 | maxReplyChars: Math.min(Number(process.env.TELEGRAM_MAX_REPLY_CHARS || 3500), 4096), |
| 85 | pollTimeoutSeconds: Number(process.env.TELEGRAM_POLL_TIMEOUT_SECONDS || 50), |
| 86 | turnTimeoutMs: Number(envFirst(process.env, "CODEWHALE_TURN_TIMEOUT_MS", "DEEPSEEK_TURN_TIMEOUT_MS") || 900000) |
| 87 | }; |
| 88 | |
| 89 | const { runtimeJson, authHeaders } = createRuntimeClient({ ...config, runtimeRequestTimeoutMs: 15000 }); |
| 90 | const botAccountId = config.botToken.split(":")[0]; |
| 91 | let runtimeCapabilities = {}; |
| 92 | |
| 93 | const TELEGRAM_SYSTEM_PROMPT = |
| 94 | "You are being controlled from a Telegram phone chat. Keep status updates concise. Ask for tool approvals when needed; do not assume mobile messages imply blanket approval."; |
| 95 | |
| 96 | const threadStore = await ThreadStore.open(config.threadMapPath); |
| 97 | const activeTurnTasks = new Map(); |
| 98 | let stopping = false; |
| 99 | let updateOffset = threadStore.getCursor( |
| 100 | "telegram.update_offset", |
| 101 | Number(process.env.TELEGRAM_UPDATE_OFFSET || 0) |
| 102 | ); |
| 103 | |
| 104 | function requestStop() { |
| 105 | stopping = true; |
| 106 | abortActiveTurnStreams(); |
| 107 | } |
| 108 | |
| 109 | process.once("SIGINT", requestStop); |
| 110 | process.once("SIGTERM", requestStop); |
| 111 | |
| 112 | console.log("Starting CodeWhale Telegram bridge"); |
| 113 | console.log(`Runtime: ${config.runtimeUrl}`); |
| 114 | console.log(`Workspace: ${config.workspace}`); |
| 115 | if (!config.allowlist.length && !config.allowUnlisted) { |
| 116 | console.log("No allowlist configured. Incoming chats will receive their IDs and be refused."); |
| 117 | } |
| 118 | |
| 119 | try { |
| 120 | runtimeCapabilities = (await runtimeJson("/v1/runtime/info"))?.capabilities || {}; |
| 121 | } catch { |
| 122 | console.warn("Engine recovery capabilities unavailable; uncertain admissions will remain retained."); |
| 123 | } |
| 124 | await settleLegacyOwners(threadStore, runtimeJson, (thread) => createdByBridge(thread, { systemPrompt: TELEGRAM_SYSTEM_PROMPT, workspace: config.workspace })); |
| 125 | await configureBotCommands().catch((error) => { |
| 126 | console.error("failed to configure Telegram bot command menu", error); |
| 127 | }); |
| 128 | void reattachActiveTurns().catch((error) => { |
| 129 | console.error("failed to reattach active Telegram bridge turns", error); |
| 130 | }); |
| 131 | await pollTelegram(); |
| 132 | |
| 133 | async function configureBotCommands() { |
| 134 | await telegramApi("setMyCommands", { |
| 135 | commands: [ |
| 136 | { command: "menu", description: "Open CodeWhale controls" }, |
| 137 | { command: "status", description: "Show runtime and workspace status" }, |
| 138 | { command: "threads", description: "List recent runtime threads" }, |
| 139 | { command: "new", description: "Create a new thread" }, |
| 140 | { command: "interrupt", description: "Interrupt the active turn" }, |
| 141 | { command: "answer", description: "Answer the current agent question" }, |
| 142 | { command: "compact", description: "Compact the current thread" }, |
| 143 | { command: "help", description: "Show command help" } |
| 144 | ] |
| 145 | }); |
| 146 | } |
| 147 | |
| 148 | async function pollTelegram() { |
| 149 | let pollingConflictAttempts = 0; |
| 150 | while (!stopping) { |
| 151 | try { |
| 152 | const updates = await telegramApi("getUpdates", { |
| 153 | offset: updateOffset || undefined, |
| 154 | timeout: config.pollTimeoutSeconds, |
| 155 | allowed_updates: ["message", "callback_query"] |
| 156 | }); |
| 157 | pollingConflictAttempts = 0; |
| 158 | for (const update of updates || []) { |
| 159 | try { |
| 160 | await handleIncomingUpdate(update); |
| 161 | await markUpdateHandled(update); |
| 162 | } catch (error) { |
| 163 | console.error("failed to handle incoming Telegram update", error); |
| 164 | if (isPermanentTelegramError(error)) { |
| 165 | await markUpdateHandled(update); |
| 166 | continue; |
| 167 | } |
| 168 | await delay(telegramRetryDelayMs(error)); |
| 169 | break; |
| 170 | } |
| 171 | } |
| 172 | } catch (error) { |
| 173 | if (looksLikePollingConflict(error)) { |
| 174 | const waitMs = telegramPollingConflictDelayMs(pollingConflictAttempts); |
| 175 | pollingConflictAttempts += 1; |
| 176 | if (waitMs == null) { |
| 177 | throw new Error( |
| 178 | "Telegram getUpdates conflict; another bridge is polling this bot token. Stop the other bridge process or use a different token." |
| 179 | ); |
| 180 | } |
| 181 | console.warn( |
| 182 | `Telegram getUpdates conflict; another bridge is polling this bot. Retrying in ${Math.round(waitMs / 1000)}s.` |
| 183 | ); |
| 184 | await delay(waitMs); |
| 185 | continue; |
| 186 | } |
| 187 | pollingConflictAttempts = 0; |
| 188 | const waitMs = telegramRetryDelayMs(error); |
| 189 | console.error(`Telegram poll failed: ${error.message}. Retrying in ${Math.round(waitMs / 1000)}s.`); |
| 190 | await delay(waitMs); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | async function markUpdateHandled(update) { |
| 196 | if (update.update_id == null) return; |
| 197 | if (!Number.isFinite(Number(update.update_id))) return; |
| 198 | const nextOffset = Math.max(updateOffset, Number(update.update_id) + 1); |
| 199 | if (nextOffset === updateOffset) return; |
| 200 | updateOffset = nextOffset; |
| 201 | await threadStore.setCursor("telegram.update_offset", updateOffset); |
| 202 | } |
| 203 | |
| 204 | async function handleIncomingUpdate(update) { |
| 205 | if (update.callback_query) { |
| 206 | if (await isReplayCallbackUpdate(update)) return; |
| 207 | await handleCallbackQuery(update.callback_query); |
| 208 | return; |
| 209 | } |
| 210 | |
| 211 | const identity = telegramIdentity(update); |
| 212 | if (!identity.chatId || !identity.messageId) return; |
| 213 | if (identity.isBot) return; |
| 214 | |
| 215 | if (!identity.text) { |
| 216 | await sendText(identity.chatId, "Only text messages are supported in this first bridge."); |
| 217 | return; |
| 218 | } |
| 219 | |
| 220 | const scoped = stripGroupPrefix(identity.text, { |
| 221 | chatType: identity.chatType, |
| 222 | requirePrefix: config.requirePrefixInGroup, |
| 223 | prefix: config.groupPrefix |
| 224 | }); |
| 225 | if (!scoped.accepted) return; |
| 226 | |
| 227 | if (isGroupChat(identity.chatType) && !config.allowGroups) { |
| 228 | await sendText( |
| 229 | identity.chatId, |
| 230 | "Group chat control is disabled for this bridge. DM the bot, or set TELEGRAM_ALLOW_GROUPS=true and allowlist this chat." |
| 231 | ); |
| 232 | return; |
| 233 | } |
| 234 | |
| 235 | if (!isAllowed(identity, config.allowlist, config.allowUnlisted)) { |
| 236 | await sendText(identity.chatId, pairingRefusalText(identity)); |
| 237 | return; |
| 238 | } |
| 239 | |
| 240 | const command = parseCommand(scoped.text); |
| 241 | const messageKey = JSON.stringify([botAccountId, identity.chatId, identity.messageId]); |
| 242 | if (["prompt", "answer"].includes(commandAction(command).kind)) { |
| 243 | const state = await threadStore.getChat(identity.chatId); |
| 244 | if (state?.pendingAdmission?.messageKey === messageKey || state?.activeMessageKey === messageKey) { |
| 245 | await threadStore.save(); |
| 246 | startTrackedTurnStream(identity.chatId); |
| 247 | return; |
| 248 | } |
| 249 | } else if (await threadStore.recordMessage(messageKey)) return; |
| 250 | await rememberAuthorizedIdentity(identity); |
| 251 | await handleCommand(identity.chatId, command, { ...identity, messageKey }); |
| 252 | } |
| 253 | |
| 254 | async function rememberAuthorizedIdentity({ chatId, chatType, userId, username, isBot }) { |
| 255 | await threadStore.patchChat(chatId, { |
| 256 | authorizedIdentity: { chatId, chatType, userId, username, isBot } |
| 257 | }); |
| 258 | } |
| 259 | |
| 260 | async function isReplayCallbackUpdate(update) { |
| 261 | if (update.update_id == null) return false; |
| 262 | return threadStore.recordMessage(`callback:${update.update_id}`); |
| 263 | } |
| 264 | |
| 265 | async function releaseUnownedRecovery(chatId) { |
| 266 | const state = await threadStore.getChat(chatId); |
| 267 | if (!state?.threadId || threadStore.ownsThread(chatId, state.threadId) || threadStore.ownershipPending(chatId, state.threadId)) return state; |
| 268 | if (!state.pendingAdmission && !state.activeTurnId && !state.pendingQuestion) return state; |
| 269 | await clearActiveTurn(chatId); |
| 270 | return threadStore.patchChat(chatId, { pendingAdmission: null }); |
| 271 | } |
| 272 | |
| 273 | async function handleCommand(chatId, command, identity) { |
| 274 | await releaseUnownedRecovery(chatId); |
| 275 | const action = commandAction(command); |
| 276 | if (["new_thread", "resume", "compact"].includes(action.kind)) { |
| 277 | const state = await threadStore.getChat(chatId); |
| 278 | if (state?.pendingAdmission || state?.activeTurnId || state?.pendingReply) { |
| 279 | await sendText(chatId, "This chat has a pending turn or retained reply. Use /status to inspect it before replacing its thread."); |
| 280 | return; |
| 281 | } |
| 282 | } |
| 283 | switch (action.kind) { |
| 284 | case "help": |
| 285 | await sendText(chatId, helpText(), { replyMarkup: controlKeyboard() }); |
| 286 | return; |
| 287 | case "menu": |
| 288 | await sendMenu(chatId); |
| 289 | return; |
| 290 | case "status": |
| 291 | await sendStatus(chatId, identity); |
| 292 | return; |
| 293 | case "threads": |
| 294 | await sendThreads(chatId, identity); |
| 295 | return; |
| 296 | case "new_thread": { |
| 297 | const state = await ensureThread(chatId, { forceNew: true }); |
| 298 | await sendText(chatId, `Created thread ${state.threadId}`, { replyMarkup: controlKeyboard() }); |
| 299 | return; |
| 300 | } |
| 301 | case "resume": |
| 302 | await resumeThread(chatId, action.threadId, identity); |
| 303 | return; |
| 304 | case "interrupt": |
| 305 | await interruptActiveTurn(chatId, identity); |
| 306 | return; |
| 307 | case "compact": |
| 308 | await compactThread(chatId); |
| 309 | return; |
| 310 | case "approval": |
| 311 | await decideApproval(chatId, action, identity); |
| 312 | return; |
| 313 | case "set_model": |
| 314 | await setChatModel(chatId, action.modelName); |
| 315 | return; |
| 316 | case "answer": |
| 317 | await answerQuestion(chatId, action.text, identity); |
| 318 | await threadStore.recordMessage(identity.messageKey); |
| 319 | return; |
| 320 | case "prompt": |
| 321 | await startPromptTurn(chatId, action.prompt, identity); |
| 322 | return; |
| 323 | default: |
| 324 | await sendText(chatId, helpText(), { replyMarkup: controlKeyboard() }); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | async function handleCallbackQuery(query) { |
| 329 | const chat = query.message?.chat || {}; |
| 330 | const from = query.from || {}; |
| 331 | const identity = { |
| 332 | chatId: chat.id != null ? String(chat.id) : "", |
| 333 | messageId: query.message?.message_id != null ? String(query.message.message_id) : "", |
| 334 | chatType: chat.type || "", |
| 335 | userId: from.id != null ? String(from.id) : "", |
| 336 | username: from.username ? `@${from.username}` : "", |
| 337 | firstName: from.first_name || "", |
| 338 | isBot: Boolean(from.is_bot) |
| 339 | }; |
| 340 | |
| 341 | if (!identity.chatId || !query.id) return; |
| 342 | if (identity.isBot) return; |
| 343 | |
| 344 | if (isGroupChat(identity.chatType) && !config.allowGroups) { |
| 345 | await answerCallback(query.id, "Group control is disabled."); |
| 346 | return; |
| 347 | } |
| 348 | if (!isAllowed(identity, config.allowlist, config.allowUnlisted)) { |
| 349 | await answerCallback(query.id, "This chat is not allowlisted."); |
| 350 | return; |
| 351 | } |
| 352 | |
| 353 | const action = callbackAction(query.data); |
| 354 | if (!action) { |
| 355 | await answerCallback(query.id, "Unknown action."); |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | await rememberAuthorizedIdentity(identity); |
| 360 | answerCallback(query.id, "Working...").catch((error) => { |
| 361 | console.warn("failed to acknowledge Telegram callback", error); |
| 362 | }); |
| 363 | await handleModalAction(identity.chatId, action, query, identity); |
| 364 | } |
| 365 | |
| 366 | async function handleModalAction(chatId, action, query = null, identity = null) { |
| 367 | if (["new_thread", "compact"].includes(action.kind)) { |
| 368 | const state = await threadStore.getChat(chatId); |
| 369 | if (state?.pendingAdmission || state?.activeTurnId || state?.pendingReply) { |
| 370 | await sendText(chatId, "This chat has a pending turn or retained reply. Use /status to inspect it before replacing its thread."); |
| 371 | return; |
| 372 | } |
| 373 | } |
| 374 | switch (action.kind) { |
| 375 | case "help": |
| 376 | await sendText(chatId, helpText(), { replyMarkup: controlKeyboard() }); |
| 377 | return; |
| 378 | case "status": |
| 379 | await sendStatus(chatId, identity); |
| 380 | return; |
| 381 | case "threads": |
| 382 | await sendThreads(chatId, identity); |
| 383 | return; |
| 384 | case "new_thread": { |
| 385 | const state = await ensureThread(chatId, { forceNew: true }); |
| 386 | await sendText(chatId, `Created thread ${state.threadId}`, { replyMarkup: controlKeyboard() }); |
| 387 | return; |
| 388 | } |
| 389 | case "interrupt": |
| 390 | await interruptActiveTurn(chatId, identity); |
| 391 | return; |
| 392 | case "compact": |
| 393 | await compactThread(chatId); |
| 394 | return; |
| 395 | case "set_model": |
| 396 | await setChatModel(chatId, action.modelName); |
| 397 | return; |
| 398 | case "stored_action": |
| 399 | await handleStoredAction(chatId, action, query, identity); |
| 400 | return; |
| 401 | default: |
| 402 | await sendText(chatId, helpText(), { replyMarkup: controlKeyboard() }); |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | async function handleStoredAction(chatId, action, query = null, identity = null) { |
| 407 | // Approval buttons also belong to the thread still bound to this chat. |
| 408 | const state = await threadStore.getChat(chatId); |
| 409 | const owner = { chatId, threadId: state?.threadId, actorId: turnActor(identity) }; |
| 410 | const stored = await threadStore.getAction(action.token, owner); |
| 411 | if (!stored) { |
| 412 | await sendText(chatId, "That action expired. Open /menu and try again."); |
| 413 | return; |
| 414 | } |
| 415 | |
| 416 | if (stored.kind === "resume") { |
| 417 | await threadStore.takeAction(action.token, owner); |
| 418 | await resumeThread(chatId, stored.threadId, identity); |
| 419 | return; |
| 420 | } |
| 421 | |
| 422 | if (stored.kind === "approval") { |
| 423 | const suffix = action.suffix || ""; |
| 424 | const decision = suffix === "deny" ? "deny" : "allow"; |
| 425 | const remember = suffix === "remember"; |
| 426 | // The token is consumed only after the Runtime accepted the decision. |
| 427 | try { |
| 428 | await settleStoredApproval(threadStore, action.token, owner, async () => { |
| 429 | if (!(await decideApproval(chatId, { decision, approvalId: stored.approvalId, remember, turnId: stored.owner.turnId }, identity))) { |
| 430 | throw new ApprovalOwnershipError("not delivered"); |
| 431 | } |
| 432 | }); |
| 433 | } catch (error) { |
| 434 | if (error instanceof ApprovalOwnershipError) return; |
| 435 | throw error; |
| 436 | } |
| 437 | if (query?.message?.message_id) { |
| 438 | await editMessageReplyMarkup(chatId, query.message.message_id, null).catch(() => {}); |
| 439 | } |
| 440 | return; |
| 441 | } |
| 442 | |
| 443 | await sendText(chatId, "That action is no longer supported."); |
| 444 | } |
| 445 | |
| 446 | async function sendMenu(chatId) { |
| 447 | const state = await threadStore.getChat(chatId); |
| 448 | await sendText( |
| 449 | chatId, |
| 450 | [ |
| 451 | "CodeWhale controls", |
| 452 | state?.threadId ? `thread=${state.threadId}` : "thread=(new on first prompt)", |
| 453 | `model=${state?.model || config.model}` |
| 454 | ].join("\n"), |
| 455 | { replyMarkup: controlKeyboard() } |
| 456 | ); |
| 457 | } |
| 458 | |
| 459 | async function ensureThread(chatId, { forceNew = false, threadRequest } = {}) { |
| 460 | const existing = await threadStore.getChat(chatId); |
| 461 | if (forceNew && (existing?.pendingAdmission || existing?.activeTurnId)) { |
| 462 | throw new Error("This chat has a pending turn or retained reply. Use /status to inspect it before replacing its thread."); |
| 463 | } |
| 464 | if (existing?.threadId && !forceNew) { |
| 465 | threadStore.requireOwnedThread(chatId, existing.threadId); |
| 466 | return existing; |
| 467 | } |
| 468 | |
| 469 | const effectiveModel = existing?.model || config.model; |
| 470 | const thread = await runtimeJson("/v1/threads", { |
| 471 | method: "POST", |
| 472 | body: threadRequest || { |
| 473 | model: effectiveModel, |
| 474 | workspace: config.workspace, |
| 475 | mode: config.mode, |
| 476 | allow_shell: config.allowShell, |
| 477 | trust_mode: config.trustMode, |
| 478 | auto_approve: config.autoApprove, |
| 479 | archived: false, |
| 480 | system_prompt: TELEGRAM_SYSTEM_PROMPT |
| 481 | } |
| 482 | }); |
| 483 | |
| 484 | const state = { |
| 485 | ...preservedChatStateFields(existing, ["model", "authorizedIdentity", "pendingAdmission", "pendingReply"]), |
| 486 | threadId: thread.id, |
| 487 | lastSeq: 0, |
| 488 | activeTurnId: null, |
| 489 | updatedAt: new Date().toISOString() |
| 490 | }; |
| 491 | await threadStore.recordThreadOwner(chatId, thread.id); |
| 492 | await threadStore.setChat(chatId, state); |
| 493 | return state; |
| 494 | } |
| 495 | |
| 496 | async function startPromptTurn(chatId, prompt, identity) { |
| 497 | const current = await threadStore.getChat(chatId); |
| 498 | if (current?.pendingQuestion) { |
| 499 | await answerQuestion(chatId, prompt, identity); |
| 500 | await threadStore.recordMessage(identity.messageKey); |
| 501 | return; |
| 502 | } |
| 503 | if (current?.pendingReply) { |
| 504 | await sendText(chatId, "The previous reply is retained because delivery was not confirmed. Its initiating human can retrieve it with /status before starting another turn."); |
| 505 | return; |
| 506 | } |
| 507 | if (activeTurnTasks.has(chatId) || current?.pendingAdmission || current?.activeTurnId) { |
| 508 | startTrackedTurnStream(chatId); |
| 509 | await sendText(chatId, "This chat has a pending turn. Use /status or /interrupt.", { |
| 510 | replyMarkup: activeTurnKeyboard() |
| 511 | }); |
| 512 | return; |
| 513 | } |
| 514 | if (!prompt.trim()) return sendText(chatId, helpText(), { replyMarkup: controlKeyboard() }); |
| 515 | if (current?.threadId && !threadStore.ownsThread(chatId, current.threadId)) { |
| 516 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE, { replyMarkup: controlKeyboard() }); |
| 517 | return; |
| 518 | } |
| 519 | const actorId = turnActor(identity); |
| 520 | if (!actorId || !identity.messageKey) throw new ApprovalOwnershipError("turn needs its initiating human and message"); |
| 521 | const request = { |
| 522 | prompt, input_summary: prompt.slice(0, 200), model: current?.model || config.model, |
| 523 | mode: config.mode, allow_shell: config.allowShell, trust_mode: config.trustMode, |
| 524 | auto_approve: config.autoApprove |
| 525 | }; |
| 526 | const operationKey = supportsAdmissionRecovery() |
| 527 | ? createHash("sha256").update(identity.messageKey).digest("hex") : null; |
| 528 | if (operationKey) request.operation_key = operationKey; |
| 529 | const replay = await threadStore.recordMessage(identity.messageKey, chatId, { pendingAdmission: { |
| 530 | botAccountId, runtimeUrl: config.runtimeUrl, actorId, identity: { |
| 531 | chatId, chatType: identity.chatType, userId: identity.userId, |
| 532 | username: identity.username, isBot: identity.isBot |
| 533 | }, messageKey: identity.messageKey, request, operationKey, |
| 534 | threadId: current?.threadId || null, submitted: false, sinceSeq: null, |
| 535 | threadRequest: { |
| 536 | model: request.model, workspace: config.workspace, mode: request.mode, |
| 537 | allow_shell: request.allow_shell, trust_mode: request.trust_mode, |
| 538 | auto_approve: request.auto_approve, archived: false, |
| 539 | system_prompt: TELEGRAM_SYSTEM_PROMPT |
| 540 | } |
| 541 | } }); |
| 542 | if (!replay) startTrackedTurnStream(chatId); |
| 543 | } |
| 544 | |
| 545 | function abortActiveTurnStreams() { |
| 546 | for (const task of activeTurnTasks.values()) task.controller?.abort(); |
| 547 | } |
| 548 | |
| 549 | async function clearActiveTurn(chatId) { |
| 550 | await threadStore.patchChat(chatId, { |
| 551 | activeTurnId: null, activeMessageKey: null, activeIdentity: null, activeBotAccountId: null, activeRuntimeUrl: null, |
| 552 | responseText: "", turnTerminal: false, pendingQuestion: null, updatedAt: new Date().toISOString() |
| 553 | }); |
| 554 | } |
| 555 | |
| 556 | function recoveryAllowed(chatId, state) { |
| 557 | const pending = state?.pendingAdmission; |
| 558 | const identity = pending?.identity || state?.activeIdentity || state?.authorizedIdentity; |
| 559 | const accountId = pending?.botAccountId || state?.activeBotAccountId; |
| 560 | const runtimeUrl = pending?.runtimeUrl || state?.activeRuntimeUrl; |
| 561 | return (!runtimeUrl || runtimeUrl === config.runtimeUrl) && (!accountId || accountId === botAccountId) && identity && identity.chatId === chatId && !identity.isBot && |
| 562 | ["private", "group", "supergroup"].includes(identity.chatType) && |
| 563 | (!isGroupChat(identity.chatType) || config.allowGroups) && |
| 564 | isAllowed(identity, config.allowlist, config.allowUnlisted); |
| 565 | } |
| 566 | |
| 567 | function supportsAdmissionRecovery() { |
| 568 | return runtimeCapabilities.turn_operation_idempotency === true && runtimeCapabilities.turn_operation_lookup === true; |
| 569 | } |
| 570 | |
| 571 | function startTrackedTurnStream(chatId) { |
| 572 | if (stopping || activeTurnTasks.has(chatId)) return false; |
| 573 | const controller = new AbortController(); |
| 574 | const task = { controller }; |
| 575 | activeTurnTasks.set(chatId, task); |
| 576 | void (async () => { |
| 577 | while (!stopping && !controller.signal.aborted) { |
| 578 | const state = await releaseUnownedRecovery(chatId); |
| 579 | if (!recoveryAllowed(chatId, state)) return; |
| 580 | if (!state?.pendingAdmission && !state?.activeTurnId) return; |
| 581 | if (threadStore.ownershipPending(chatId, state.pendingAdmission?.threadId || state.threadId)) { |
| 582 | await delay(2000); |
| 583 | continue; |
| 584 | } |
| 585 | try { |
| 586 | if (await runPrompt(chatId, { signal: controller.signal })) return; |
| 587 | const pending = (await threadStore.getChat(chatId))?.pendingAdmission; |
| 588 | if (pending?.submitted && (!pending.operationKey || !supportsAdmissionRecovery())) return; |
| 589 | } catch (error) { |
| 590 | console.error("Telegram turn recovery deferred; original request retained", error); |
| 591 | } |
| 592 | if (!stopping && !controller.signal.aborted) await delay(2000); |
| 593 | } |
| 594 | })().catch((error) => { |
| 595 | console.error("Telegram recovery stopped; persisted state retained", error); |
| 596 | }).finally(() => { |
| 597 | if (activeTurnTasks.get(chatId) === task) activeTurnTasks.delete(chatId); |
| 598 | }); |
| 599 | return true; |
| 600 | } |
| 601 | |
| 602 | function turnActor(identity) { |
| 603 | return identity?.userId && !identity.isBot ? `telegram-user:${identity.userId}` : ""; |
| 604 | } |
| 605 | |
| 606 | async function runPrompt(chatId, options = {}) { |
| 607 | let state = await releaseUnownedRecovery(chatId); |
| 608 | if (!recoveryAllowed(chatId, state)) return true; |
| 609 | if (threadStore.ownershipPending(chatId, state?.pendingAdmission?.threadId || state?.threadId)) return false; |
| 610 | let pending = state?.pendingAdmission; |
| 611 | if (pending) { |
| 612 | if (pending.threadId && !pending.submitted && !threadStore.ownsThread(chatId, pending.threadId)) { |
| 613 | if (threadStore.ownershipPending(chatId, pending.threadId)) return false; |
| 614 | await threadStore.patchChat(chatId, { pendingAdmission: null }); |
| 615 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 616 | return true; |
| 617 | } |
| 618 | const admission = await admitTurn({ |
| 619 | runtimeJson, pending, capabilities: runtimeCapabilities, |
| 620 | persistPending: (value) => threadStore.patchChat(chatId, { pendingAdmission: value }), |
| 621 | ensureThread: async (threadRequest) => (await ensureThread(chatId, { threadRequest })).threadId |
| 622 | }); |
| 623 | pending = admission.pending; |
| 624 | const turn = admission.turn; |
| 625 | if (!turn) { |
| 626 | if (admission.blocked && !pending.submitted) { |
| 627 | await threadStore.patchChat(chatId, { pendingAdmission: null }); |
| 628 | await sendText(chatId, "Thread already has an active turn. Wait for it to finish or send /interrupt.", { replyMarkup: activeTurnKeyboard() }); |
| 629 | return true; |
| 630 | } |
| 631 | return admission.uncertain === true; |
| 632 | } |
| 633 | await threadStore.recordTurnOrigin(chatId, pending.threadId, turn.id, pending.actorId); |
| 634 | state = await threadStore.patchChat(chatId, { |
| 635 | pendingAdmission: null, activeTurnId: turn.id, activeMessageKey: pending.messageKey, |
| 636 | activeIdentity: pending.identity, activeBotAccountId: pending.botAccountId, |
| 637 | activeRuntimeUrl: pending.runtimeUrl, |
| 638 | lastSeq: pending.sinceSeq, responseText: "", turnTerminal: false, |
| 639 | updatedAt: new Date().toISOString() |
| 640 | }); |
| 641 | await sendTurnText(chatId, `Started turn ${turn.id}`, { replyMarkup: activeTurnKeyboard() }); |
| 642 | } |
| 643 | if (!state?.activeTurnId) return true; |
| 644 | if (state.turnTerminal || await streamTurnEvents(chatId, state.threadId, state.activeTurnId, Number(state.lastSeq || 0), options)) { |
| 645 | await clearActiveTurn(chatId); |
| 646 | return true; |
| 647 | } |
| 648 | return false; |
| 649 | } |
| 650 | |
| 651 | async function reattachActiveTurns() { |
| 652 | for (const [chatId, state] of threadStore.listChats()) { |
| 653 | if ((!state?.pendingAdmission && !state?.activeTurnId) || !recoveryAllowed(chatId, state)) continue; |
| 654 | startTrackedTurnStream(chatId); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | async function streamTurnEvents(chatId, threadId, turnId, sinceSeq, options = {}) { |
| 659 | const controller = new AbortController(); |
| 660 | let timedOut = false; |
| 661 | const timeout = setTimeout(() => { |
| 662 | timedOut = true; |
| 663 | controller.abort(); |
| 664 | }, config.turnTimeoutMs); |
| 665 | const abortFromCaller = () => controller.abort(); |
| 666 | if (options.signal?.aborted) { |
| 667 | controller.abort(); |
| 668 | } else { |
| 669 | options.signal?.addEventListener("abort", abortFromCaller, { once: true }); |
| 670 | } |
| 671 | let responseText = (await threadStore.getChat(chatId))?.responseText || ""; |
| 672 | let turnTerminal = false; |
| 673 | let latestSeq = sinceSeq; |
| 674 | let flushedSeq = sinceSeq; |
| 675 | let lastSeqFlushAt = 0; |
| 676 | let sentProgressAt = Date.now(); |
| 677 | let typingPaused = false; |
| 678 | let typingInFlight = false; |
| 679 | |
| 680 | async function flushLastSeq(force = false) { |
| 681 | if (latestSeq <= flushedSeq) return; |
| 682 | if (!force && Date.now() - lastSeqFlushAt < LAST_SEQ_FLUSH_INTERVAL_MS) return; |
| 683 | await threadStore.patchChat(chatId, { lastSeq: latestSeq, responseText, turnTerminal }); |
| 684 | flushedSeq = latestSeq; |
| 685 | lastSeqFlushAt = Date.now(); |
| 686 | } |
| 687 | |
| 688 | const tickTyping = async () => { |
| 689 | if (stopping || typingPaused || typingInFlight) return; |
| 690 | typingInFlight = true; |
| 691 | try { |
| 692 | await sendTypingAction(chatId); |
| 693 | } catch (error) { |
| 694 | console.warn("failed to send Telegram typing action", error); |
| 695 | } finally { |
| 696 | typingInFlight = false; |
| 697 | } |
| 698 | }; |
| 699 | const typingTimer = setInterval(() => { |
| 700 | void tickTyping(); |
| 701 | }, TYPING_INTERVAL_MS); |
| 702 | typingTimer.unref?.(); |
| 703 | |
| 704 | try { |
| 705 | void tickTyping(); |
| 706 | const response = await fetch( |
| 707 | `${config.runtimeUrl}/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=${sinceSeq}`, |
| 708 | { |
| 709 | headers: authHeaders(), |
| 710 | signal: controller.signal |
| 711 | } |
| 712 | ); |
| 713 | if (!response.ok) { |
| 714 | const body = await readJsonSafe(response); |
| 715 | throw new Error(compactRuntimeError(response.status, body)); |
| 716 | } |
| 717 | |
| 718 | for await (const record of readThreadEvents(response, threadId)) { |
| 719 | if (record.event === "stream.end") return false; |
| 720 | latestSeq = Math.max(latestSeq, Number(record.seq || 0)); |
| 721 | |
| 722 | if (!turnId || record.turn_id !== turnId) continue; |
| 723 | const lifecycleStatus = |
| 724 | record.event === "turn.lifecycle" |
| 725 | ? record.payload?.turn?.status || record.payload?.status |
| 726 | : null; |
| 727 | const stopTypingEvent = |
| 728 | record.event === "turn.completed" || |
| 729 | ["failed", "canceled", "interrupted"].includes(lifecycleStatus); |
| 730 | if (typingPaused && !["approval.required", "user_input.required"].includes(record.event) && !stopTypingEvent) { |
| 731 | typingPaused = false; |
| 732 | void tickTyping(); |
| 733 | } |
| 734 | |
| 735 | if (record.event === "item.delta" && record.payload?.kind === "agent_message") { |
| 736 | responseText += record.payload.delta || ""; |
| 737 | const now = Date.now(); |
| 738 | if (responseText.length > config.maxReplyChars && now - sentProgressAt > 15000) { |
| 739 | const [head, rest] = splitAtCodePoint(responseText, config.maxReplyChars); |
| 740 | await sendTurnText(chatId, head); |
| 741 | responseText = rest; |
| 742 | sentProgressAt = now; |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | if (record.event === "user_input.required") { |
| 747 | typingPaused = true; |
| 748 | const input = record.payload || {}; |
| 749 | const inputId = input.input_id || input.id; |
| 750 | if (inputId && input.request) { |
| 751 | await threadStore.patchChat(chatId, { pendingQuestion: { inputId, request: input.request, turnId } }); |
| 752 | await sendTurnText(chatId, `${questionText(input.request)}\nUse /answer followed by your response.`, { replyMarkup: activeTurnKeyboard() }); |
| 753 | } |
| 754 | } |
| 755 | if (["user_input.answered", "user_input.canceled"].includes(record.event)) { |
| 756 | const state = await threadStore.getChat(chatId); |
| 757 | if (state?.pendingQuestion?.inputId === (record.payload?.input_id || record.payload?.id)) { |
| 758 | await threadStore.patchChat(chatId, { pendingQuestion: null }); |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | if (record.event === "approval.required") { |
| 763 | typingPaused = true; |
| 764 | const approval = record.payload || {}; |
| 765 | const approvalId = approval.approval_id || approval.id; |
| 766 | if (!approvalId) { |
| 767 | await sendTurnText( |
| 768 | chatId, |
| 769 | [ |
| 770 | "Approval required", |
| 771 | `tool=${approval.tool_name || "unknown"}`, |
| 772 | approval.description || "", |
| 773 | "", |
| 774 | "No approval_id was provided by the runtime; use /status and retry from the TUI." |
| 775 | ] |
| 776 | .filter(Boolean) |
| 777 | .join("\n"), |
| 778 | { replyMarkup: controlKeyboard() } |
| 779 | ); |
| 780 | continue; |
| 781 | } |
| 782 | const origin = threadStore.turnOrigin(chatId, threadId, turnId); |
| 783 | if (!origin) { |
| 784 | await sendTurnText(chatId, "Approval has no recorded initiating human; decide from the TUI."); |
| 785 | continue; |
| 786 | } |
| 787 | const actionToken = await threadStore.putAction( |
| 788 | { kind: "approval", approvalId }, |
| 789 | { chatId, threadId, turnId, actorId: origin.actorId } |
| 790 | ); |
| 791 | await sendTurnText( |
| 792 | chatId, |
| 793 | [ |
| 794 | "Approval required", |
| 795 | `tool=${approval.tool_name || "unknown"}`, |
| 796 | `approval_id=${approvalId}`, |
| 797 | approval.description || "", |
| 798 | "", |
| 799 | `Tap a button, or reply /allow ${approvalId}`, |
| 800 | `Reply /deny ${approvalId}` |
| 801 | ] |
| 802 | .filter(Boolean) |
| 803 | .join("\n"), |
| 804 | { replyMarkup: approvalKeyboard(actionToken) } |
| 805 | ); |
| 806 | } |
| 807 | |
| 808 | if (record.event === "turn.completed") { |
| 809 | typingPaused = true; |
| 810 | const turn = record.payload?.turn || {}; |
| 811 | const status = turn.status || "completed"; |
| 812 | const error = turn.error ? `\n${turn.error}` : ""; |
| 813 | if (status !== "completed") { |
| 814 | await sendTurnText(chatId, `Turn ${status}.${error}`.trim(), { |
| 815 | replyMarkup: controlKeyboard(), retain: true |
| 816 | }); |
| 817 | } else { |
| 818 | await sendTurnText(chatId, responseText.trim() || "Turn completed.", { |
| 819 | replyMarkup: controlKeyboard(), retain: true |
| 820 | }); |
| 821 | } |
| 822 | turnTerminal = true; |
| 823 | return true; |
| 824 | } |
| 825 | |
| 826 | if (record.event === "turn.lifecycle") { |
| 827 | if (["failed", "canceled", "interrupted"].includes(lifecycleStatus)) { |
| 828 | typingPaused = true; |
| 829 | await sendTurnText(chatId, `Turn ${lifecycleStatus}.`, { replyMarkup: controlKeyboard(), retain: true }); |
| 830 | turnTerminal = true; |
| 831 | return true; |
| 832 | } |
| 833 | } |
| 834 | await flushLastSeq(false); |
| 835 | } |
| 836 | } catch (error) { |
| 837 | if (error.name === "AbortError") { |
| 838 | if (timedOut) { |
| 839 | await sendTurnText(chatId, "Observation timed out; the bridge will reconnect to the same turn."); |
| 840 | } else if (!stopping) { |
| 841 | await sendTurnText(chatId, "Turn stream aborted."); |
| 842 | } |
| 843 | return; |
| 844 | } |
| 845 | throw error; |
| 846 | } finally { |
| 847 | clearInterval(typingTimer); |
| 848 | clearTimeout(timeout); |
| 849 | options.signal?.removeEventListener("abort", abortFromCaller); |
| 850 | await flushLastSeq(true); |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | async function answerQuestion(chatId, text, identity) { |
| 855 | const state = await threadStore.getChat(chatId); |
| 856 | if (!state?.threadId || !state.activeTurnId || !recoveryAllowed(chatId, state) || |
| 857 | threadStore.turnOrigin(chatId, state.threadId, state.activeTurnId)?.actorId !== turnActor(identity)) { |
| 858 | await sendText(chatId, "Only the recorded initiating human can answer this turn's question."); |
| 859 | return; |
| 860 | } |
| 861 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`); |
| 862 | const inputs = (detail.pending_user_inputs || []).filter((input) => input.turn_id === state.activeTurnId); |
| 863 | const input = state.pendingQuestion |
| 864 | ? inputs.find((candidate) => (candidate.id || candidate.input_id) === state.pendingQuestion.inputId) |
| 865 | : inputs.length === 1 ? inputs[0] : null; |
| 866 | const inputId = input?.id || input?.input_id; |
| 867 | if (!inputId) { |
| 868 | await threadStore.patchChat(chatId, { pendingQuestion: null }); |
| 869 | await sendText(chatId, "No matching question is waiting in this turn."); |
| 870 | return; |
| 871 | } |
| 872 | const answers = parseQuestionAnswers(input.request, text); |
| 873 | if (!answers) { |
| 874 | await sendText(chatId, questionText(input.request)); |
| 875 | return; |
| 876 | } |
| 877 | await runtimeJson(`/v1/user-input/${encodeURIComponent(state.threadId)}/${encodeURIComponent(inputId)}`, { |
| 878 | method: "POST", body: { answers } |
| 879 | }); |
| 880 | if ((await threadStore.getChat(chatId))?.pendingQuestion?.inputId === inputId) { |
| 881 | await threadStore.patchChat(chatId, { pendingQuestion: null }); |
| 882 | } |
| 883 | await sendText(chatId, "Answer sent."); |
| 884 | } |
| 885 | |
| 886 | async function sendStatus(chatId, identity) { |
| 887 | const state = await threadStore.getChat(chatId); |
| 888 | const reply = state?.pendingReply; |
| 889 | if (reply && recoveryAllowed(chatId, { pendingAdmission: reply }) && reply.actorId === turnActor(identity)) { |
| 890 | await sendText(chatId, `Retained reply (the earlier delivery may have succeeded):\n\n${reply.text}`, { replyMarkup: controlKeyboard() }); |
| 891 | if ((await threadStore.getChat(chatId))?.pendingReply?.key === reply.key) { |
| 892 | await threadStore.patchChat(chatId, { pendingReply: null }); |
| 893 | } |
| 894 | } |
| 895 | const [health, runtimeInfo, workspace] = await Promise.all([ |
| 896 | runtimeJson("/health", { auth: false }), |
| 897 | runtimeJson("/v1/runtime/info"), |
| 898 | runtimeJson("/v1/workspace/status") |
| 899 | ]); |
| 900 | await sendText( |
| 901 | chatId, |
| 902 | [ |
| 903 | `runtime=${health.status || "unknown"}`, |
| 904 | `version=${runtimeInfo.version || "unknown"}`, |
| 905 | `bind=${runtimeInfo.bind_host}:${runtimeInfo.port}`, |
| 906 | `auth_required=${runtimeInfo.auth_required}`, |
| 907 | `workspace=${workspace.workspace}`, |
| 908 | `git_repo=${workspace.git_repo}`, |
| 909 | workspace.branch ? `branch=${workspace.branch}` : "", |
| 910 | `staged=${workspace.staged} unstaged=${workspace.unstaged} untracked=${workspace.untracked}`, |
| 911 | state?.pendingAdmission ? "The original prompt is retained while Engine admission is reconciled." : "", |
| 912 | state?.pendingAdmission?.submitted && !state.pendingAdmission.operationKey ? "This Engine cannot reconcile the uncertain admission; inspect the Runtime before repeating the prompt." : "", |
| 913 | state?.activeTurnId ? `turn=${state.activeTurnId}` : "", |
| 914 | state?.pendingQuestion ? questionText(state.pendingQuestion.request) : "" |
| 915 | ] |
| 916 | .filter(Boolean) |
| 917 | .join("\n"), |
| 918 | { replyMarkup: controlKeyboard() } |
| 919 | ); |
| 920 | } |
| 921 | |
| 922 | async function sendThreads(chatId, identity) { |
| 923 | const state = await threadStore.getChat(chatId); |
| 924 | const threads = isGroupChat(identity?.chatType) |
| 925 | ? state?.threadId && threadStore.ownsThread(chatId, state.threadId) ? [{ id: state.threadId }] : [] |
| 926 | : await listOwnedThreads(threadStore, runtimeJson, chatId); |
| 927 | if (!threads.length) { |
| 928 | await sendText(chatId, "No threads started by this chat yet.", { replyMarkup: controlKeyboard() }); |
| 929 | return; |
| 930 | } |
| 931 | const actions = []; |
| 932 | for (const [index, thread] of threads.slice(0, 8).entries()) { |
| 933 | const token = await threadStore.putAction( |
| 934 | { kind: "resume", threadId: thread.id }, |
| 935 | { chatId } |
| 936 | ); |
| 937 | actions.push({ token, label: `Resume ${index + 1}` }); |
| 938 | } |
| 939 | await sendText( |
| 940 | chatId, |
| 941 | threads |
| 942 | .map((thread, index) => { |
| 943 | const status = thread.latest_turn_status || "none"; |
| 944 | return `${index + 1}. ${thread.id} [${status}] ${thread.title || thread.preview || ""}`; |
| 945 | }) |
| 946 | .join("\n"), |
| 947 | { replyMarkup: threadListKeyboard(actions) } |
| 948 | ); |
| 949 | } |
| 950 | |
| 951 | async function resumeThread(chatId, args, identity) { |
| 952 | const existing = await threadStore.getChat(chatId); |
| 953 | if (existing?.pendingAdmission || existing?.activeTurnId || existing?.pendingReply) { |
| 954 | await sendText(chatId, "This chat has a pending turn or retained reply. Use /status to inspect it before replacing its thread."); |
| 955 | return; |
| 956 | } |
| 957 | const threadId = args.trim(); |
| 958 | if (!threadId) { |
| 959 | await sendText(chatId, "Usage: /resume <thread_id>"); |
| 960 | return; |
| 961 | } |
| 962 | if (!threadStore.ownsThread(chatId, threadId)) { |
| 963 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 964 | return; |
| 965 | } |
| 966 | if (isGroupChat(identity?.chatType) && (threadId !== existing?.threadId || |
| 967 | !(existing?.turnOrigins || []).some((origin) => origin.threadId === threadId && origin.actorId === turnActor(identity)))) { |
| 968 | await sendText(chatId, "Group chats can only resume their own thread through a recorded initiating human."); |
| 969 | return; |
| 970 | } |
| 971 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`); |
| 972 | await threadStore.setChat(chatId, { |
| 973 | ...preservedChatStateFields(existing), |
| 974 | threadId, |
| 975 | lastSeq: Number(detail.latest_seq || 0), |
| 976 | activeTurnId: null, |
| 977 | updatedAt: new Date().toISOString() |
| 978 | }); |
| 979 | await sendText(chatId, `Resumed thread ${threadId}`, { replyMarkup: controlKeyboard() }); |
| 980 | } |
| 981 | |
| 982 | async function interruptActiveTurn(chatId, identity) { |
| 983 | const state = await threadStore.getChat(chatId); |
| 984 | if (state?.pendingAdmission) { |
| 985 | if (state.pendingAdmission.actorId !== turnActor(identity)) { |
| 986 | await sendText(chatId, "Only the initiating human can control this pending turn."); |
| 987 | return; |
| 988 | } |
| 989 | startTrackedTurnStream(chatId); |
| 990 | await sendText(chatId, "The original prompt's admission is still being reconciled. Use /status, then /interrupt once its turn is known."); |
| 991 | return; |
| 992 | } |
| 993 | if (!state?.threadId) { |
| 994 | await sendText(chatId, "No runtime thread recorded for this chat."); |
| 995 | return; |
| 996 | } |
| 997 | if (!threadStore.ownsThread(chatId, state.threadId)) { |
| 998 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 999 | return; |
| 1000 | } |
| 1001 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}`); |
| 1002 | const runningTurn = latestRunningTurn(detail); |
| 1003 | const turnId = state.activeTurnId || runningTurn?.id; |
| 1004 | if (!turnId) { |
| 1005 | await sendText(chatId, "No active turn recorded for this chat."); |
| 1006 | return; |
| 1007 | } |
| 1008 | if (threadStore.turnOrigin(chatId, state.threadId, turnId)?.actorId !== turnActor(identity)) { |
| 1009 | await sendText(chatId, "Only the recorded initiating human can interrupt this turn here. Use the Runtime for an unbound turn."); |
| 1010 | return; |
| 1011 | } |
| 1012 | await runtimeJson( |
| 1013 | `/v1/threads/${encodeURIComponent(state.threadId)}/turns/${encodeURIComponent( |
| 1014 | turnId |
| 1015 | )}/interrupt`, |
| 1016 | { method: "POST" } |
| 1017 | ); |
| 1018 | await threadStore.patchChat(chatId, { |
| 1019 | activeTurnId: turnId, |
| 1020 | updatedAt: new Date().toISOString() |
| 1021 | }); |
| 1022 | await sendText(chatId, `Interrupt requested for ${turnId}`, { replyMarkup: controlKeyboard() }); |
| 1023 | } |
| 1024 | |
| 1025 | async function compactThread(chatId) { |
| 1026 | const current = await threadStore.getChat(chatId); |
| 1027 | if (current?.threadId && !threadStore.ownsThread(chatId, current.threadId)) { |
| 1028 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 1029 | return; |
| 1030 | } |
| 1031 | const state = await ensureThread(chatId); |
| 1032 | const result = await runtimeJson(`/v1/threads/${encodeURIComponent(state.threadId)}/compact`, { |
| 1033 | method: "POST", |
| 1034 | body: { reason: "telegram bridge request" } |
| 1035 | }); |
| 1036 | await sendText(chatId, `Compaction started: ${result.turn?.id || "unknown turn"}`, { |
| 1037 | replyMarkup: activeTurnKeyboard() |
| 1038 | }); |
| 1039 | } |
| 1040 | |
| 1041 | /** Deliver a decision for an approval pending on this chat's thread. */ |
| 1042 | async function decideApproval(chatId, action, identity) { |
| 1043 | const decision = action.decision; |
| 1044 | const { approvalId, remember } = action; |
| 1045 | if (!approvalId) { |
| 1046 | await sendText( |
| 1047 | chatId, |
| 1048 | `Usage: /${decision} <approval_id>${decision === "allow" ? " [remember]" : ""}` |
| 1049 | ); |
| 1050 | return false; |
| 1051 | } |
| 1052 | try { |
| 1053 | await decideRuntimeApproval(runtimeJson, { store: threadStore, chatId, actorId: turnActor(identity), approvalId, decision, remember, turnId: action.turnId, ownsThread: (threadId) => threadStore.ownsThread(chatId, threadId) }); |
| 1054 | } catch (error) { |
| 1055 | if (error instanceof ThreadOwnershipError) { |
| 1056 | await sendText(chatId, THREAD_NOT_OWNED_MESSAGE); |
| 1057 | return false; |
| 1058 | } |
| 1059 | if (!(error instanceof ApprovalOwnershipError)) throw error; |
| 1060 | await sendText(chatId, `Approval ${approvalId} is not waiting in this chat.`); |
| 1061 | return false; |
| 1062 | } |
| 1063 | await sendText(chatId, `Approval ${approvalId}: ${decision}${remember ? " and remember" : ""}`); |
| 1064 | return true; |
| 1065 | } |
| 1066 | |
| 1067 | async function setChatModel(chatId, modelName) { |
| 1068 | if (!modelName || modelName === "default") { |
| 1069 | await threadStore.patchChat(chatId, { |
| 1070 | model: null, |
| 1071 | updatedAt: new Date().toISOString() |
| 1072 | }); |
| 1073 | await sendText(chatId, `Reset per-chat model. Using bridge default: ${config.model}`, { |
| 1074 | replyMarkup: controlKeyboard() |
| 1075 | }); |
| 1076 | return; |
| 1077 | } |
| 1078 | await threadStore.patchChat(chatId, { |
| 1079 | model: modelName, |
| 1080 | updatedAt: new Date().toISOString() |
| 1081 | }); |
| 1082 | await sendText(chatId, `Per-chat model set to: ${modelName}`, { replyMarkup: controlKeyboard() }); |
| 1083 | } |
| 1084 | |
| 1085 | async function sendText(chatId, text, options = {}) { |
| 1086 | const chunks = splitMessage(text, config.maxReplyChars); |
| 1087 | for (const [index, chunk] of chunks.entries()) { |
| 1088 | const body = { |
| 1089 | chat_id: chatId, |
| 1090 | ...telegramMessageBody(chunk, { markdown: true, maxChars: config.maxReplyChars }), |
| 1091 | disable_web_page_preview: true |
| 1092 | }; |
| 1093 | if (options.replyMarkup && index === chunks.length - 1) { |
| 1094 | body.reply_markup = options.replyMarkup; |
| 1095 | } |
| 1096 | try { |
| 1097 | await telegramApi("sendMessage", body); |
| 1098 | } catch (error) { |
| 1099 | if (!isTelegramMarkdownParseError(error)) throw error; |
| 1100 | const fallbackBody = { |
| 1101 | chat_id: chatId, |
| 1102 | ...telegramMessageBody(chunk, { markdown: false, maxChars: config.maxReplyChars }), |
| 1103 | disable_web_page_preview: true |
| 1104 | }; |
| 1105 | if (options.replyMarkup && index === chunks.length - 1) { |
| 1106 | fallbackBody.reply_markup = options.replyMarkup; |
| 1107 | } |
| 1108 | await telegramApi("sendMessage", fallbackBody); |
| 1109 | } |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | async function sendTypingAction(chatId) { |
| 1114 | const controller = new AbortController(); |
| 1115 | const timeout = setTimeout(() => controller.abort(), TYPING_TIMEOUT_MS); |
| 1116 | try { |
| 1117 | await telegramApi( |
| 1118 | "sendChatAction", |
| 1119 | { |
| 1120 | chat_id: chatId, |
| 1121 | action: "typing" |
| 1122 | }, |
| 1123 | { signal: controller.signal } |
| 1124 | ); |
| 1125 | } finally { |
| 1126 | clearTimeout(timeout); |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | async function sendTurnText(chatId, text, options = {}) { |
| 1131 | let reply; |
| 1132 | if (options.retain) { |
| 1133 | const state = await threadStore.getChat(chatId); |
| 1134 | reply = { |
| 1135 | key: createHash("sha256").update(JSON.stringify([state.threadId, state.activeTurnId, text])).digest("hex"), |
| 1136 | text, identity: state.activeIdentity, actorId: turnActor(state.activeIdentity), |
| 1137 | botAccountId: state.activeBotAccountId, runtimeUrl: state.activeRuntimeUrl |
| 1138 | }; |
| 1139 | await threadStore.patchChat(chatId, { pendingReply: reply, turnTerminal: true }); |
| 1140 | } |
| 1141 | try { |
| 1142 | await sendText(chatId, text, options); |
| 1143 | if (reply && (await threadStore.getChat(chatId))?.pendingReply?.key === reply.key) { |
| 1144 | await threadStore.patchChat(chatId, { pendingReply: null }); |
| 1145 | } |
| 1146 | } catch (error) { |
| 1147 | console.error("failed to send Telegram turn update", error); |
| 1148 | } |
| 1149 | } |
| 1150 | |
| 1151 | async function answerCallback(callbackQueryId, text = "") { |
| 1152 | await telegramApi("answerCallbackQuery", { |
| 1153 | callback_query_id: callbackQueryId, |
| 1154 | text: text.slice(0, 200), |
| 1155 | show_alert: false |
| 1156 | }); |
| 1157 | } |
| 1158 | |
| 1159 | async function editMessageReplyMarkup(chatId, messageId, replyMarkup) { |
| 1160 | await telegramApi("editMessageReplyMarkup", { |
| 1161 | chat_id: chatId, |
| 1162 | message_id: messageId, |
| 1163 | reply_markup: replyMarkup |
| 1164 | }); |
| 1165 | } |
| 1166 | |
| 1167 | async function telegramApi(method, body = {}, options = {}) { |
| 1168 | for (let attempt = 0; ; attempt += 1) { |
| 1169 | try { |
| 1170 | return await telegramApiOnce(method, body, options); |
| 1171 | } catch (error) { |
| 1172 | const retryMs = method === "sendMessage" ? telegramSendRetryDelayMs(error, attempt) : null; |
| 1173 | if (retryMs == null) throw error; |
| 1174 | console.warn( |
| 1175 | `Telegram ${method} failed: ${error.message}. Retrying in ${Math.round(retryMs / 1000)}s.` |
| 1176 | ); |
| 1177 | await delay(retryMs); |
| 1178 | } |
| 1179 | } |
| 1180 | } |
| 1181 | |
| 1182 | async function telegramApiOnce(method, body = {}, options = {}) { |
| 1183 | const response = await fetch(`${config.apiBase}/bot${config.botToken}/${method}`, { |
| 1184 | method: "POST", |
| 1185 | headers: { "content-type": "application/json" }, |
| 1186 | body: JSON.stringify(body), |
| 1187 | signal: options.signal || AbortSignal.timeout(method === "getUpdates" ? (config.pollTimeoutSeconds + 15) * 1000 : 15000) |
| 1188 | }); |
| 1189 | const payload = await readJsonSafe(response); |
| 1190 | if (!response.ok || !payload || typeof payload !== "object" || payload.ok !== true) { |
| 1191 | const error = new Error( |
| 1192 | payload?.description || `Telegram API request failed (${response.status})` |
| 1193 | ); |
| 1194 | error.errorCode = payload?.error_code || response.status; |
| 1195 | error.description = payload?.description || ""; |
| 1196 | error.parameters = payload?.parameters || {}; |
| 1197 | throw error; |
| 1198 | } |
| 1199 | return payload.result; |
| 1200 | } |
| 1201 | |
| 1202 | function requiredEnv(name) { |
| 1203 | const value = process.env[name]; |
| 1204 | if (!value || !value.trim()) { |
| 1205 | throw new Error(`${name} is required`); |
| 1206 | } |
| 1207 | return value.trim(); |
| 1208 | } |
| 1209 | |
| 1210 | function requiredEnvFirst(...names) { |
| 1211 | const value = envFirst(process.env, ...names); |
| 1212 | if (!value) { |
| 1213 | throw new Error(`${names.join(" or ")} is required`); |
| 1214 | } |
| 1215 | return value; |
| 1216 | } |
| 1217 | |
| 1218 | function delay(ms) { |
| 1219 | return new Promise((resolve) => setTimeout(resolve, ms)); |
| 1220 | } |
| 1221 |