-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathorchestrator.py
More file actions
1900 lines (1660 loc) · 73.4 KB
/
orchestrator.py
File metadata and controls
1900 lines (1660 loc) · 73.4 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
"""Message orchestrator — single entry point for all Telegram updates.
Routes messages based on agentic vs classic mode. In agentic mode, provides
a minimal conversational interface (3 commands, no inline keyboards). In
classic mode, delegates to existing full-featured handlers.
"""
import asyncio
import re
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
import structlog
from telegram import (
BotCommand,
InlineKeyboardButton,
InlineKeyboardMarkup,
InputMediaPhoto,
Update,
)
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
from ..claude.sdk_integration import StreamUpdate
from ..config.settings import Settings
from ..projects import PrivateTopicsUnavailableError
from .utils.draft_streamer import DraftStreamer, generate_draft_id
from .utils.html_format import escape_html
from .utils.image_extractor import (
FileAttachment,
ImageAttachment,
should_send_as_photo,
validate_file_path,
validate_image_path,
)
logger = structlog.get_logger()
# Patterns that look like secrets/credentials in CLI arguments
_SECRET_PATTERNS: List[re.Pattern[str]] = [
# API keys / tokens (sk-ant-..., sk-..., ghp_..., gho_..., github_pat_..., xoxb-...)
re.compile(
r"(sk-ant-api\d*-[A-Za-z0-9_-]{10})[A-Za-z0-9_-]*"
r"|(sk-[A-Za-z0-9_-]{20})[A-Za-z0-9_-]*"
r"|(ghp_[A-Za-z0-9]{5})[A-Za-z0-9]*"
r"|(gho_[A-Za-z0-9]{5})[A-Za-z0-9]*"
r"|(github_pat_[A-Za-z0-9_]{5})[A-Za-z0-9_]*"
r"|(xoxb-[A-Za-z0-9]{5})[A-Za-z0-9-]*"
),
# AWS access keys
re.compile(r"(AKIA[0-9A-Z]{4})[0-9A-Z]{12}"),
# Generic long hex/base64 tokens after common flags/env patterns
re.compile(
r"((?:--token|--secret|--password|--api-key|--apikey|--auth)"
r"[= ]+)['\"]?[A-Za-z0-9+/_.:-]{8,}['\"]?"
),
# Inline env assignments like KEY=value
re.compile(
r"((?:TOKEN|SECRET|PASSWORD|API_KEY|APIKEY|AUTH_TOKEN|PRIVATE_KEY"
r"|ACCESS_KEY|CLIENT_SECRET|WEBHOOK_SECRET)"
r"=)['\"]?[^\s'\"]{8,}['\"]?"
),
# Bearer / Basic auth headers
re.compile(r"(Bearer )[A-Za-z0-9+/_.:-]{8,}" r"|(Basic )[A-Za-z0-9+/=]{8,}"),
# Connection strings with credentials user:pass@host
re.compile(r"://([^:]+:)[^@]{4,}(@)"),
]
def _redact_secrets(text: str) -> str:
"""Replace likely secrets/credentials with redacted placeholders."""
result = text
for pattern in _SECRET_PATTERNS:
result = pattern.sub(
lambda m: next((g + "***" for g in m.groups() if g is not None), "***"),
result,
)
return result
# Tool name -> friendly emoji mapping for verbose output
_TOOL_ICONS: Dict[str, str] = {
"Read": "\U0001f4d6",
"Write": "\u270f\ufe0f",
"Edit": "\u270f\ufe0f",
"MultiEdit": "\u270f\ufe0f",
"Bash": "\U0001f4bb",
"Glob": "\U0001f50d",
"Grep": "\U0001f50d",
"LS": "\U0001f4c2",
"Task": "\U0001f9e0",
"TaskOutput": "\U0001f9e0",
"WebFetch": "\U0001f310",
"WebSearch": "\U0001f310",
"NotebookRead": "\U0001f4d3",
"NotebookEdit": "\U0001f4d3",
"TodoRead": "\u2611\ufe0f",
"TodoWrite": "\u2611\ufe0f",
}
def _tool_icon(name: str) -> str:
"""Return emoji for a tool, with a default wrench."""
return _TOOL_ICONS.get(name, "\U0001f527")
class MessageOrchestrator:
"""Routes messages based on mode. Single entry point for all Telegram updates."""
def __init__(self, settings: Settings, deps: Dict[str, Any]):
self.settings = settings
self.deps = deps
def _inject_deps(self, handler: Callable) -> Callable: # type: ignore[type-arg]
"""Wrap handler to inject dependencies into context.bot_data."""
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
for key, value in self.deps.items():
context.bot_data[key] = value
context.bot_data["settings"] = self.settings
context.user_data.pop("_thread_context", None)
is_sync_bypass = handler.__name__ == "sync_threads"
is_start_bypass = handler.__name__ in {"start_command", "agentic_start"}
message_thread_id = self._extract_message_thread_id(update)
should_enforce = self.settings.enable_project_threads
if should_enforce:
if self.settings.project_threads_mode == "private":
should_enforce = not is_sync_bypass and not (
is_start_bypass and message_thread_id is None
)
else:
should_enforce = not is_sync_bypass
if should_enforce:
allowed = await self._apply_thread_routing_context(update, context)
if not allowed:
return
try:
await handler(update, context)
finally:
if should_enforce:
self._persist_thread_state(context)
return wrapped
async def _apply_thread_routing_context(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> bool:
"""Enforce strict project-thread routing and load thread-local state."""
manager = context.bot_data.get("project_threads_manager")
if manager is None:
await self._reject_for_thread_mode(
update,
"❌ <b>Project Thread Mode Misconfigured</b>\n\n"
"Thread manager is not initialized.",
)
return False
chat = update.effective_chat
message = update.effective_message
if not chat or not message:
return False
if self.settings.project_threads_mode == "group":
if chat.id != self.settings.project_threads_chat_id:
await self._reject_for_thread_mode(
update,
manager.guidance_message(mode=self.settings.project_threads_mode),
)
return False
else:
if getattr(chat, "type", "") != "private":
await self._reject_for_thread_mode(
update,
manager.guidance_message(mode=self.settings.project_threads_mode),
)
return False
message_thread_id = self._extract_message_thread_id(update)
if not message_thread_id:
await self._reject_for_thread_mode(
update,
manager.guidance_message(mode=self.settings.project_threads_mode),
)
return False
project = await manager.resolve_project(chat.id, message_thread_id)
if not project:
await self._reject_for_thread_mode(
update,
manager.guidance_message(mode=self.settings.project_threads_mode),
)
return False
state_key = f"{chat.id}:{message_thread_id}"
thread_states = context.user_data.setdefault("thread_state", {})
state = thread_states.get(state_key, {})
project_root = project.absolute_path
current_dir_raw = state.get("current_directory")
current_dir = (
Path(current_dir_raw).resolve() if current_dir_raw else project_root
)
if not self._is_within(current_dir, project_root) or not current_dir.is_dir():
current_dir = project_root
context.user_data["current_directory"] = current_dir
context.user_data["claude_session_id"] = state.get("claude_session_id")
context.user_data["_thread_context"] = {
"chat_id": chat.id,
"message_thread_id": message_thread_id,
"state_key": state_key,
"project_slug": project.slug,
"project_root": str(project_root),
"project_name": project.name,
}
return True
def _persist_thread_state(self, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Persist compatibility keys back into per-thread state."""
thread_context = context.user_data.get("_thread_context")
if not thread_context:
return
project_root = Path(thread_context["project_root"])
current_dir = context.user_data.get("current_directory", project_root)
if not isinstance(current_dir, Path):
current_dir = Path(str(current_dir))
current_dir = current_dir.resolve()
if not self._is_within(current_dir, project_root) or not current_dir.is_dir():
current_dir = project_root
thread_states = context.user_data.setdefault("thread_state", {})
thread_states[thread_context["state_key"]] = {
"current_directory": str(current_dir),
"claude_session_id": context.user_data.get("claude_session_id"),
"project_slug": thread_context["project_slug"],
}
@staticmethod
def _is_within(path: Path, root: Path) -> bool:
"""Return True if path is within root."""
try:
path.relative_to(root)
return True
except ValueError:
return False
@staticmethod
def _extract_message_thread_id(update: Update) -> Optional[int]:
"""Extract topic/thread id from update message for forum/direct topics."""
message = update.effective_message
if not message:
return None
message_thread_id = getattr(message, "message_thread_id", None)
if isinstance(message_thread_id, int) and message_thread_id > 0:
return message_thread_id
dm_topic = getattr(message, "direct_messages_topic", None)
topic_id = getattr(dm_topic, "topic_id", None) if dm_topic else None
if isinstance(topic_id, int) and topic_id > 0:
return topic_id
# Telegram omits message_thread_id for the General topic in forum
# supergroups; its canonical thread ID is 1.
chat = update.effective_chat
if chat and getattr(chat, "is_forum", False):
return 1
return None
async def _reject_for_thread_mode(self, update: Update, message: str) -> None:
"""Send a guidance response when strict thread routing rejects an update."""
query = update.callback_query
if query:
try:
await query.answer()
except Exception:
pass
if query.message:
await query.message.reply_text(message, parse_mode="HTML")
return
if update.effective_message:
await update.effective_message.reply_text(message, parse_mode="HTML")
def register_handlers(self, app: Application) -> None:
"""Register handlers based on mode."""
if self.settings.agentic_mode:
self._register_agentic_handlers(app)
else:
self._register_classic_handlers(app)
def _register_agentic_handlers(self, app: Application) -> None:
"""Register agentic handlers: commands + text/file/photo."""
from .handlers import command
# Commands
handlers = [
("start", self.agentic_start),
("new", self.agentic_new),
("stop", self.agentic_stop),
("status", self.agentic_status),
("verbose", self.agentic_verbose),
("cleanup", self.agentic_cleanup),
("repo", self.agentic_repo),
("restart", command.restart_command),
]
if self.settings.enable_project_threads:
handlers.append(("sync_threads", command.sync_threads))
for cmd, handler in handlers:
app.add_handler(CommandHandler(cmd, self._inject_deps(handler)))
# Text messages -> Claude
app.add_handler(
MessageHandler(
filters.TEXT & ~filters.COMMAND,
self._inject_deps(self.agentic_text),
),
group=10,
)
# File uploads -> Claude (documents, audio files, video files)
app.add_handler(
MessageHandler(
filters.Document.ALL | filters.AUDIO | filters.VIDEO,
self._inject_deps(self.agentic_document),
),
group=10,
)
# Photo uploads -> Claude
app.add_handler(
MessageHandler(filters.PHOTO, self._inject_deps(self.agentic_photo)),
group=10,
)
# Voice messages -> transcribe -> Claude
app.add_handler(
MessageHandler(filters.VOICE, self._inject_deps(self.agentic_voice)),
group=10,
)
# Only cd: callbacks (for project selection), scoped by pattern
app.add_handler(
CallbackQueryHandler(
self._inject_deps(self._agentic_callback),
pattern=r"^cd:",
)
)
logger.info("Agentic handlers registered")
def _register_classic_handlers(self, app: Application) -> None:
"""Register full classic handler set (moved from core.py)."""
from .handlers import callback, command, message
handlers = [
("start", command.start_command),
("help", command.help_command),
("new", command.new_session),
("continue", command.continue_session),
("end", command.end_session),
("ls", command.list_files),
("cd", command.change_directory),
("pwd", command.print_working_directory),
("projects", command.show_projects),
("status", command.session_status),
("export", command.export_session),
("actions", command.quick_actions),
("git", command.git_command),
("restart", command.restart_command),
]
if self.settings.enable_project_threads:
handlers.append(("sync_threads", command.sync_threads))
for cmd, handler in handlers:
app.add_handler(CommandHandler(cmd, self._inject_deps(handler)))
app.add_handler(
MessageHandler(
filters.TEXT & ~filters.COMMAND,
self._inject_deps(message.handle_text_message),
),
group=10,
)
app.add_handler(
MessageHandler(
filters.Document.ALL, self._inject_deps(message.handle_document)
),
group=10,
)
app.add_handler(
MessageHandler(filters.PHOTO, self._inject_deps(message.handle_photo)),
group=10,
)
app.add_handler(
MessageHandler(filters.VOICE, self._inject_deps(message.handle_voice)),
group=10,
)
app.add_handler(
CallbackQueryHandler(self._inject_deps(callback.handle_callback_query))
)
logger.info("Classic handlers registered (13 commands + full handler set)")
async def get_bot_commands(self) -> list: # type: ignore[type-arg]
"""Return bot commands appropriate for current mode."""
if self.settings.agentic_mode:
commands = [
BotCommand("start", "Start the bot"),
BotCommand("new", "Start a fresh session"),
BotCommand("stop", "Stop current Claude task"),
BotCommand("status", "Show session status"),
BotCommand("verbose", "Set output verbosity (0/1/2/3)"),
BotCommand("cleanup", "Delete tool/thinking messages"),
BotCommand("repo", "List repos / switch workspace"),
BotCommand("restart", "Restart the bot"),
]
if self.settings.enable_project_threads:
commands.append(BotCommand("sync_threads", "Sync project topics"))
return commands
else:
commands = [
BotCommand("start", "Start bot and show help"),
BotCommand("help", "Show available commands"),
BotCommand("new", "Clear context and start fresh session"),
BotCommand("continue", "Explicitly continue last session"),
BotCommand("end", "End current session and clear context"),
BotCommand("ls", "List files in current directory"),
BotCommand("cd", "Change directory (resumes project session)"),
BotCommand("pwd", "Show current directory"),
BotCommand("projects", "Show all projects"),
BotCommand("status", "Show session status"),
BotCommand("export", "Export current session"),
BotCommand("actions", "Show quick actions"),
BotCommand("git", "Git repository commands"),
BotCommand("restart", "Restart the bot"),
]
if self.settings.enable_project_threads:
commands.append(BotCommand("sync_threads", "Sync project topics"))
return commands
# --- Agentic handlers ---
async def agentic_start(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Brief welcome, no buttons."""
user = update.effective_user
sync_line = ""
if (
self.settings.enable_project_threads
and self.settings.project_threads_mode == "private"
):
if (
not update.effective_chat
or getattr(update.effective_chat, "type", "") != "private"
):
await update.message.reply_text(
"🚫 <b>Private Topics Mode</b>\n\n"
"Use this bot in a private chat and run <code>/start</code> there.",
parse_mode="HTML",
)
return
manager = context.bot_data.get("project_threads_manager")
if manager:
try:
result = await manager.sync_topics(
context.bot,
chat_id=update.effective_chat.id,
)
sync_line = (
"\n\n🧵 Topics synced"
f" (created {result.created}, reused {result.reused})."
)
except PrivateTopicsUnavailableError:
await update.message.reply_text(
manager.private_topics_unavailable_message(),
parse_mode="HTML",
)
return
except Exception:
sync_line = "\n\n🧵 Topic sync failed. Run /sync_threads to retry."
current_dir = context.user_data.get(
"current_directory", self.settings.approved_directory
)
dir_display = f"<code>{current_dir}/</code>"
safe_name = escape_html(user.first_name)
await update.message.reply_text(
f"Hi {safe_name}! I'm your AI coding assistant.\n"
f"Just tell me what you need — I can read, write, and run code.\n\n"
f"Working in: {dir_display}\n"
f"Commands: /new (reset) · /status"
f"{sync_line}",
parse_mode="HTML",
)
async def agentic_new(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Reset session, one-line confirmation."""
context.user_data["claude_session_id"] = None
context.user_data["session_started"] = True
context.user_data["force_new_session"] = True
await update.message.reply_text("Session reset. What's next?")
async def agentic_status(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Compact one-line status, no buttons."""
current_dir = context.user_data.get(
"current_directory", self.settings.approved_directory
)
dir_display = str(current_dir)
session_id = context.user_data.get("claude_session_id")
session_status = "active" if session_id else "none"
# Cost info
cost_str = ""
rate_limiter = context.bot_data.get("rate_limiter")
if rate_limiter:
try:
user_status = rate_limiter.get_user_status(update.effective_user.id)
cost_usage = user_status.get("cost_usage", {})
current_cost = cost_usage.get("current", 0.0)
cost_str = f" · Cost: ${current_cost:.2f}"
except Exception:
pass
await update.message.reply_text(
f"📂 {dir_display} · Session: {session_status}{cost_str}"
)
def _get_verbose_level(self, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Return effective verbose level: per-user override or global default."""
user_override = context.user_data.get("verbose_level")
if user_override is not None:
return int(user_override)
return self.settings.verbose_level
async def agentic_verbose(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Set output verbosity: /verbose [0|1|2]."""
args = update.message.text.split()[1:] if update.message.text else []
if not args:
current = self._get_verbose_level(context)
labels = {0: "quiet", 1: "normal", 2: "detailed", 3: "full"}
await update.message.reply_text(
f"Verbosity: <b>{current}</b> ({labels.get(current, '?')})\n\n"
"Usage: <code>/verbose 0|1|2|3</code>\n"
" 0 = quiet (final response only)\n"
" 1 = normal (tools + reasoning)\n"
" 2 = detailed (tools with inputs + reasoning)\n"
" 3 = full (commands + output, like vanilla Claude Code)",
parse_mode="HTML",
)
return
try:
level = int(args[0])
if level not in (0, 1, 2, 3):
raise ValueError
except ValueError:
await update.message.reply_text(
"Please use: /verbose 0, /verbose 1, /verbose 2, or /verbose 3"
)
return
context.user_data["verbose_level"] = level
labels = {0: "quiet", 1: "normal", 2: "detailed", 3: "full (commands + output)"}
await update.message.reply_text(
f"Verbosity set to <b>{level}</b> ({labels[level]})",
parse_mode="HTML",
)
async def agentic_cleanup(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Delete tool/thinking messages from the last response: /cleanup."""
msg_ids = context.user_data.get("last_tool_message_ids", [])
chat_id = context.user_data.get("last_tool_chat_id")
if not msg_ids or not chat_id:
await update.message.reply_text("No tool messages to clean up.")
return
deleted = 0
for msg_id in msg_ids:
try:
await context.bot.delete_message(chat_id=chat_id, message_id=msg_id)
deleted += 1
except Exception:
pass # message may already be deleted or too old
context.user_data["last_tool_message_ids"] = []
await update.message.reply_text(f"Cleaned up {deleted} messages.")
async def agentic_stop(
self, update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Stop the currently running Claude task: /stop."""
task = context.user_data.get("running_claude_task")
if task and not task.done():
# Kill the Claude CLI subprocess first
claude_integration = context.bot_data.get("claude_integration")
if claude_integration:
sdk_manager = getattr(claude_integration, "sdk_manager", None)
if sdk_manager:
await sdk_manager.abort()
# Then cancel the asyncio task
task.cancel()
context.user_data["running_claude_task"] = None
await update.message.reply_text("⛔ Stopped.")
else:
await update.message.reply_text("Nothing running.")
def _format_verbose_progress(
self,
activity_log: List[Dict[str, Any]],
verbose_level: int,
start_time: float,
) -> str:
"""Build the progress message text based on activity so far."""
if not activity_log:
return "Working..."
elapsed = time.time() - start_time
lines: List[str] = [f"Working... ({elapsed:.0f}s)\n"]
max_entries = 30 if verbose_level >= 3 else 15
for entry in activity_log[-max_entries:]:
kind = entry.get("kind", "tool")
if kind == "text":
snippet = entry.get("detail", "")
if verbose_level >= 3:
lines.append(f"\U0001f4ac {snippet}")
elif verbose_level >= 2:
lines.append(f"\U0001f4ac {snippet}")
else:
lines.append(f"\U0001f4ac {snippet[:80]}")
elif kind == "result":
# Tool result (level 3 only)
result = entry.get("detail", "")
if "base64" in result and len(result) > 100:
result = "[binary/image data]"
lines.append(f" \u2514\u2500 {result[:300]}")
else:
icon = _tool_icon(entry["name"])
if verbose_level >= 2 and entry.get("detail"):
lines.append(f"{icon} {entry['name']}: {entry['detail']}")
else:
lines.append(f"{icon} {entry['name']}")
if len(activity_log) > 15:
lines.insert(1, f"... ({len(activity_log) - 15} earlier entries)\n")
return "\n".join(lines)
@staticmethod
def _summarize_tool_input(tool_name: str, tool_input: Dict[str, Any]) -> str:
"""Return a short summary of tool input for verbose level 2."""
if not tool_input:
return ""
if tool_name in ("Read", "Write", "Edit", "MultiEdit"):
path = tool_input.get("file_path") or tool_input.get("path", "")
if path:
# Show just the filename, not the full path
return path.rsplit("/", 1)[-1]
if tool_name in ("Glob", "Grep"):
pattern = tool_input.get("pattern", "")
if pattern:
return pattern[:60]
if tool_name == "Bash":
cmd = tool_input.get("command", "")
if cmd:
return _redact_secrets(cmd[:100])[:80]
if tool_name in ("WebFetch", "WebSearch"):
return (tool_input.get("url", "") or tool_input.get("query", ""))[:60]
if tool_name == "Task":
desc = tool_input.get("description", "")
if desc:
return desc[:60]
# Generic: show first key's value
for v in tool_input.values():
if isinstance(v, str) and v:
return v[:60]
return ""
@staticmethod
def _start_typing_heartbeat(
chat: Any,
interval: float = 2.0,
) -> "asyncio.Task[None]":
"""Start a background typing indicator task.
Sends typing every *interval* seconds, independently of
stream events. Cancel the returned task in a ``finally``
block.
"""
async def _heartbeat() -> None:
try:
while True:
await asyncio.sleep(interval)
try:
await chat.send_action("typing")
except Exception:
pass
except asyncio.CancelledError:
pass
return asyncio.create_task(_heartbeat())
def _make_stream_callback(
self,
verbose_level: int,
progress_msg: Any,
tool_log: List[Dict[str, Any]],
start_time: float,
mcp_images: Optional[List[ImageAttachment]] = None,
approved_directory: Optional[Path] = None,
draft_streamer: Optional[DraftStreamer] = None,
chat: Any = None,
reply_to_message_id: Optional[int] = None,
) -> Optional[Callable[[StreamUpdate], Any]]:
"""Create a stream callback that sends per-event messages.
At verbose >= 1, each tool call and thinking block gets its own
Telegram message (like linuz90's bot). Tool messages are tracked
in tool_log for optional cleanup.
When *mcp_images* is provided, the callback also intercepts
``send_file_to_user`` tool calls and collects validated
:class:`ImageAttachment` objects for later Telegram delivery.
"""
need_mcp_intercept = mcp_images is not None and approved_directory is not None
if verbose_level == 0 and not need_mcp_intercept and draft_streamer is None:
return None
# Track sent tool message IDs for optional cleanup
tool_message_ids: List[int] = []
tool_log.append({"_tool_message_ids": tool_message_ids})
last_tool_msg_id: List[Optional[int]] = [None] # track last tool msg for result appending
last_edit_time = [0.0] # mutable container for throttled progress edits
has_used_tools = [False] # track whether any tool calls were seen
async def _send_tool_msg(text: str) -> Optional[int]:
"""Send a tool status message and track its ID."""
if not chat:
return None
try:
msg = await chat.send_message(text)
tool_message_ids.append(msg.message_id)
return msg.message_id
except Exception:
return None
async def _edit_tool_msg(msg_id: int, text: str) -> None:
"""Edit a previously sent tool message."""
if not chat:
return
try:
await chat._bot.edit_message_text(
text, chat_id=chat.id, message_id=msg_id
)
except Exception:
pass
def _format_tool_detail(name: str, tool_input: dict) -> str:
"""Format tool input for display — clean, human-readable."""
if name == "Bash":
cmd = tool_input.get("command", "")
# Show first 200 chars of command
return cmd[:200] + ("..." if len(cmd) > 200 else "")
elif name in ("Read", "Write", "Edit", "MultiEdit"):
path = tool_input.get("file_path", "")
return path.rsplit("/", 1)[-1] if "/" in path else path
elif name in ("Grep", "Glob"):
pattern = tool_input.get("pattern", "")
path = tool_input.get("path", "")
short_path = path.rsplit("/", 1)[-1] if "/" in path else path
return f'"{pattern}" in {short_path}' if short_path else f'"{pattern}"'
elif name == "Skill":
return tool_input.get("skill", "")
elif name == "ToolSearch":
return tool_input.get("query", "")
elif name in ("WebFetch", "WebSearch"):
return (tool_input.get("url", "") or tool_input.get("query", ""))[:80]
elif "send_file" in name or "send_image" in name:
path = tool_input.get("file_path", "")
return path.rsplit("/", 1)[-1] if "/" in path else path
else:
# Generic: show first meaningful value
for v in tool_input.values():
if isinstance(v, str) and v:
return v[:80]
return ""
def _clean_result(text: str) -> str:
"""Clean tool result for display."""
if not text:
return ""
# Skip binary/base64 data
if "base64" in text or len(text) > 1000:
if "base64" in text:
return "[imagen/datos binarios]"
return text[:200] + "..."
# Clean up common noise
text = text.strip()
if text.startswith("[{'type':") or text.startswith("{'type':"):
return "[datos estructurados]"
return text[:300]
async def _on_stream(update_obj: StreamUpdate) -> None:
# Intercept send_file_to_user / send_image_to_user MCP tool calls
if update_obj.tool_calls and need_mcp_intercept:
for tc in update_obj.tool_calls:
tc_name = tc.get("name", "")
if tc_name in ("send_file_to_user", "send_image_to_user") or tc_name.endswith(
("__send_file_to_user", "__send_image_to_user")
):
tc_input = tc.get("input", {})
file_path = tc_input.get("file_path", "")
caption = tc_input.get("caption", "")
attachment = validate_file_path(
file_path, approved_directory, caption
)
if attachment:
mcp_images.append(attachment)
# Send per-event messages for tool calls
if update_obj.tool_calls:
has_used_tools[0] = True
# Extended thinking (ThinkingBlocks — Claude's internal reasoning)
if update_obj.type == "thinking" and update_obj.content:
thinking = update_obj.content.strip()
if thinking and verbose_level >= 1:
# Show first line of thinking as a 🧠 message
first_line = thinking.split("\n", 1)[0].strip()[:200]
if first_line:
await _send_tool_msg(f"🧠 {first_line}")
tool_log.append({"kind": "text", "detail": f"🧠 {first_line}"})
# Assistant text (visible reasoning / commentary)
# Process BEFORE tool calls so 💬 appears before 💻/✏️
# Only show 💬 when tools have been used (intermediate thinking).
# For pure text responses, skip — the final formatted message
# will show the same text.
if update_obj.type == "assistant" and update_obj.content:
text = update_obj.content.strip()
if text and "[ThinkingBlock(" in text:
text = ""
if text and verbose_level >= 1 and has_used_tools[0]:
first_line = text.split("\n", 1)[0].strip()[:200]
if first_line:
await _send_tool_msg(f"💬 {first_line}")
tool_log.append({"kind": "text", "detail": first_line})
# Reset draft so it only shows NEW text going forward
if draft_streamer:
draft_streamer.reset_text()
# Tool calls — send after assistant text so 💬 appears first
if update_obj.tool_calls and verbose_level >= 1:
for tc in update_obj.tool_calls:
name = tc.get("name", "unknown")
tool_input = tc.get("input", {})
icon = _tool_icon(name)
detail = _format_tool_detail(name, tool_input)
if verbose_level >= 3 and name == "Bash":
# Level 3: show full command
cmd = tool_input.get("command", "")[:400]
msg_text = f"{icon} {cmd}"
elif detail:
msg_text = f"{icon} {name}: {detail}"
else:
msg_text = f"{icon} {name}"
msg_id = await _send_tool_msg(msg_text)
last_tool_msg_id[0] = msg_id
# Also log for reference
tool_log.append({"kind": "tool", "name": name, "detail": detail})
# Tool results — edit the last tool message to append result
if verbose_level >= 3 and update_obj.type == "tool_result":
result_text = _clean_result(str(getattr(update_obj, "content", "") or ""))
if result_text and last_tool_msg_id[0]:
# Read current message and append result
tool_log.append({"kind": "result", "detail": result_text})
# Stream response text to user via draft (live typing preview).
# The draft is temporary (vanishes when next real message arrives)
# but the persistent 💬 and final messages capture everything.
if draft_streamer and update_obj.content:
if update_obj.type == "stream_delta":
await draft_streamer.append_text(update_obj.content)
# Throttle progress message edits to avoid Telegram rate limits.
# Update "Working..." with elapsed time counter.
if verbose_level >= 1:
now = time.time()
if (now - last_edit_time[0]) >= 3.0:
last_edit_time[0] = now
elapsed = int(now - start_time)
new_text = f"⏳ Working... ({elapsed}s)"
try:
await progress_msg.edit_text(new_text)
except Exception:
pass
return _on_stream
async def _send_formatted_message(
self,
update: Update,
text: str,
parse_mode: str = "HTML",
reply_to_message_id: Optional[int] = None,
) -> None:
"""Send a formatted message with HTML fallback to plain text.
If Telegram rejects the HTML, strips tags and retries as plain text.
"""
try:
await update.message.reply_text(
text,
parse_mode=parse_mode,
reply_markup=None,
reply_to_message_id=reply_to_message_id,
)
except Exception as e:
logger.warning(
"HTML send failed, falling back to plain text",
error=str(e),
html_preview=text[:200],
)
# Strip HTML tags for plain text fallback
plain = re.sub(r"<[^>]+>", "", text)
# Also unescape HTML entities
plain = plain.replace("&", "&").replace("<", "<").replace(">", ">")
try:
await update.message.reply_text(
plain,
reply_markup=None,
reply_to_message_id=reply_to_message_id,
)
except Exception as plain_err:
await update.message.reply_text(
f"Failed to deliver response "
f"(error: {str(plain_err)[:150]}). Please try again.",
reply_to_message_id=reply_to_message_id,
)
async def _send_images(
self,
update: Update,
images: List[ImageAttachment],
reply_to_message_id: Optional[int] = None,
caption: Optional[str] = None,
caption_parse_mode: Optional[str] = None,
) -> bool:
"""Send extracted images as a media group (album) or documents.
If *caption* is provided and fits (≤1024 chars), it is attached to the
photo / first album item so text + images appear as one message.
Returns True if the caption was successfully embedded in the photo message.
"""
photos: List[ImageAttachment] = []
documents: List[ImageAttachment] = []
for img in images:
if should_send_as_photo(img.path):
photos.append(img)
else:
documents.append(img)
# Telegram caption limit
use_caption = bool(
caption and len(caption) <= 1024 and photos and not documents
)
caption_sent = False
# Send raster photos as a single album (Telegram groups 2-10 items)
if photos:
try: