forked from grinev/opencode-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1295 lines (1106 loc) · 43.2 KB
/
index.ts
File metadata and controls
1295 lines (1106 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Bot, Context, InputFile, NextFunction } from "grammy";
import { promises as fs } from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
import { SocksProxyAgent } from "socks-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import { config } from "../config.js";
import { authMiddleware } from "./middleware/auth.js";
import { interactionGuardMiddleware } from "./middleware/interaction-guard.js";
import { unknownCommandMiddleware } from "./middleware/unknown-command.js";
import { BOT_COMMANDS } from "./commands/definitions.js";
import { startCommand } from "./commands/start.js";
import { helpCommand } from "./commands/help.js";
import { statusCommand } from "./commands/status.js";
import {
AGENT_MODE_BUTTON_TEXT_PATTERN,
MODEL_BUTTON_TEXT_PATTERN,
VARIANT_BUTTON_TEXT_PATTERN,
} from "./message-patterns.js";
import { sessionsCommand, handleSessionSelect } from "./commands/sessions.js";
import { newCommand } from "./commands/new.js";
import { projectsCommand, handleProjectSelect } from "./commands/projects.js";
import { openCommand, handleOpenCallback, clearOpenPathIndex } from "./commands/open.js";
import { abortCommand } from "./commands/abort.js";
import { opencodeStartCommand } from "./commands/opencode-start.js";
import { opencodeStopCommand } from "./commands/opencode-stop.js";
import { renameCommand, handleRenameCancel, handleRenameTextAnswer } from "./commands/rename.js";
import { handleTaskCallback, handleTaskTextInput, taskCommand } from "./commands/task.js";
import { handleTaskListCallback, taskListCommand } from "./commands/tasklist.js";
import {
commandsCommand,
handleCommandsCallback,
handleCommandTextArguments,
} from "./commands/commands.js";
import { ttsCommand } from "./commands/tts.js";
import {
handleQuestionCallback,
showCurrentQuestion,
handleQuestionTextAnswer,
} from "./handlers/question.js";
import { handlePermissionCallback, showPermissionRequest } from "./handlers/permission.js";
import { handleAgentSelect, showAgentSelectionMenu } from "./handlers/agent.js";
import { handleModelSelect, showModelSelectionMenu } from "./handlers/model.js";
import { handleVariantSelect, showVariantSelectionMenu } from "./handlers/variant.js";
import { handleContextButtonPress, handleCompactConfirm } from "./handlers/context.js";
import { handleInlineMenuCancel } from "./handlers/inline-menu.js";
import { questionManager } from "../question/manager.js";
import { interactionManager } from "../interaction/manager.js";
import { clearAllInteractionState } from "../interaction/cleanup.js";
import { keyboardManager } from "../keyboard/manager.js";
import { subscribeToEvents } from "../opencode/events.js";
import { summaryAggregator } from "../summary/aggregator.js";
import { formatToolInfo } from "../summary/formatter.js";
import { renderSubagentCards } from "../summary/subagent-formatter.js";
import { ToolMessageBatcher } from "../summary/tool-message-batcher.js";
import { getCurrentSession } from "../session/manager.js";
import { ingestSessionInfoForCache } from "../session/cache-manager.js";
import { logger } from "../utils/logger.js";
import { safeBackgroundTask } from "../utils/safe-background-task.js";
import { withTelegramRateLimitRetry } from "../utils/telegram-rate-limit-retry.js";
import { pinnedMessageManager } from "../pinned/manager.js";
import { t } from "../i18n/index.js";
import { clearPromptResponseMode, processUserPrompt } from "./handlers/prompt.js";
import { handleVoiceMessage } from "./handlers/voice.js";
import { handleDocumentMessage } from "./handlers/document.js";
import { downloadTelegramFile, toDataUri } from "./utils/file-download.js";
import { finalizeAssistantResponse } from "./utils/finalize-assistant-response.js";
import { sendTtsResponseForSession } from "./utils/send-tts-response.js";
import { deliverThinkingMessage } from "./utils/thinking-message.js";
import {
editRenderedBotPart,
getTelegramRenderedPartSignature,
sendBotText,
sendRenderedBotPart,
} from "./utils/telegram-text.js";
import { formatAssistantRunFooter } from "./utils/assistant-run-footer.js";
import { getModelCapabilities, supportsInput } from "../model/capabilities.js";
import { getStoredModel } from "../model/manager.js";
import type { FilePartInput } from "@opencode-ai/sdk/v2";
import { foregroundSessionState } from "../scheduled-task/foreground-state.js";
import { scheduledTaskRuntime } from "../scheduled-task/runtime.js";
import { assistantRunState } from "./assistant-run-state.js";
import { ResponseStreamer } from "./streaming/response-streamer.js";
import type { StreamingMessagePayload } from "./streaming/response-streamer.js";
import { ToolCallStreamer, type ToolStreamKey } from "./streaming/tool-call-streamer.js";
import {
prepareAssistantFinalStreamingPayload,
prepareAssistantStreamingPayload,
renderAssistantFinalPartsSafe,
} from "./utils/assistant-rendering.js";
let botInstance: Bot<Context> | null = null;
let chatIdInstance: number | null = null;
let commandsInitialized = false;
const TELEGRAM_DOCUMENT_CAPTION_MAX_LENGTH = 1024;
const RESPONSE_STREAM_THROTTLE_MS = config.bot.responseStreamThrottleMs;
const RESPONSE_STREAM_TEXT_LIMIT = 3800;
const SESSION_RETRY_PREFIX = "🔁";
const SUBAGENT_STREAM_PREFIX = "🧩";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const TEMP_DIR = path.join(__dirname, "..", ".tmp");
const sessionCompletionTasks = new Map<string, Promise<void>>();
function getCurrentReplyKeyboard() {
if (!keyboardManager.isInitialized()) {
return undefined;
}
return keyboardManager.getKeyboard();
}
function prepareDocumentCaption(caption: string): string {
const normalizedCaption = caption.trim();
if (!normalizedCaption) {
return "";
}
if (normalizedCaption.length <= TELEGRAM_DOCUMENT_CAPTION_MAX_LENGTH) {
return normalizedCaption;
}
return `${normalizedCaption.slice(0, TELEGRAM_DOCUMENT_CAPTION_MAX_LENGTH - 3)}...`;
}
function prepareStreamingPayload(messageText: string): StreamingMessagePayload | null {
return prepareAssistantStreamingPayload(messageText, RESPONSE_STREAM_TEXT_LIMIT);
}
function prepareFinalStreamingPayload(messageText: string): StreamingMessagePayload | null {
return prepareAssistantFinalStreamingPayload(messageText, RESPONSE_STREAM_TEXT_LIMIT);
}
function enqueueSessionCompletionTask(sessionId: string, task: () => Promise<void>): Promise<void> {
const previousTask = sessionCompletionTasks.get(sessionId) ?? Promise.resolve();
const nextTask = previousTask
.catch(() => undefined)
.then(task)
.finally(() => {
if (sessionCompletionTasks.get(sessionId) === nextTask) {
sessionCompletionTasks.delete(sessionId);
}
});
sessionCompletionTasks.set(sessionId, nextTask);
return nextTask;
}
const toolMessageBatcher = new ToolMessageBatcher({
sendText: async (sessionId, text) => {
if (!botInstance || !chatIdInstance) {
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}
const keyboard = getCurrentReplyKeyboard();
await botInstance.api.sendMessage(chatIdInstance, text, {
disable_notification: true,
...(keyboard ? { reply_markup: keyboard } : {}),
});
},
sendFile: async (sessionId, fileData) => {
if (!botInstance || !chatIdInstance) {
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}
const tempFilePath = path.join(TEMP_DIR, fileData.filename);
try {
logger.debug(
`[Bot] Sending code file: ${fileData.filename} (${fileData.buffer.length} bytes, session=${sessionId})`,
);
await fs.mkdir(TEMP_DIR, { recursive: true });
await fs.writeFile(tempFilePath, fileData.buffer);
const keyboard = getCurrentReplyKeyboard();
await botInstance.api.sendDocument(chatIdInstance, new InputFile(tempFilePath), {
caption: fileData.caption,
disable_notification: true,
...(keyboard ? { reply_markup: keyboard } : {}),
});
} finally {
await fs.unlink(tempFilePath).catch(() => {});
}
},
});
const responseStreamer = new ResponseStreamer({
throttleMs: RESPONSE_STREAM_THROTTLE_MS,
sendPart: async (part, options) => {
if (!botInstance || !chatIdInstance || chatIdInstance <= 0) {
throw new Error("Bot context missing for streamed send");
}
return sendRenderedBotPart({
api: botInstance.api,
chatId: chatIdInstance,
part,
options,
});
},
editPart: async (messageId, part, options) => {
if (!botInstance || !chatIdInstance || chatIdInstance <= 0) {
throw new Error("Bot context missing for streamed edit");
}
try {
return await editRenderedBotPart({
api: botInstance.api,
chatId: chatIdInstance,
messageId,
part,
options,
});
} catch (error) {
const errorMessage =
error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
if (errorMessage.includes("message is not modified")) {
return {
deliveredSignature: getTelegramRenderedPartSignature(part),
};
}
throw error;
}
},
deleteText: async (messageId) => {
if (!botInstance || !chatIdInstance || chatIdInstance <= 0) {
throw new Error("Bot context missing for streamed delete");
}
await botInstance.api.deleteMessage(chatIdInstance, messageId).catch((error) => {
const errorMessage =
error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
if (
errorMessage.includes("message to delete not found") ||
errorMessage.includes("message identifier is not specified")
) {
return;
}
throw error;
});
},
});
const toolCallStreamer = new ToolCallStreamer({
throttleMs: RESPONSE_STREAM_THROTTLE_MS,
sendText: async (sessionId, text) => {
if (!botInstance || !chatIdInstance || chatIdInstance <= 0) {
throw new Error("Bot context missing for tool stream send");
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
throw new Error(`Tool stream session mismatch for send: ${sessionId}`);
}
const sentMessage = await botInstance.api.sendMessage(chatIdInstance, text, {
disable_notification: true,
});
return sentMessage.message_id;
},
editText: async (sessionId, messageId, text) => {
if (!botInstance || !chatIdInstance || chatIdInstance <= 0) {
throw new Error("Bot context missing for tool stream edit");
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
throw new Error(`Tool stream session mismatch for edit: ${sessionId}`);
}
try {
await botInstance.api.editMessageText(chatIdInstance, messageId, text);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
if (errorMessage.includes("message is not modified")) {
return;
}
throw error;
}
},
deleteText: async (sessionId, messageId) => {
if (!botInstance || !chatIdInstance || chatIdInstance <= 0) {
throw new Error("Bot context missing for tool stream delete");
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
throw new Error(`Tool stream session mismatch for delete: ${sessionId}`);
}
await botInstance.api.deleteMessage(chatIdInstance, messageId).catch((error) => {
const errorMessage =
error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
if (
errorMessage.includes("message to delete not found") ||
errorMessage.includes("message identifier is not specified")
) {
return;
}
throw error;
});
},
});
function getToolStreamKey(tool: string): ToolStreamKey {
if (tool === "todowrite") {
return "todo";
}
return "default";
}
async function ensureCommandsInitialized(ctx: Context, next: NextFunction): Promise<void> {
if (commandsInitialized || !ctx.from || ctx.from.id !== config.telegram.allowedUserId) {
await next();
return;
}
if (!ctx.chat) {
logger.warn("[Bot] Cannot initialize commands: chat context is missing");
await next();
return;
}
try {
await ctx.api.setMyCommands(BOT_COMMANDS, {
scope: {
type: "chat",
chat_id: ctx.chat.id,
},
});
commandsInitialized = true;
logger.debug(`[Bot] Commands initialized for authorized user (chat_id=${ctx.chat.id})`);
} catch (err) {
logger.error("[Bot] Failed to set commands:", err);
}
await next();
}
async function ensureEventSubscription(directory: string): Promise<void> {
if (!directory) {
logger.error("No directory found for event subscription");
return;
}
summaryAggregator.setTypingIndicatorEnabled(true);
summaryAggregator.setOnCleared(() => {
toolMessageBatcher.clearAll("summary_aggregator_clear");
toolCallStreamer.clearAll("summary_aggregator_clear");
responseStreamer.clearAll("summary_aggregator_clear");
});
summaryAggregator.setOnPartial((sessionId, messageId, messageText) => {
if (!botInstance || !chatIdInstance) {
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}
const preparedStreamPayload = prepareStreamingPayload(messageText);
if (!preparedStreamPayload) {
return;
}
// Reply keyboards make the first streamed message non-editable in Telegram,
// so partial chunks must be sent without reply_markup and finalized later.
preparedStreamPayload.sendOptions = { disable_notification: true };
preparedStreamPayload.editOptions = undefined;
responseStreamer.enqueue(sessionId, messageId, preparedStreamPayload);
});
summaryAggregator.setOnComplete((sessionId, messageId, messageText, completionInfo) => {
void enqueueSessionCompletionTask(sessionId, async () => {
if (!botInstance || !chatIdInstance) {
logger.error("Bot or chat ID not available for sending message");
clearPromptResponseMode(sessionId);
responseStreamer.clearMessage(sessionId, messageId, "bot_context_missing");
toolCallStreamer.clearSession(sessionId, "bot_context_missing");
assistantRunState.clearRun(sessionId, "bot_context_missing");
foregroundSessionState.markIdle(sessionId);
return;
}
const currentSession = getCurrentSession();
if (currentSession?.id !== sessionId) {
clearPromptResponseMode(sessionId);
responseStreamer.clearMessage(sessionId, messageId, "session_mismatch");
toolCallStreamer.clearSession(sessionId, "session_mismatch");
assistantRunState.clearRun(sessionId, "session_mismatch");
foregroundSessionState.markIdle(sessionId);
await scheduledTaskRuntime.flushDeferredDeliveries();
return;
}
const botApi = botInstance.api;
const chatId = chatIdInstance;
try {
assistantRunState.markResponseCompleted(sessionId, {
agent: completionInfo.agent,
providerID: completionInfo.providerID,
modelID: completionInfo.modelID,
});
await finalizeAssistantResponse({
sessionId,
messageId,
messageText,
responseStreamer,
flushPendingServiceMessages: () =>
Promise.all([
toolMessageBatcher.flushSession(sessionId, "assistant_message_completed"),
toolCallStreamer.breakSession(sessionId, "assistant_message_completed"),
]).then(() => undefined),
prepareStreamingPayload: prepareFinalStreamingPayload,
renderFinalParts: (text) => renderAssistantFinalPartsSafe(text),
getReplyKeyboard: getCurrentReplyKeyboard,
sendRenderedPart: async (part, options) => {
await sendRenderedBotPart({
api: botApi,
chatId,
part,
options: options as Parameters<typeof sendBotText>[0]["options"],
});
},
});
await sendTtsResponseForSession({
api: botApi,
sessionId,
chatId,
text: messageText,
});
} catch (err) {
clearPromptResponseMode(sessionId);
assistantRunState.clearRun(sessionId, "assistant_finalize_failed");
logger.error("Failed to send message to Telegram:", err);
// Stop processing events after critical error to prevent infinite loop
logger.error("[Bot] CRITICAL: Stopping event processing due to error");
summaryAggregator.clear();
foregroundSessionState.markIdle(sessionId);
} finally {
await scheduledTaskRuntime.flushDeferredDeliveries();
}
});
});
summaryAggregator.setOnTool(async (toolInfo) => {
if (!botInstance || !chatIdInstance) {
logger.error("Bot or chat ID not available for sending tool notification");
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== toolInfo.sessionId) {
return;
}
const shouldIncludeToolInfoInFileCaption =
toolInfo.hasFileAttachment &&
(toolInfo.tool === "write" || toolInfo.tool === "edit" || toolInfo.tool === "apply_patch");
if (
config.bot.hideToolCallMessages ||
shouldIncludeToolInfoInFileCaption ||
toolInfo.tool === "task"
) {
return;
}
try {
const message = formatToolInfo(toolInfo);
if (message) {
toolCallStreamer.append(toolInfo.sessionId, message, getToolStreamKey(toolInfo.tool));
}
} catch (err) {
logger.error("Failed to send tool notification to Telegram:", err);
}
});
summaryAggregator.setOnSubagent(async (sessionId, subagents) => {
if (!botInstance || !chatIdInstance) {
return;
}
if (config.bot.hideToolCallMessages) {
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}
try {
const renderedCards = await renderSubagentCards(subagents);
if (!renderedCards) {
return;
}
toolCallStreamer.replaceByPrefix(
sessionId,
SUBAGENT_STREAM_PREFIX,
renderedCards,
"subagent",
);
} catch (err) {
logger.error("Failed to render subagent activity for Telegram:", err);
}
});
summaryAggregator.setOnToolFile(async (fileInfo) => {
if (!botInstance || !chatIdInstance) {
logger.error("Bot or chat ID not available for sending file");
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== fileInfo.sessionId) {
return;
}
if (config.bot.hideToolFileMessages) {
return;
}
try {
await toolCallStreamer.breakSession(fileInfo.sessionId, "tool_file_boundary");
const toolMessage = formatToolInfo(fileInfo);
const caption = prepareDocumentCaption(toolMessage || fileInfo.fileData.caption);
toolMessageBatcher.enqueueFile(fileInfo.sessionId, {
...fileInfo.fileData,
caption,
});
} catch (err) {
logger.error("Failed to send file to Telegram:", err);
}
});
summaryAggregator.setOnQuestion(async (questions, requestID) => {
if (!botInstance || !chatIdInstance) {
logger.error("Bot or chat ID not available for showing questions");
return;
}
const currentSession = getCurrentSession();
if (currentSession) {
await Promise.all([
toolMessageBatcher.flushSession(currentSession.id, "question_asked"),
toolCallStreamer.flushSession(currentSession.id, "question_asked"),
]);
}
if (questionManager.isActive()) {
logger.warn("[Bot] Replacing active poll with a new one");
const previousMessageIds = questionManager.getMessageIds();
for (const messageId of previousMessageIds) {
await botInstance.api.deleteMessage(chatIdInstance, messageId).catch(() => {});
}
clearAllInteractionState("question_replaced_by_new_poll");
}
logger.info(`[Bot] Received ${questions.length} questions from agent, requestID=${requestID}`);
questionManager.startQuestions(questions, requestID);
await showCurrentQuestion(botInstance.api, chatIdInstance);
});
summaryAggregator.setOnQuestionError(async () => {
logger.info(`[Bot] Question tool failed, clearing active poll and deleting messages`);
// Delete all messages from the invalid poll
const messageIds = questionManager.getMessageIds();
for (const messageId of messageIds) {
if (chatIdInstance) {
await botInstance?.api.deleteMessage(chatIdInstance, messageId).catch((err) => {
logger.error(`[Bot] Failed to delete question message ${messageId}:`, err);
});
}
}
clearAllInteractionState("question_error");
});
summaryAggregator.setOnPermission(async (request) => {
if (!botInstance || !chatIdInstance) {
logger.error("Bot or chat ID not available for showing permission request");
return;
}
await Promise.all([
toolMessageBatcher.flushSession(request.sessionID, "permission_asked"),
toolCallStreamer.flushSession(request.sessionID, "permission_asked"),
]);
logger.info(
`[Bot] Received permission request from agent: type=${request.permission}, requestID=${request.id}`,
);
await showPermissionRequest(botInstance.api, chatIdInstance, request);
});
summaryAggregator.setOnThinking(async (sessionId) => {
if (!botInstance || !chatIdInstance) {
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}
logger.debug("[Bot] Agent started thinking");
await toolCallStreamer.breakSession(sessionId, "thinking_started");
deliverThinkingMessage(sessionId, toolMessageBatcher, {
hideThinkingMessages: config.bot.hideThinkingMessages,
});
// Refresh pinned message so it shows the latest in-memory context
// (accumulated from silent token updates). 1 API call per thinking event.
if (pinnedMessageManager.isInitialized()) {
await pinnedMessageManager.refresh();
}
});
summaryAggregator.setOnTokens(async (tokens, isCompleted) => {
if (!pinnedMessageManager.isInitialized()) {
return;
}
try {
logger.debug(
`[Bot] Received tokens: input=${tokens.input}, output=${tokens.output}, completed=${isCompleted}`,
);
const contextSize = tokens.input + tokens.cacheRead;
const contextLimit = pinnedMessageManager.getContextLimit();
// Skip non-completed messages with zero context: a new assistant message
// starts with tokens={input:0, ...} which would overwrite valid context
// from the previous step. Only accept zeros from completed messages.
if (!isCompleted && contextSize === 0) {
logger.debug("[Bot] Skipping zero-token intermediate update");
return;
}
// Update both keyboard and pinned state in memory (keeps them in sync)
if (contextLimit > 0) {
keyboardManager.updateContext(contextSize, contextLimit);
}
pinnedMessageManager.updateTokensSilent(tokens);
// Full pinned message update (API call) only on completed messages
if (isCompleted) {
await pinnedMessageManager.onMessageComplete(tokens);
}
} catch (err) {
logger.error("[Bot] Error updating pinned message with tokens:", err);
}
});
summaryAggregator.setOnCost(async (cost) => {
if (!pinnedMessageManager.isInitialized()) {
return;
}
try {
logger.debug(`[Bot] Cost update: $${cost.toFixed(2)}`);
await pinnedMessageManager.onCostUpdate(cost);
} catch (err) {
logger.error("[Bot] Error updating cost:", err);
}
});
summaryAggregator.setOnSessionCompacted(async (sessionId, directory) => {
if (!pinnedMessageManager.isInitialized()) {
return;
}
try {
logger.info(`[Bot] Session compacted, reloading context: ${sessionId}`);
await pinnedMessageManager.onSessionCompacted(sessionId, directory);
} catch (err) {
logger.error("[Bot] Error reloading context after compaction:", err);
}
});
summaryAggregator.setOnSessionIdle(async (sessionId) => {
await sessionCompletionTasks.get(sessionId)?.catch(() => undefined);
const completedRun = assistantRunState.finishRun(sessionId, "session_idle");
clearPromptResponseMode(sessionId);
if (!botInstance || !chatIdInstance) {
foregroundSessionState.markIdle(sessionId);
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
foregroundSessionState.markIdle(sessionId);
await scheduledTaskRuntime.flushDeferredDeliveries();
return;
}
try {
await Promise.all([
toolMessageBatcher.flushSession(sessionId, "session_idle"),
toolCallStreamer.flushSession(sessionId, "session_idle"),
]);
if (completedRun?.hasCompletedResponse) {
const agent = completedRun.actualAgent || completedRun.configuredAgent;
const providerID = completedRun.actualProviderID || completedRun.configuredProviderID;
const modelID = completedRun.actualModelID || completedRun.configuredModelID;
if (agent && providerID && modelID) {
const keyboard = getCurrentReplyKeyboard();
await botInstance.api.sendMessage(
chatIdInstance,
formatAssistantRunFooter({
agent,
providerID,
modelID,
elapsedMs: Date.now() - completedRun.startedAt,
}),
{
...(keyboard ? { reply_markup: keyboard } : {}),
},
);
}
}
} catch (err) {
logger.error("[Bot] Failed to send session idle footer:", err);
} finally {
foregroundSessionState.markIdle(sessionId);
await scheduledTaskRuntime.flushDeferredDeliveries();
}
});
summaryAggregator.setOnSessionError(async (sessionId, message) => {
if (!botInstance || !chatIdInstance) {
clearPromptResponseMode(sessionId);
assistantRunState.clearRun(sessionId, "session_error_no_bot_context");
foregroundSessionState.markIdle(sessionId);
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
clearPromptResponseMode(sessionId);
responseStreamer.clearSession(sessionId, "session_error_not_current");
toolCallStreamer.clearSession(sessionId, "session_error_not_current");
assistantRunState.clearRun(sessionId, "session_error_not_current");
foregroundSessionState.markIdle(sessionId);
await scheduledTaskRuntime.flushDeferredDeliveries();
return;
}
responseStreamer.clearSession(sessionId, "session_error");
clearPromptResponseMode(sessionId);
assistantRunState.clearRun(sessionId, "session_error");
await Promise.all([
toolMessageBatcher.flushSession(sessionId, "session_error"),
toolCallStreamer.flushSession(sessionId, "session_error"),
]);
const normalizedMessage = message.trim() || t("common.unknown_error");
const truncatedMessage =
normalizedMessage.length > 3500
? `${normalizedMessage.slice(0, 3497)}...`
: normalizedMessage;
await botInstance.api
.sendMessage(chatIdInstance, t("bot.session_error", { message: truncatedMessage }))
.catch((err) => {
logger.error("[Bot] Failed to send session.error message:", err);
});
foregroundSessionState.markIdle(sessionId);
await scheduledTaskRuntime.flushDeferredDeliveries();
});
summaryAggregator.setOnSessionRetry(async ({ sessionId, message }) => {
if (!botInstance || !chatIdInstance) {
return;
}
const currentSession = getCurrentSession();
if (!currentSession || currentSession.id !== sessionId) {
return;
}
const normalizedMessage = message.trim() || t("common.unknown_error");
const truncatedMessage =
normalizedMessage.length > 3500
? `${normalizedMessage.slice(0, 3497)}...`
: normalizedMessage;
const retryMessage = t("bot.session_retry", { message: truncatedMessage });
toolCallStreamer.replaceByPrefix(sessionId, SESSION_RETRY_PREFIX, retryMessage);
});
summaryAggregator.setOnSessionDiff(async (_sessionId, diffs) => {
if (!pinnedMessageManager.isInitialized()) {
return;
}
try {
await pinnedMessageManager.onSessionDiff(diffs);
} catch (err) {
logger.error("[Bot] Error updating session diff:", err);
}
});
summaryAggregator.setOnFileChange((change) => {
if (!pinnedMessageManager.isInitialized()) {
return;
}
pinnedMessageManager.addFileChange(change);
});
pinnedMessageManager.setOnKeyboardUpdate(async (tokensUsed, tokensLimit) => {
try {
logger.debug(`[Bot] Updating keyboard with context: ${tokensUsed}/${tokensLimit}`);
keyboardManager.updateContext(tokensUsed, tokensLimit);
// Don't send automatic keyboard updates - keyboard will update naturally with user messages
} catch (err) {
logger.error("[Bot] Error updating keyboard context:", err);
}
});
logger.info(`[Bot] Subscribing to OpenCode events for project: ${directory}`);
subscribeToEvents(directory, (event) => {
if (event.type === "session.created" || event.type === "session.updated") {
const info = (
event.properties as { info?: { directory?: string; time?: { updated?: number } } }
).info;
if (info?.directory) {
safeBackgroundTask({
taskName: `session.cache.${event.type}`,
task: () => ingestSessionInfoForCache(info),
});
}
}
summaryAggregator.processEvent(event);
}).catch((err) => {
logger.error("Failed to subscribe to events:", err);
});
}
export function createBot(): Bot<Context> {
clearAllInteractionState("bot_startup");
sessionCompletionTasks.clear();
assistantRunState.clearAll("bot_startup");
const botOptions: ConstructorParameters<typeof Bot<Context>>[1] = {};
if (config.telegram.proxyUrl) {
const proxyUrl = config.telegram.proxyUrl;
let agent;
if (proxyUrl.startsWith("socks")) {
agent = new SocksProxyAgent(proxyUrl);
logger.info(`[Bot] Using SOCKS proxy: ${proxyUrl.replace(/\/\/.*@/, "//***@")}`);
} else {
agent = new HttpsProxyAgent(proxyUrl);
logger.info(`[Bot] Using HTTP/HTTPS proxy: ${proxyUrl.replace(/\/\/.*@/, "//***@")}`);
}
botOptions.client = {
baseFetchConfig: {
agent,
compress: true,
},
};
}
const bot = new Bot(config.telegram.token, botOptions);
// Heartbeat for diagnostics: verify the event loop is not blocked
let heartbeatCounter = 0;
setInterval(() => {
heartbeatCounter++;
if (heartbeatCounter % 6 === 0) {
// Log every 30 seconds (5 sec * 6)
logger.debug(`[Bot] Heartbeat #${heartbeatCounter} - event loop alive`);
}
}, 5000);
// Log all API calls for diagnostics
let lastGetUpdatesTime = Date.now();
bot.api.config.use(async (prev, method, payload, signal) => {
if (method === "getUpdates") {
const now = Date.now();
const timeSinceLast = now - lastGetUpdatesTime;
logger.debug(`[Bot API] getUpdates called (${timeSinceLast}ms since last)`);
lastGetUpdatesTime = now;
return prev(method, payload, signal);
}
if (method === "sendMessage") {
logger.debug(`[Bot API] sendMessage to chat ${(payload as { chat_id?: number }).chat_id}`);
}
return withTelegramRateLimitRetry(() => prev(method, payload, signal), {
maxRetries: 5,
onRetry: ({ attempt, retryAfterMs, error }) => {
logger.warn(
`[Bot API] Telegram rate limit on ${method}, retrying in ${retryAfterMs}ms (attempt=${attempt})`,
error,
);
},
});
});
bot.use((ctx, next) => {
const hasCallbackQuery = !!ctx.callbackQuery;
const hasMessage = !!ctx.message;
const callbackData = ctx.callbackQuery?.data || "N/A";
logger.debug(
`[DEBUG] Incoming update: hasCallbackQuery=${hasCallbackQuery}, hasMessage=${hasMessage}, callbackData=${callbackData}`,
);
return next();
});
bot.use(authMiddleware);
bot.use(ensureCommandsInitialized);
bot.use(interactionGuardMiddleware);
const blockMenuWhileInteractionActive = async (ctx: Context): Promise<boolean> => {
const activeInteraction = interactionManager.getSnapshot();
if (!activeInteraction) {
return false;
}
logger.debug(
`[Bot] Blocking menu open while interaction active: kind=${activeInteraction.kind}, expectedInput=${activeInteraction.expectedInput}`,
);
await ctx.reply(t("interaction.blocked.finish_current"));
return true;
};
bot.command("start", startCommand);
bot.command("help", helpCommand);
bot.command("status", statusCommand);
bot.command("tts", ttsCommand);
bot.command("opencode_start", opencodeStartCommand);
bot.command("opencode_stop", opencodeStopCommand);
bot.command("projects", projectsCommand);
bot.command("open", openCommand);
bot.command("sessions", sessionsCommand);
bot.command("new", newCommand);
bot.command("abort", abortCommand);
bot.command("task", taskCommand);
bot.command("tasklist", taskListCommand);
bot.command("rename", renameCommand);
bot.command("commands", commandsCommand);
bot.on("message:text", unknownCommandMiddleware);
bot.on("callback_query:data", async (ctx) => {
logger.debug(`[Bot] Received callback_query:data: ${ctx.callbackQuery?.data}`);
logger.debug(`[Bot] Callback context: from=${ctx.from?.id}, chat=${ctx.chat?.id}`);
if (ctx.chat) {
botInstance = bot;
chatIdInstance = ctx.chat.id;