-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtelegram_kiro_bot.py
More file actions
executable file
·1572 lines (1350 loc) · 61.2 KB
/
Copy pathtelegram_kiro_bot.py
File metadata and controls
executable file
·1572 lines (1350 loc) · 61.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
#!/usr/bin/env python3.12
import configparser
import json
import logging
import os
import pty
import re
import select
import signal
import subprocess
import threading
import time
from pathlib import Path
from queue import Empty, Queue
from telegram import Update
from telegram.constants import ChatAction
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
# Import ACP session manager
from kiro_session_acp import KiroSessionACP
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler("/tmp/telegram_kiro_bot.log"),
logging.StreamHandler(),
],
)
logger = logging.getLogger(__name__)
# Use ACP-based session manager
KiroSession = KiroSessionACP
class TelegramBot:
def __init__(
self,
token,
authorized_user,
attachments_dir=None,
chunk_timeout=2.0,
typing_refresh_interval=4.0,
prompt_timeout=600,
group_id=None,
topic_cache_path=None,
):
self.token = token
self.authorized_user = authorized_user
self.attachments_dir = Path(
attachments_dir or "~/.kiro/bot_attachments"
).expanduser()
self._setup_attachments_dir()
self.kiro = KiroSessionACP()
# Configure timeouts
self.kiro.chunk_timeout = chunk_timeout
self.kiro.typing_refresh_interval = typing_refresh_interval
self.kiro.prompt_timeout = prompt_timeout
# Group topic configuration
self.group_id = group_id
self._topic_cache_path = Path(
topic_cache_path or "~/.kiro/topic_agent_map.json"
).expanduser()
self._topic_agent_cache = {} # thread_id (int) -> agent_name (str)
self._load_topic_cache()
# Configure timeouts
self.kiro.chunk_timeout = chunk_timeout
self.kiro.typing_refresh_interval = typing_refresh_interval
self.kiro.prompt_timeout = prompt_timeout
# Build application
self.application = Application.builder().token(token).build()
self.loop = None
# Set up async callback for Kiro to send messages back
async def send_to_telegram(chat_id, text, thread_id=None):
kwargs = {"chat_id": chat_id, "text": text, "parse_mode": "HTML"}
if thread_id:
kwargs["message_thread_id"] = thread_id
await self.application.bot.send_message(**kwargs)
self.kiro.send_to_telegram = send_to_telegram
self.kiro.application = self.application
# Conversation state for multi-step interactions
self.user_states = {} # chat_id -> state dict
# Start fresh session (load_state removed for now - will add back later)
print(f"[DEBUG] Starting fresh session")
self.kiro.start_session()
# Add message and command handlers
self.application.add_handler(
MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message)
)
# Note: Agent and chat commands are handled via interception
# This allows backslash prefix support (\agent, \chat)
# Attachment handlers
self.application.add_handler(MessageHandler(filters.PHOTO, self.handle_photo))
self.application.add_handler(
MessageHandler(filters.Document.ALL, self.handle_document)
)
# Forum topic lifecycle handlers
self.application.add_handler(
MessageHandler(
filters.StatusUpdate.FORUM_TOPIC_CREATED,
self.handle_forum_topic_created,
)
)
self.application.add_handler(
MessageHandler(
filters.StatusUpdate.FORUM_TOPIC_EDITED, self.handle_forum_topic_edited
)
)
# Global error handler for transient network errors (Fix 5)
self.application.add_error_handler(self._error_handler)
@staticmethod
async def _error_handler(update, context):
"""Handle errors from python-telegram-bot, suppressing transient network issues."""
import telegram.error
error = context.error
if isinstance(error, telegram.error.NetworkError):
logger.warning(f"Transient network error (suppressed): {error}")
else:
logger.error(f"Unhandled error: {error}", exc_info=context.error)
def _setup_attachments_dir(self):
"""Create attachments directory if it doesn't exist"""
try:
self.attachments_dir.mkdir(parents=True, exist_ok=True, mode=0o755)
logger.info(f"Attachments directory ready: {self.attachments_dir}")
except Exception as e:
logger.error(f"Failed to create attachments directory: {e}")
raise
def _load_topic_cache(self):
"""Load topic-agent mapping from disk."""
if self._topic_cache_path.exists():
try:
with open(self._topic_cache_path, "r") as f:
data = json.load(f)
# Keys are stored as strings in JSON, convert to int
self._topic_agent_cache = {int(k): v for k, v in data.items()}
logger.info(
f"Loaded topic cache: {len(self._topic_agent_cache)} entries"
)
except Exception as e:
logger.error(f"Failed to load topic cache: {e}")
self._topic_agent_cache = {}
def _save_topic_cache(self):
"""Persist topic-agent mapping to disk."""
try:
self._topic_cache_path.parent.mkdir(parents=True, exist_ok=True)
with open(self._topic_cache_path, "w") as f:
json.dump(
{str(k): v for k, v in self._topic_agent_cache.items()}, f, indent=2
)
logger.info(f"Saved topic cache: {len(self._topic_agent_cache)} entries")
except Exception as e:
logger.error(f"Failed to save topic cache: {e}")
def _get_available_agent_names(self):
"""Get all available agent names (built-in + custom)."""
agents = ["kiro_default"]
agents_dir = Path.home() / ".kiro" / "agents"
if agents_dir.exists():
for f in agents_dir.glob("*.json"):
agents.append(f.stem)
return sorted(set(agents))
def _match_agent_name(self, topic_name):
"""Case-insensitive match of topic name to agent name (spaces normalized to underscores)."""
available = self._get_available_agent_names()
lower_map = {a.lower(): a for a in available}
normalized = topic_name.lower().replace(" ", "_")
return lower_map.get(normalized)
def _sanitize_filename(self, filename):
"""Remove dangerous characters from filename"""
safe = re.sub(r'[/\\:*?"<>|]', "_", filename)
safe = safe.replace(" ", "_")
return safe[:255]
def _generate_attachment_path(self, user_id, filename):
"""Generate unique file path for attachment"""
timestamp = int(time.time())
safe_filename = self._sanitize_filename(filename)
unique_filename = f"{timestamp}_{user_id}_{safe_filename}"
return self.attachments_dir / unique_filename
def _format_attachment_message(self, caption, file_path):
"""Format message with attachment info for Kiro CLI"""
context = "Note: The user sent this via Telegram. The attachment was downloaded to the local filesystem at the path below."
if caption:
return f"{context}\\n\\n{caption}\\n\\nThe attachment is {file_path}"
return f"{context}\\n\\nThe attachment is {file_path}"
async def handle_photo(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle photo uploads"""
username = update.effective_user.username
if username != self.authorized_user:
return
try:
# Get highest resolution photo
photo = update.message.photo[-1]
file = await context.bot.get_file(photo.file_id)
# Generate path and download
user_id = update.effective_user.id
filename = f"photo_{photo.file_id[-8:]}.jpg"
file_path = self._generate_attachment_path(user_id, filename)
await file.download_to_drive(file_path)
logger.info(f"Downloaded photo to {file_path}")
# Format message and send to Kiro
caption = update.message.caption or ""
message = self._format_attachment_message(caption, str(file_path))
message = message.replace("\n", "\\n")
chat_id = update.effective_chat.id
thread_id = getattr(update.message, "message_thread_id", None)
# Group topic routing
if update.effective_chat.type in ("group", "supergroup") and thread_id:
agent_name = await self._resolve_topic_agent(update, context, thread_id)
if agent_name:
if agent_name not in self.kiro.agents:
self.kiro.start_agent_background(agent_name=agent_name)
import asyncio
await asyncio.sleep(2)
await context.bot.send_chat_action(
chat_id=chat_id,
action=ChatAction.TYPING,
message_thread_id=thread_id,
)
self.kiro.send_message_to_agent(
agent_name, message, chat_id, thread_id
)
return
# 1-to-1 chat
self.kiro.set_chat_id(chat_id)
self.kiro.last_typing_indicator = 0
self.kiro.send_to_kiro(message)
await update.effective_chat.send_action(ChatAction.TYPING)
except Exception as e:
logger.error(f"Error handling photo: {e}")
await update.message.reply_text(f"❌ Failed to process photo: {e}")
async def handle_document(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle document uploads"""
username = update.effective_user.username
if username != self.authorized_user:
return
try:
document = update.message.document
file = await context.bot.get_file(document.file_id)
# Generate path and download
user_id = update.effective_user.id
filename = document.file_name or f"document_{document.file_id[-8:]}"
file_path = self._generate_attachment_path(user_id, filename)
await file.download_to_drive(file_path)
logger.info(f"Downloaded document to {file_path}")
# Format message and send to Kiro
caption = update.message.caption or ""
message = self._format_attachment_message(caption, str(file_path))
message = message.replace("\n", "\\n")
chat_id = update.effective_chat.id
thread_id = getattr(update.message, "message_thread_id", None)
# Group topic routing
if update.effective_chat.type in ("group", "supergroup") and thread_id:
agent_name = await self._resolve_topic_agent(update, context, thread_id)
if agent_name:
if agent_name not in self.kiro.agents:
self.kiro.start_agent_background(agent_name=agent_name)
import asyncio
await asyncio.sleep(2)
await context.bot.send_chat_action(
chat_id=chat_id,
action=ChatAction.TYPING,
message_thread_id=thread_id,
)
self.kiro.send_message_to_agent(
agent_name, message, chat_id, thread_id
)
return
# 1-to-1 chat
self.kiro.set_chat_id(chat_id)
self.kiro.last_typing_indicator = 0
self.kiro.send_to_kiro(message)
await update.effective_chat.send_action(ChatAction.TYPING)
except Exception as e:
logger.error(f"Error handling document: {e}")
await update.message.reply_text(f"❌ Failed to process document: {e}")
async def handle_group_message(
self,
update: Update,
context: ContextTypes.DEFAULT_TYPE,
thread_id_override: int = None,
):
"""Handle message in a group forum topic."""
thread_id = (
thread_id_override
if thread_id_override is not None
else update.message.message_thread_id
)
if thread_id is None:
return # General topic or non-forum message
chat_id = update.effective_chat.id
message_text = update.message.text
# Check for intercepted commands first
if message_text and await self.handle_intercepted_commands_group(
update, context, thread_id
):
return
# Resolve topic to agent
agent_name = await self._resolve_topic_agent(update, context, thread_id)
if not agent_name:
return
# Ensure agent session is running
if agent_name not in self.kiro.agents:
await context.bot.send_message(
chat_id=chat_id,
text=f"🔄 Starting agent `{agent_name}`...",
message_thread_id=thread_id,
parse_mode="HTML",
)
self.kiro.start_agent_background(agent_name=agent_name)
# Give it time to start
import asyncio
await asyncio.sleep(2)
# Send typing indicator
await context.bot.send_chat_action(
chat_id=chat_id, action=ChatAction.TYPING, message_thread_id=thread_id
)
# Route message to agent
text = message_text.replace("\n", "\\n") if message_text else ""
self.kiro.send_message_to_agent(agent_name, text, chat_id, thread_id)
async def _resolve_topic_agent(self, update, context, thread_id):
"""Resolve a topic's thread_id to an agent name."""
chat_id = update.effective_chat.id
# Check cache first
if thread_id in self._topic_agent_cache:
return self._topic_agent_cache[thread_id]
# Try to get topic name from the message's reply_to_message (forum_topic_created)
topic_name = None
if (
update.message.reply_to_message
and update.message.reply_to_message.forum_topic_created
):
topic_name = update.message.reply_to_message.forum_topic_created.name
if not topic_name:
# Fallback: try getForumTopicIconSticker or ask user to register
await context.bot.send_message(
chat_id=chat_id,
text="❓ Can't determine topic name. Use `\\topic register <agent>` in this topic to map it.",
message_thread_id=thread_id,
parse_mode="HTML",
)
return None
# Match to agent
agent_name = self._match_agent_name(topic_name)
if not agent_name:
agents = self._get_available_agent_names()
agents_list = "\n".join(f"• <code>{a}</code>" for a in agents)
await context.bot.send_message(
chat_id=chat_id,
text=f"❌ No agent matches topic '<b>{topic_name}</b>'\n\nAvailable agents:\n{agents_list}",
message_thread_id=thread_id,
parse_mode="HTML",
)
return None
# Cache it
self._topic_agent_cache[thread_id] = agent_name
self._save_topic_cache()
logger.info(f"Cached topic {thread_id} -> agent {agent_name}")
return agent_name
async def handle_forum_topic_created(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
):
"""Handle forum topic creation — auto-populate cache if name matches an agent."""
if update.effective_user.username != self.authorized_user:
return
topic = update.message.forum_topic_created
if not topic:
return
thread_id = update.message.message_thread_id
agent_name = self._match_agent_name(topic.name)
if agent_name:
self._topic_agent_cache[thread_id] = agent_name
self._save_topic_cache()
logger.info(f"Auto-cached new topic {thread_id} -> {agent_name}")
async def handle_forum_topic_edited(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
):
"""Handle forum topic rename — update or invalidate cache."""
if update.effective_user.username != self.authorized_user:
return
edited = update.message.forum_topic_edited
if not edited:
return
thread_id = update.message.message_thread_id
new_name = getattr(edited, "name", None)
if new_name:
agent_name = self._match_agent_name(new_name)
if agent_name:
self._topic_agent_cache[thread_id] = agent_name
self._save_topic_cache()
logger.info(f"Updated topic cache {thread_id} -> {agent_name}")
elif thread_id in self._topic_agent_cache:
del self._topic_agent_cache[thread_id]
self._save_topic_cache()
logger.info(
f"Invalidated topic cache for {thread_id} (renamed to '{new_name}')"
)
async def handle_intercepted_commands_group(
self, update: Update, context: ContextTypes.DEFAULT_TYPE, thread_id: int
) -> bool:
"""Handle bot commands in group topics. Returns True if intercepted."""
message_text = update.message.text.strip()
normalized = message_text.replace("\\", "/")
chat_id = update.effective_chat.id
# Topic management commands
if normalized.startswith("/topic"):
parts = normalized.split()
if len(parts) >= 2:
if parts[1] == "register" and len(parts) >= 3:
agent_name = parts[2]
matched = self._match_agent_name(agent_name)
if matched:
self._topic_agent_cache[thread_id] = matched
self._save_topic_cache()
await context.bot.send_message(
chat_id=chat_id,
text=f"✅ Topic registered to agent `{matched}`",
message_thread_id=thread_id,
parse_mode="HTML",
)
else:
await context.bot.send_message(
chat_id=chat_id,
text=f"❌ No agent named '{agent_name}'",
message_thread_id=thread_id,
)
return True
elif parts[1] == "sync":
await self._sync_topics(update, context)
return True
return True
# Cancel - scoped to this topic's agent
if normalized == "/cancel":
agent_name = self._topic_agent_cache.get(thread_id)
if agent_name:
self.kiro.cancel_operation(agent_name=agent_name)
await context.bot.send_message(
chat_id=chat_id,
text=f"🛑 Cancelling operation for `{agent_name}`...",
message_thread_id=thread_id,
parse_mode="HTML",
)
else:
await context.bot.send_message(
chat_id=chat_id,
text="🛑 No agent mapped to this topic",
message_thread_id=thread_id,
)
return True
# Context - scoped to topic's agent
if normalized == "/context":
agent_name = self._topic_agent_cache.get(thread_id)
if agent_name and agent_name in self.kiro.agents:
agent_data = self.kiro.agents[agent_name]
session_id = agent_data["session_id"]
usage = self.kiro.context_tracker.get_usage(session_id)
text = (
f"📊 Context usage ({agent_name}): {usage:.1f}%"
if usage
else f"📊 Context usage ({agent_name}): Unknown"
)
await context.bot.send_message(
chat_id=chat_id, text=text, message_thread_id=thread_id
)
else:
await context.bot.send_message(
chat_id=chat_id,
text="❌ No active agent for this topic",
message_thread_id=thread_id,
)
return True
# Compact - scoped to topic's agent
if normalized == "/compact":
agent_name = self._topic_agent_cache.get(thread_id)
if agent_name and agent_name in self.kiro.agents:
self.kiro.send_message_to_agent(
agent_name, "/compact", chat_id, thread_id
)
else:
await context.bot.send_message(
chat_id=chat_id,
text="❌ No active agent for this topic",
message_thread_id=thread_id,
)
return True
# Agent list
if normalized == "/agent list":
await self.list_agents(update, context)
return True
# Model commands scoped to topic's agent
if normalized.startswith("/model"):
agent_name = self._topic_agent_cache.get(thread_id)
parts = normalized.split(maxsplit=1)
if len(parts) >= 2:
if parts[1] == "list":
if agent_name and agent_name in self.kiro.agents:
models_info = self.kiro.get_available_models(agent_name)
if models_info:
current_model = models_info.get("currentModelId", "unknown")
available_models = models_info.get("availableModels", [])
response = f"<b>Model ({agent_name}):</b> <code>{current_model}</code>\n\n<b>Available:</b>\n"
for model in available_models:
mid = model.get("modelId", "unknown")
desc = model.get("description", "")
marker = "→ " if mid == current_model else " "
response += f"{marker}<code>{mid}</code> - {desc}\n"
await context.bot.send_message(
chat_id=chat_id,
text=response,
message_thread_id=thread_id,
parse_mode="HTML",
)
else:
await context.bot.send_message(
chat_id=chat_id,
text="❌ No model info available",
message_thread_id=thread_id,
)
else:
await context.bot.send_message(
chat_id=chat_id,
text="❌ No active agent for this topic",
message_thread_id=thread_id,
)
else:
model_id = parts[1]
if agent_name and agent_name in self.kiro.agents:
self.kiro.set_model(model_id, chat_id, agent_name=agent_name)
else:
await context.bot.send_message(
chat_id=chat_id,
text="❌ No active agent for this topic",
message_thread_id=thread_id,
)
else:
await context.bot.send_message(
chat_id=chat_id,
text="Usage: \\model list OR \\model <model_id>",
message_thread_id=thread_id,
)
return True
return False
async def _sync_topics(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Create forum topics for all agents that don't already have one."""
chat_id = update.effective_chat.id
thread_id = update.message.message_thread_id
agents = self._get_available_agent_names()
cached_agents = set(self._topic_agent_cache.values())
created = []
for agent in agents:
if agent not in cached_agents:
try:
result = await context.bot.create_forum_topic(
chat_id=chat_id, name=agent
)
self._topic_agent_cache[result.message_thread_id] = agent
created.append(agent)
except Exception as e:
logger.warning(f"Failed to create topic for '{agent}': {e}")
self._save_topic_cache()
if created:
msg = f"✅ Created {len(created)} topics:\n" + "\n".join(
f"• {a}" for a in created
)
else:
msg = "✅ All agents already have topics"
await context.bot.send_message(
chat_id=chat_id, text=msg, message_thread_id=thread_id
)
async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle incoming messages"""
# Store the event loop for thread-safe calls
if not self.loop:
import asyncio
self.loop = asyncio.get_running_loop()
# Set the loop on the callback so worker thread can use it
self.kiro.send_to_telegram.loop = self.loop
# Also set it on kiro for typing indicator
self.kiro.event_loop = self.loop
logger.info(f"Event loop set: {self.loop}")
username = update.effective_user.username
chat_id = update.effective_chat.id
print(f"[DEBUG] Received message from user: {username}")
if username != self.authorized_user:
print(f"[DEBUG] Unauthorized user {username}, ignoring")
return
message_text = update.message.text
# Route group forum messages to topic handler
if update.effective_chat.type in ("group", "supergroup"):
if (
hasattr(update.message, "is_topic_message")
and update.message.is_topic_message
):
await self.handle_group_message(update, context)
return
# General topic in forum groups (not marked as is_topic_message)
if getattr(update.effective_chat, "is_forum", False):
# Treat as General — route to group handler with no thread_id
await self.handle_group_message(update, context, thread_id_override=0)
return
# Non-forum group message, ignore
return
# Check if user is in a conversation state
if chat_id in self.user_states:
await self.handle_conversation_state(update, context)
return
print(f"[DEBUG] About to check intercepted commands for: {message_text}")
# Check for intercepted commands before processing
if await self.handle_intercepted_commands(update, context):
print(f"[DEBUG] Command was intercepted, returning")
return
print(f"[DEBUG] Command not intercepted, proceeding to kiro-cli")
# Normal message processing
message_text = message_text.replace("\n", "\\n")
print(f"[DEBUG] Processing message: {message_text}")
# Show typing indicator briefly
await context.bot.send_chat_action(
chat_id=update.effective_chat.id, action=ChatAction.TYPING
)
# Send to Kiro (non-blocking via queue)
print(f"[DEBUG] Sending to Kiro: {message_text}")
self.kiro.send_message(message_text, update.effective_chat.id)
async def handle_intercepted_commands(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> bool:
"""Handle intercepted kiro commands. Returns True if command was intercepted."""
message_text = update.message.text.strip()
print(f"[DEBUG] Checking interception for: {message_text}")
# Normalize backslash to forward slash for consistent processing
normalized_text = message_text.replace("\\", "/")
print(f"[DEBUG] Normalized text: {normalized_text}")
# Help command
if normalized_text == "/help":
print(f"[DEBUG] Intercepted help command")
await self.show_help(update, context)
return True
# Usage command
if normalized_text == "/usage":
print(f"[DEBUG] Intercepted usage command")
await self.show_usage(update, context)
return True
# Cancel command
if normalized_text == "/cancel":
print(f"[DEBUG] Intercepted cancel command")
self.kiro.cancel_operation()
await update.message.reply_text("🛑 Cancelling operation...")
return True
# Subagents command
if normalized_text == "/subagents":
print(f"[DEBUG] Intercepted subagents command")
await self.show_subagents(update, context)
return True
if normalized_text.startswith("/subagents kill "):
name = normalized_text[len("/subagents kill ") :].strip()
if name:
result = self.kiro.terminate_subagent(name)
await update.message.reply_text(result)
return True
# Model commands
if normalized_text.startswith("/model"):
print(f"[DEBUG] Intercepted model command")
parts = normalized_text.split(maxsplit=1)
if len(parts) == 2:
if parts[1] == "list":
await self.show_models(update, context)
return True
else:
# Set model
model_id = parts[1]
await self.set_model(update, context, model_id)
return True
else:
await update.message.reply_text(
"Usage: \\model list OR \\model <model_id>"
)
return True
# Agent commands
if normalized_text.startswith("/agent"):
print(f"[DEBUG] Intercepted agent command")
parts = normalized_text.split()
if len(parts) == 1:
# Just "/agent" with no subcommand
await update.message.reply_text(
"Usage: /agent <create|list|swap|delete> [name]"
)
return True
elif len(parts) >= 2:
subcommand = parts[1]
print(f"[DEBUG] Agent subcommand: {subcommand}")
if subcommand == "create":
if len(parts) >= 3:
agent_name = parts[2]
await self.start_agent_creation(update, context, agent_name)
else:
await update.message.reply_text("Usage: /agent create <name>")
return True
elif subcommand == "list":
print(f"[DEBUG] Calling list_agents")
await self.list_agents(update, context)
return True
elif subcommand == "swap":
if len(parts) >= 3:
agent_name = parts[2]
await self.swap_agent(update, context, agent_name)
else:
await update.message.reply_text("Usage: /agent swap <name>")
return True
elif subcommand == "delete":
if len(parts) >= 3:
agent_name = parts[2]
await self.delete_agent(update, context, agent_name)
else:
await update.message.reply_text("Usage: /agent delete <name>")
return True
# Chat commands
elif normalized_text.startswith("/chat"):
print(f"[DEBUG] Intercepted chat command")
parts = normalized_text.split()
if len(parts) == 1:
# Just "/chat" with no subcommand
await update.message.reply_text("Usage: /chat <save|load|list> [name]")
return True
elif len(parts) >= 2:
subcommand = parts[1]
print(f"[DEBUG] Chat subcommand: {subcommand}")
if subcommand == "save" and len(parts) >= 3:
chat_name = parts[2]
await self.save_chat(update, context, chat_name)
return True
elif subcommand == "load" and len(parts) >= 3:
chat_name = parts[2]
await self.load_chat(update, context, chat_name)
return True
elif subcommand == "list":
await self.list_chats(update, context)
return True
# Context commands
elif normalized_text.startswith("/context"):
print(f"[DEBUG] Intercepted context command")
parts = normalized_text.split()
if len(parts) == 1:
# Just "/context" - show usage
await self.show_context_usage(update, context)
return True
elif len(parts) >= 2:
subcommand = parts[1]
if subcommand == "show":
# Send as regular message, not as command
self.kiro.send_message("/context show", update.effective_chat.id)
return True
elif subcommand == "clear":
# Send as regular message, not as command
self.kiro.send_message("/context clear", update.effective_chat.id)
return True
# Compact command
elif normalized_text == "/compact":
print(f"[DEBUG] Intercepted compact command")
# Send as regular message, not as command
self.kiro.send_message("/compact", update.effective_chat.id)
return True
return False
async def start_agent_creation(
self, update: Update, context: ContextTypes.DEFAULT_TYPE, agent_name: str
):
"""Start agent creation flow from intercepted command"""
chat_id = update.effective_chat.id
# Validate agent name
valid, error_msg = self.validate_agent_name(agent_name)
if not valid:
await update.message.reply_text(f"❌ Invalid agent name: {error_msg}")
return
# Check if agent already exists
agent_file = Path.home() / ".kiro" / "agents" / f"{agent_name}.json"
if agent_file.exists():
await update.message.reply_text(f"❌ Agent '{agent_name}' already exists!")
return
# Start conversation flow
self.user_states[chat_id] = {
"type": "create_agent",
"step": "description",
"agent_name": agent_name,
}
# Suppress background agent output during interactive flow
self.kiro.suppress_output = True
await update.message.reply_text(
f"Creating agent '{agent_name}'...\n\nWhat's the agent description?"
)
async def list_agents(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle intercepted /agent list command"""
print(f"[DEBUG] list_agents called")
print(f"[DEBUG] Update object: {update}")
print(f"[DEBUG] Context object: {context}")
# Authorization check
if update.effective_user.username != self.authorized_user:
print(
f"[DEBUG] Unauthorized user: {update.effective_user.username} != {self.authorized_user}"
)
return
try:
# Built-in agents
builtin_agents = ["kiro_default", "kiro_planner"]
print(f"[DEBUG] Built-in agents: {builtin_agents}")
# Get custom agents from ~/.kiro/agents/
custom_agents = []
agents_dir = Path.home() / ".kiro" / "agents"
print(f"[DEBUG] Checking agents dir: {agents_dir}")
if agents_dir.exists():
for agent_file in agents_dir.glob("*.json"):
custom_agents.append(agent_file.stem)
print(f"[DEBUG] Custom agents: {custom_agents}")
print(f"[DEBUG] Active agent: {self.kiro.active_agent}")
# Format response with HTML for tappable agent names
pending_agents = set(self.kiro.agents_with_pending_output())
response = "<b>Available agents:</b>\n\n"
response += "<b>Built-in agents:</b>\n"
for agent in builtin_agents:
current_marker = " ← active" if agent == self.kiro.active_agent else ""
pending_marker = " *" if agent in pending_agents else ""
response += f"• <code>{agent}</code>{current_marker}{pending_marker}\n"
if custom_agents:
response += "\n<b>Custom agents:</b>\n"
for agent in sorted(custom_agents):
current_marker = (
" ← active" if agent == self.kiro.active_agent else ""
)
pending_marker = " *" if agent in pending_agents else ""
response += (
f"• <code>{agent}</code>{current_marker}{pending_marker}\n"
)
if pending_agents:
response += "\n* = has pending output"
print(f"[DEBUG] Final response length: {len(response)}")
print(f"[DEBUG] Final response: '{response}'")
print(f"[DEBUG] About to send reply_text")
await update.message.reply_text(response, parse_mode="HTML")
print(f"[DEBUG] Reply sent successfully")
except Exception as e:
print(f"[DEBUG] Error in list_agents: {e}")
print(f"[DEBUG] Exception type: {type(e)}")
import traceback
print(f"[DEBUG] Traceback: {traceback.format_exc()}")
await update.message.reply_text(f"Error: {e}")
async def show_subagents(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show active subagents for the current agent."""
if update.effective_user.username != self.authorized_user:
return
subagents = self.kiro.get_subagents()
if not subagents:
await update.message.reply_text("No active subagents")
return
response = f"<b>Active subagents</b> ({len(subagents)}):\n\n"
for sid, info in subagents.items():
response += f"🔀 <code>{info['name']}</code>\n"
if info.get("last_tool"):
response += f" 🔧 {info['last_tool']}\n"
elif info.get("query"):
response += f" {info['query']}\n"
await update.message.reply_text(response, parse_mode="HTML")
async def show_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show all available bot commands"""
help_text = """📚 Telegram Kiro Bot Commands
Agent Management
\\agent list - List all agents
\\agent swap <name> - Switch to agent
\\agent create <name> - Create new agent
\\agent delete <name> - Delete agent
Conversation Management
\\chat save <name> - Save conversation
\\chat load <name> - Load conversation
\\chat list - List saved conversations
Context Management