-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent42.py
More file actions
1706 lines (1507 loc) · 69.7 KB
/
agent42.py
File metadata and controls
1706 lines (1507 loc) · 69.7 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
"""
agent42.py - The answer to life, the universe, and all your tasks.
Multi-agent orchestrator platform. Free models handle the iterative work;
premium APIs or human review gate the final output.
Now with:
- Channel gateway (Discord, Slack, Telegram, Email) — Phase 2
- Skills framework (SKILL.md dynamic loading) — Phase 3
- Tool ecosystem (MCP, web search, cron, subagents) — Phase 4
- 8 LLM providers with 20+ models — Phase 5
- Persistent memory system — Phase 6
Usage:
python agent42.py # Start with defaults
python agent42.py --port 8080 # Custom dashboard port
python agent42.py --repo /path/to # Specify repo path
python agent42.py --no-dashboard # Headless mode (terminal only)
python agent42.py --max-agents 2 # Limit concurrent agents
Dashboard: http://localhost:8000 (default)
"""
import argparse
import asyncio
import atexit
import json
import logging
import os
import signal
import sys
from pathlib import Path
import uvicorn
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env", override=True)
from agents.agent import Agent
from agents.extension_loader import ExtensionLoader
from agents.learner import Learner
from agents.model_router import ModelRouter
from agents.profile_loader import ProfileLoader
from channels.base import InboundMessage, OutboundMessage
from channels.manager import ChannelManager
from core.app_manager import AppManager
from core.approval_gate import ApprovalGate
from core.capacity import compute_effective_capacity
from core.chat_session_manager import ChatSessionManager
from core.command_filter import DEFAULT_ALLOWLIST, CommandFilter
from core.config import settings
from core.device_auth import DeviceStore
from core.github_accounts import GitHubAccountStore
from core.heartbeat import HeartbeatService
from core.intent_classifier import IntentClassifier, PendingClarification, ScopeInfo
from core.key_store import KeyStore
from core.project_manager import ProjectManager
from core.rate_limiter import ToolLimit, ToolRateLimiter
from core.repo_manager import RepositoryManager
from core.sandbox import WorkspaceSandbox
from core.security_scanner import ScheduledSecurityScanner
from core.task_queue import Task, TaskQueue, TaskStatus, TaskType, infer_task_type
from core.worktree_manager import WorktreeManager
from dashboard.auth import init_device_store
from dashboard.server import create_app
from dashboard.websocket_manager import WebSocketManager
from memory.consolidation import ConsolidationPipeline
from memory.qdrant_store import QdrantConfig, QdrantStore
from memory.redis_session import RedisConfig, RedisSessionBackend
from memory.session import SessionManager
from memory.store import MemoryStore
from skills.loader import SkillLoader
from tools.app_test_tool import AppTestTool
from tools.app_tool import AppTool
from tools.behaviour_tool import BehaviourTool
from tools.browser_tool import BrowserTool
from tools.code_intel import CodeIntelTool
from tools.content_analyzer import ContentAnalyzerTool
from tools.context import ToolContext
from tools.cron import CronScheduler, CronTool
from tools.data_tool import DataTool
from tools.dependency_audit import DependencyAuditTool
from tools.diff_tool import DiffTool
from tools.docker_tool import DockerTool
from tools.file_watcher import FileWatcherTool
from tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool
from tools.git_tool import GitTool
from tools.grep_tool import GrepTool
from tools.http_client import HttpClientTool
from tools.image_gen import ImageGenTool
from tools.knowledge_tool import KnowledgeTool
from tools.linter_tool import LinterTool
from tools.mcp_client import MCPManager
from tools.memory_tool import MemoryTool
from tools.notify_tool import NotifyUserTool
from tools.outline_tool import OutlineTool
from tools.persona_tool import PersonaTool
from tools.plugin_loader import PluginLoader
from tools.pr_generator import PRGeneratorTool
from tools.python_exec import PythonExecTool
from tools.registry import ToolRegistry
from tools.repo_map import RepoMapTool
from tools.scoring_tool import ScoringTool
from tools.security_analyzer import SecurityAnalyzerTool
from tools.shell import ShellTool
from tools.ssh_tool import SSHTool
from tools.subagent import SubagentTool
from tools.summarizer_tool import SummarizerTool
from tools.team_tool import TeamTool
from tools.template_tool import TemplateTool
from tools.test_runner import TestRunnerTool
from tools.tunnel_tool import TunnelTool
from tools.video_gen import VideoGenTool
from tools.vision_tool import VisionTool
from tools.web_search import WebFetchTool, WebSearchTool
from tools.workflow_tool import WorkflowTool
# -- Logging -------------------------------------------------------------------
LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
_log_handlers: list[logging.Handler] = [logging.StreamHandler(sys.stdout)]
try:
_log_handlers.append(logging.FileHandler("agent42.log"))
except PermissionError:
print(
"WARNING: Cannot write to agent42.log (permission denied) — logging to stdout only.",
file=sys.stderr,
)
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, handlers=_log_handlers)
logger = logging.getLogger("agent42")
# Ensure exit is always logged even if the finally block or signal handling is bypassed
atexit.register(lambda: print("Agent42 process exiting (atexit)", flush=True))
# -- Custom persona loader ----------------------------------------------------
_PERSONA_FILE = Path(__file__).parent / "data" / "agent42_persona.json"
def _load_custom_persona() -> str:
"""Load the custom chat persona prompt from disk.
Returns the saved prompt string, or "" if no custom persona is set.
"""
if _PERSONA_FILE.exists():
try:
data = json.loads(_PERSONA_FILE.read_text())
return data.get("prompt", "")
except Exception:
pass
return ""
class Agent42:
"""Core orchestrator — manages tasks, agents, channels, tools, and dashboard."""
def __init__(
self,
repo_path: str | None = None,
dashboard_port: int = 8000,
headless: bool = False,
max_agents: int | None = None,
):
# Data directory: always the agent42 install dir (for memory, sessions, etc.)
self.data_dir = Path(__file__).parent.resolve()
# Repo path: optional, can be configured later via dashboard
self.repo_path = Path(repo_path).resolve() if repo_path else self.data_dir
self.has_repo = repo_path is not None and (Path(repo_path).resolve() / ".git").exists()
self.dashboard_port = dashboard_port
self.headless = headless
self.max_agents = max_agents or settings.max_concurrent_agents
# Core infrastructure — optional Redis-backed queue
queue_backend = None
if settings.redis_url:
from core.queue_backend import RedisQueueBackend
queue_backend = RedisQueueBackend(
redis_url=settings.redis_url,
redis_password=settings.redis_password,
fallback_json_path=settings.tasks_json_path,
)
self.task_queue = TaskQueue(
tasks_json_path=settings.tasks_json_path,
backend=queue_backend,
)
self.ws_manager = WebSocketManager()
self.worktree_manager = WorktreeManager(str(self.repo_path)) if self.has_repo else None
# Multi-repository manager
self.repo_manager = RepositoryManager(
repos_json_path=settings.repos_json_path,
clone_dir=settings.repos_clone_dir,
github_token=settings.github_token,
)
self._active_count = 0
self._active_lock = asyncio.Lock()
# Per-task intervention queues for mid-task user feedback (Agent Zero-inspired)
self._intervention_queues: dict[str, asyncio.Queue] = {}
self.approval_gate = ApprovalGate(
self.task_queue,
log_path=settings.approval_log_path,
)
self._shutdown_event = asyncio.Event()
self._uvicorn_server: uvicorn.Server | None = None
# Phase 1: Security
self.sandbox = WorkspaceSandbox(self.repo_path, enabled=settings.sandbox_enabled)
# Command filter: strict allowlist mode or default deny-list
allowlist = None
if settings.command_filter_mode == "allowlist":
if settings.command_filter_allowlist:
allowlist = [
p.strip() for p in settings.command_filter_allowlist.split(",") if p.strip()
]
else:
allowlist = list(DEFAULT_ALLOWLIST)
self.command_filter = CommandFilter(allowlist=allowlist)
# Phase 2: Channels
self.channel_manager = ChannelManager()
# Phase 3: Skills
skill_dirs = [
Path(__file__).parent / "skills" / "builtins",
self.repo_path / "skills",
]
for extra in settings.get_skills_dirs():
skill_dirs.append(Path(extra))
self.skill_loader = SkillLoader(skill_dirs)
self.skill_loader.load_all()
# Agent profiles (Agent Zero-inspired) — configurable agent personas
profile_dirs = []
if settings.agent_profiles_dir:
p = Path(settings.agent_profiles_dir)
if not p.is_absolute():
p = self.data_dir / p
profile_dirs.append(p)
self.profile_loader = ProfileLoader(extra_dirs=profile_dirs if profile_dirs else None)
self.profile_loader.load_all()
# Agent execution extensions (Agent Zero-inspired) — lifecycle hook plugins
ext_dir = None
if settings.extensions_dir:
ext_dir = Path(settings.extensions_dir)
if not ext_dir.is_absolute():
ext_dir = self.data_dir / ext_dir
self.extension_loader = ExtensionLoader(extensions_dir=ext_dir)
# Phase 4: Tools (with optional rate limiting)
rate_limiter = None
if settings.tool_rate_limiting_enabled:
rate_limiter = ToolRateLimiter()
if settings.tool_rate_limit_overrides:
try:
overrides_raw = json.loads(settings.tool_rate_limit_overrides)
overrides = {name: ToolLimit(**spec) for name, spec in overrides_raw.items()}
rate_limiter.update_limits(overrides)
except (json.JSONDecodeError, TypeError) as e:
logger.warning(f"Invalid TOOL_RATE_LIMIT_OVERRIDES: {e}")
self.tool_registry = ToolRegistry(rate_limiter=rate_limiter)
self.mcp_manager = MCPManager()
self.cron_scheduler = CronScheduler(settings.cron_jobs_path)
# Apps platform
self.app_manager = (
AppManager(
apps_dir=settings.apps_dir,
port_range_start=settings.apps_port_range_start,
port_range_end=settings.apps_port_range_end,
max_running=settings.apps_max_running,
auto_restart=settings.apps_auto_restart,
dashboard_port=dashboard_port,
git_enabled_default=settings.apps_git_enabled_default,
github_token=settings.apps_github_token,
default_mode=settings.apps_default_mode,
require_auth_default=settings.apps_require_auth_default,
)
if settings.apps_enabled
else None
)
# Chat sessions and projects
self.chat_session_manager = ChatSessionManager(self.data_dir / settings.chat_sessions_dir)
self.project_manager = ProjectManager(
self.data_dir / settings.projects_dir,
self.task_queue,
)
# Project state manager for session recovery (GSD-inspired)
from core.state_manager import StateManager
self.state_manager = StateManager(self.data_dir / settings.projects_dir)
# Phase 4b: Custom tool plugins (auto-discovery from CUSTOM_TOOLS_DIR)
if settings.custom_tools_dir:
tool_context = ToolContext(
sandbox=self.sandbox,
command_filter=self.command_filter,
task_queue=self.task_queue,
workspace=str(self.repo_path),
tool_registry=self.tool_registry,
)
custom_dir = Path(settings.custom_tools_dir)
if not custom_dir.is_absolute():
custom_dir = self.data_dir / custom_dir
self._custom_tools = PluginLoader.load_all(custom_dir, tool_context, self.tool_registry)
else:
self._custom_tools = []
# Phase 6: Memory (with optional Qdrant + Redis backends)
self._qdrant_store = None
self._redis_backend = None
if settings.qdrant_enabled:
self._qdrant_store = QdrantStore(
QdrantConfig(
url=settings.qdrant_url,
api_key=settings.qdrant_api_key,
collection_prefix=settings.qdrant_collection_prefix,
local_path=settings.qdrant_local_path,
)
)
if settings.redis_url:
self._redis_backend = RedisSessionBackend(
RedisConfig(
url=settings.redis_url,
password=settings.redis_password,
session_ttl_days=settings.session_ttl_days,
embedding_cache_ttl_hours=settings.embedding_cache_ttl_hours,
)
)
self.memory_store = MemoryStore(
self.data_dir / settings.memory_dir,
qdrant_store=self._qdrant_store,
redis_backend=self._redis_backend,
)
# Register tools now that memory_store is available
self._register_tools()
consolidation = ConsolidationPipeline(
model_router=ModelRouter(),
embedding_store=self.memory_store.embeddings,
qdrant_store=self._qdrant_store,
)
self.session_manager = SessionManager(
self.data_dir / settings.sessions_dir,
redis_backend=self._redis_backend,
consolidation_pipeline=consolidation,
)
# Phase 10: Device gateway authentication
self.device_store = DeviceStore(self.data_dir / settings.devices_file)
init_device_store(self.device_store)
# Admin-configured API keys (override .env values)
self.key_store = KeyStore(self.data_dir / ".agent42" / "settings.json")
self.key_store.inject_into_environ()
# Multi-account GitHub credential store
self.github_account_store = GitHubAccountStore(
self.data_dir / ".agent42" / "github_accounts.json"
)
# Dynamic model routing components (must be before Learner for injection)
from agents.model_catalog import ModelCatalog
from agents.model_evaluator import ModelEvaluator
from agents.model_researcher import ModelResearcher
data_dir = self.data_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
self.model_catalog = ModelCatalog(
cache_path=data_dir / "model_catalog.json",
refresh_hours=settings.model_catalog_refresh_hours,
balance_check_hours=settings.openrouter_balance_check_hours,
)
self.model_evaluator = ModelEvaluator(
performance_path=data_dir / "model_performance.json",
routing_path=self.data_dir / settings.model_routing_file,
research_path=data_dir / "model_research.json",
trial_percentage=settings.model_trial_percentage,
min_trials=settings.model_min_trials,
)
self.model_researcher = (
ModelResearcher(
research_path=data_dir / "model_research.json",
interval_hours=settings.model_research_interval_hours,
)
if settings.model_research_enabled
else None
)
# Self-learning (with model evaluator for outcome tracking)
self.workspace_skills_dir = self.data_dir / "skills" / "workspace"
self.learner = Learner(
router=ModelRouter(evaluator=self.model_evaluator, catalog=self.model_catalog),
memory_store=self.memory_store,
skills_dir=self.workspace_skills_dir,
model_evaluator=self.model_evaluator,
)
# Phase 7: Heartbeat monitoring
self.heartbeat = HeartbeatService(
on_stall=self._on_agent_stall,
on_heartbeat=self._on_heartbeat,
configured_max_agents=self.max_agents,
task_queue=self.task_queue,
tool_registry=self.tool_registry,
skill_loader=self.skill_loader,
)
# Scheduled security scanning
self.security_scanner = ScheduledSecurityScanner(
workspace_path=str(self.repo_path) if self.has_repo else str(self.data_dir),
interval_seconds=settings.get_security_scan_interval_seconds(),
min_severity=settings.security_scan_min_severity,
github_issues_enabled=settings.security_scan_github_issues,
memory_store=self.memory_store,
)
# Phase 9: Context-aware intent classification
self.intent_classifier = IntentClassifier(router=ModelRouter())
self._pending_clarifications: dict[str, PendingClarification] = {}
self._pending_scope_clarifications: dict[str, dict] = {}
# Wire up callbacks
self.task_queue.on_update(self._on_task_update)
def _register_tools(self):
"""Register all built-in tools."""
workspace = str(self.repo_path)
# Core tools
self.tool_registry.register(ShellTool(self.sandbox, self.command_filter))
self.tool_registry.register(ReadFileTool(self.sandbox))
self.tool_registry.register(WriteFileTool(self.sandbox))
self.tool_registry.register(EditFileTool(self.sandbox))
self.tool_registry.register(ListDirTool(self.sandbox))
self.tool_registry.register(WebSearchTool())
self.tool_registry.register(WebFetchTool())
self.tool_registry.register(CronTool(self.cron_scheduler))
self.tool_registry.register(SubagentTool(self.task_queue))
# Agent Zero-inspired tools
self.tool_registry.register(BehaviourTool(memory_dir=self.data_dir / settings.memory_dir))
self.tool_registry.register(MemoryTool(memory_store=self.memory_store))
self.tool_registry.register(NotifyUserTool(ws_manager=self.ws_manager))
self.tool_registry.register(MemoryTool(memory_store=self.memory_store))
# Development tools
self.tool_registry.register(GitTool(workspace))
self.tool_registry.register(GrepTool(workspace))
self.tool_registry.register(DiffTool(workspace))
self.tool_registry.register(TestRunnerTool(workspace))
self.tool_registry.register(LinterTool(workspace))
self.tool_registry.register(HttpClientTool())
# Advanced tools (from competitive analysis)
self.tool_registry.register(BrowserTool(workspace))
self.tool_registry.register(CodeIntelTool(workspace))
self.tool_registry.register(DependencyAuditTool(workspace))
self.tool_registry.register(DockerTool(workspace))
self.tool_registry.register(PythonExecTool(workspace))
self.tool_registry.register(RepoMapTool(workspace))
self.tool_registry.register(PRGeneratorTool(workspace))
self.tool_registry.register(SecurityAnalyzerTool(workspace))
self.tool_registry.register(WorkflowTool(workspace, self.tool_registry))
self.tool_registry.register(SummarizerTool(workspace))
self.tool_registry.register(FileWatcherTool(workspace))
# General-purpose tools (non-coding workflows)
self.tool_registry.register(TeamTool(self.task_queue))
self.tool_registry.register(ContentAnalyzerTool())
self.tool_registry.register(DataTool())
self.tool_registry.register(TemplateTool())
self.tool_registry.register(OutlineTool())
self.tool_registry.register(ScoringTool())
self.tool_registry.register(PersonaTool())
# Media generation tools (Phase 9)
router = ModelRouter()
self.tool_registry.register(ImageGenTool(router=router))
self.tool_registry.register(VideoGenTool(router=router))
# SSH remote shell (disabled by default — requires SSH_ENABLED=true)
if settings.ssh_enabled:
self.tool_registry.register(
SSHTool(self.sandbox, self.command_filter, self.approval_gate)
)
# Tunnel manager (disabled by default — requires TUNNEL_ENABLED=true)
if settings.tunnel_enabled:
self.tool_registry.register(TunnelTool(self.approval_gate))
# Knowledge base / RAG
embedding_store = getattr(self, "embedding_store", None)
self.tool_registry.register(KnowledgeTool(self.sandbox, embedding_store))
# Vision / image analysis
self.tool_registry.register(VisionTool(self.sandbox))
# Apps platform (enabled by default)
if self.app_manager:
self.tool_registry.register(AppTool(self.app_manager))
self.tool_registry.register(AppTestTool(self.app_manager, self.sandbox))
# Project interview tool (for structured project discovery)
if settings.project_interview_enabled:
from tools.project_interview import ProjectInterviewTool
self.tool_registry.register(
ProjectInterviewTool(
workspace_path=workspace,
router=router,
outputs_dir=settings.outputs_dir,
task_queue=self.task_queue,
)
)
async def _setup_channels(self):
"""Configure and register enabled channels based on settings."""
# Discord
if settings.discord_bot_token:
from channels.discord_channel import DiscordChannel
self.channel_manager.register(
DiscordChannel(
{
"bot_token": settings.discord_bot_token,
"guild_ids": settings.get_discord_guild_ids(),
}
)
)
logger.info("Discord channel configured")
# Slack
if settings.slack_bot_token and settings.slack_app_token:
from channels.slack_channel import SlackChannel
self.channel_manager.register(
SlackChannel(
{
"bot_token": settings.slack_bot_token,
"app_token": settings.slack_app_token,
}
)
)
logger.info("Slack channel configured")
# Telegram
if settings.telegram_bot_token:
from channels.telegram_channel import TelegramChannel
self.channel_manager.register(
TelegramChannel(
{
"bot_token": settings.telegram_bot_token,
}
)
)
logger.info("Telegram channel configured")
# Email
if settings.email_imap_host:
from channels.email_channel import EmailChannel
self.channel_manager.register(
EmailChannel(
{
"imap_host": settings.email_imap_host,
"imap_port": settings.email_imap_port,
"imap_user": settings.email_imap_user,
"imap_password": settings.email_imap_password,
"smtp_host": settings.email_smtp_host,
"smtp_port": settings.email_smtp_port,
"smtp_user": settings.email_smtp_user,
"smtp_password": settings.email_smtp_password,
}
)
)
logger.info("Email channel configured")
# Set up message handler
self.channel_manager.on_message(self._handle_channel_message)
async def _setup_mcp(self):
"""Connect to configured MCP servers and register their tools."""
mcp_servers = settings.get_mcp_servers()
for name, config in mcp_servers.items():
tools = await self.mcp_manager.connect_server(name, config)
for tool in tools:
self.tool_registry.register(tool)
async def _handle_channel_message(self, message: InboundMessage) -> OutboundMessage | None:
"""Handle incoming messages from channels with context-aware classification.
Uses LLM-based intent classification with conversation history.
If the intent is ambiguous, sends a clarification question back to the
channel instead of creating a task immediately.
When scope detection is enabled and an active scope exists, detects
whether the new message continues the current scope or represents a
topic change that warrants a new branch/task.
"""
logger.info(f"[{message.channel_type}] {message.sender_name}: {message.content[:100]}")
# Store in session history
from memory.session import SessionMessage
await self.session_manager.add_message(
message.channel_type,
message.channel_id,
SessionMessage(
role="user",
content=message.content,
channel_type=message.channel_type,
sender_id=message.sender_id,
sender_name=message.sender_name,
),
)
# Check if this is a response to a pending clarification
clarification_key = f"{message.channel_type}:{message.channel_id}:{message.sender_id}"
pending = self._pending_clarifications.get(clarification_key)
if pending:
# User responded to clarification — use their answer + original message
del self._pending_clarifications[clarification_key]
combined = f"{pending.original_message}\n\nUser clarification: {message.content}"
return await self._create_task_from_message(combined, message, force_type=None)
# Check if this is a response to a pending scope clarification
scope_clarification_key = (
f"scope:{message.channel_type}:{message.channel_id}:{message.sender_id}"
)
pending_scope = self._pending_scope_clarifications.get(scope_clarification_key)
if pending_scope:
del self._pending_scope_clarifications[scope_clarification_key]
user_answer = message.content.strip().lower()
if user_answer in ("yes", "y", "new", "new topic", "different"):
# User confirmed scope change — create new scope and task
return await self._handle_scope_change(
pending_scope["original_message"],
message,
pending_scope["classification"],
pending_scope["scope_analysis"],
)
else:
# User says it's the same scope — continue with existing scope
return await self._create_task_from_message(
pending_scope["original_message"],
message,
force_type=pending_scope["classification"].task_type,
classification=pending_scope["classification"],
parent_task_id=pending_scope["active_scope"].task_id,
)
# Get conversation history for context-aware classification
history = self.session_manager.get_history(
message.channel_type, message.channel_id, max_messages=10
)
history_dicts = [{"role": m.role, "content": m.content} for m in history] if history else []
# Classify intent with LLM + context
classification = await self.intent_classifier.classify(
message.content, conversation_history=history_dicts
)
logger.info(
f"Intent classification: {classification.task_type.value} "
f"(confidence={classification.confidence:.2f}, "
f"llm={classification.used_llm}, "
f"conversational={classification.is_conversational}, "
f"clarify={classification.needs_clarification})"
)
# Conversational mode: respond directly without creating a task
if classification.is_conversational and settings.conversational_enabled:
try:
response = await self._direct_response(message, history_dicts)
if response:
return response
except Exception as e:
logger.warning(f"Direct response failed, falling back to task: {e}")
# Fall through to task creation
# If ambiguous, ask for clarification
if classification.needs_clarification and classification.clarification_question:
self._pending_clarifications[clarification_key] = PendingClarification(
original_message=message.content,
channel_type=message.channel_type,
channel_id=message.channel_id,
sender_id=message.sender_id,
sender_name=message.sender_name,
clarification_question=classification.clarification_question,
partial_result=classification,
metadata=message.metadata,
)
return OutboundMessage(
channel_type=message.channel_type,
channel_id=message.channel_id,
content=classification.clarification_question,
metadata=message.metadata,
)
# Scope change detection: check if this message is a new topic
if settings.scope_detection_enabled:
active_scope = self.session_manager.get_active_scope(
message.channel_type, message.channel_id
)
if active_scope and self._should_check_scope(
active_scope, message.channel_type, message.channel_id
):
scope_analysis = await self.intent_classifier.detect_scope_change(
message.content,
active_scope,
conversation_history=history_dicts,
confidence_threshold=settings.scope_detection_confidence_threshold,
)
logger.info(
f"Scope analysis: continuation={scope_analysis.is_continuation}, "
f"confidence={scope_analysis.confidence:.2f}, "
f"uncertain={scope_analysis.uncertain}"
)
if scope_analysis.uncertain:
# Not sure — ask the user
self._pending_scope_clarifications[scope_clarification_key] = {
"original_message": message.content,
"classification": classification,
"scope_analysis": scope_analysis,
"active_scope": active_scope,
}
return OutboundMessage(
channel_type=message.channel_type,
channel_id=message.channel_id,
content=(
f"I noticed this might be a different topic from what we've "
f"been working on ({active_scope.summary}). Should I create "
f"a new branch/task for this, or is this related to the "
f"current work? (yes = new topic / no = same topic)"
),
metadata=message.metadata,
)
if not scope_analysis.is_continuation:
# Scope change detected — new branch/task
return await self._handle_scope_change(
message.content,
message,
classification,
scope_analysis,
)
# Continuation — route to active task instead of creating a new one
active_scope.message_count += 1
await self.session_manager.set_active_scope(
message.channel_type, message.channel_id, active_scope
)
_existing = self.task_queue.find_active_task(
origin_channel=message.channel_type,
origin_channel_id=message.channel_id,
)
if _existing:
await self.task_queue.route_message_to_task(
_existing,
message.content,
message.sender_name,
self._intervention_queues,
)
return OutboundMessage(
channel_type=message.channel_type,
channel_id=message.channel_id,
content=f"Message added to active task {_existing.id}.",
metadata=message.metadata,
)
# Fallback: no active task found despite scope — create child task
return await self._create_task_from_message(
message.content,
message,
force_type=classification.task_type,
classification=classification,
parent_task_id=active_scope.task_id,
)
# No active scope or scope detection disabled — check for active task first
_existing = self.task_queue.find_active_task(
origin_channel=message.channel_type,
origin_channel_id=message.channel_id,
)
if _existing:
await self.task_queue.route_message_to_task(
_existing,
message.content,
message.sender_name,
self._intervention_queues,
)
return OutboundMessage(
channel_type=message.channel_type,
channel_id=message.channel_id,
content=f"Message added to active task {_existing.id}.",
metadata=message.metadata,
)
# No active task — create new task and set scope
return await self._create_task_from_message(
message.content,
message,
force_type=classification.task_type,
classification=classification,
)
def _should_check_scope(
self,
active_scope: ScopeInfo,
channel_type: str,
channel_id: str,
) -> bool:
"""Determine if scope checking is warranted.
Returns False (and auto-clears the scope) when the active scope's
task has already completed, failed, or been archived.
"""
task = self.task_queue.get(active_scope.task_id)
if task and task.status in (TaskStatus.DONE, TaskStatus.FAILED, TaskStatus.ARCHIVED):
self.session_manager.clear_active_scope(channel_type, channel_id)
logger.info(
f"Auto-cleared stale scope {active_scope.scope_id} "
f"(task {active_scope.task_id} is {task.status.value})"
)
return False
return True
async def _handle_scope_change(
self,
description: str,
message: InboundMessage,
classification,
scope_analysis,
) -> OutboundMessage:
"""Handle a detected scope change by creating a new task and updating scope.
Notifies the user that a scope change was detected and a new branch
will be created for the new work.
"""
old_scope = self.session_manager.get_active_scope(message.channel_type, message.channel_id)
old_summary = old_scope.summary if old_scope else "previous work"
# Create new task (no parent link — this is a fresh scope)
result = await self._create_task_from_message(
description,
message,
force_type=classification.task_type,
classification=classification,
)
# Prepend scope change notice to the standard task-created message
scope_notice = (
f'Scope change detected — switching from "{old_summary}" to a new topic. '
f"A new branch will be created for this work.\n\n"
)
return OutboundMessage(
channel_type=result.channel_type,
channel_id=result.channel_id,
content=scope_notice + result.content,
metadata=result.metadata,
)
async def _direct_response(
self,
message: InboundMessage,
history_dicts: list[dict],
) -> OutboundMessage | None:
"""Respond directly to conversational messages without creating a task.
Uses the general assistant prompt with a fast free model for simple
messages like greetings, quick questions, and status checks.
Falls back to None on failure so the caller can create a task instead.
"""
from agents.agent import GENERAL_ASSISTANT_PROMPT
router = ModelRouter()
model = settings.conversational_model
if not model:
routing = router.get_routing(TaskType.EMAIL)
model = routing["primary"]
_custom = _load_custom_persona()
system_content = _custom or GENERAL_ASSISTANT_PROMPT
# Load persistent memory context so conversational responses
# can reference past interactions stored in MEMORY.md / HISTORY.md
from memory.store import build_conversational_memory_context
memory_context = await build_conversational_memory_context(
self.memory_store, message.content
)
if memory_context and memory_context.strip():
system_content += "\n\n" + memory_context
messages = [{"role": "system", "content": system_content}]
# Add recent conversation history for context
for h in history_dicts[-10:]:
messages.append({"role": h.get("role", "user"), "content": h.get("content", "")})
messages.append({"role": "user", "content": message.content})
text, _ = await asyncio.wait_for(
router.complete(model, messages),
timeout=30.0,
)
if not text:
return None
# Store assistant response in session history
from memory.session import SessionMessage
await self.session_manager.add_message(
message.channel_type,
message.channel_id,
SessionMessage(
role="assistant",
content=text,
channel_type=message.channel_type,
),
)
logger.info("Direct conversational response (%d chars) via %s", len(text), model)
return OutboundMessage(
channel_type=message.channel_type,
channel_id=message.channel_id,
content=text,
metadata=message.metadata,
)
async def _create_task_from_message(
self,
description: str,
message: InboundMessage,
force_type: TaskType | None = None,
classification=None,
parent_task_id: str = "",
) -> OutboundMessage:
"""Create a task from a channel message with the given (or inferred) type.
If the classification recommends a team, injects a resource allocation
directive into the task description so the executing agent knows to use
the team tool.
When ``parent_task_id`` is provided the new task is linked to the
parent (scope continuation). When omitted (new root task), the
active scope for the session is established automatically.
"""
task_type = force_type or infer_task_type(description)
# Smart resource allocation: inject team directive for complex tasks
task_description = description
team_name = ""
if (
classification
and classification.recommended_mode == "team"
and classification.recommended_team
):
team_name = classification.recommended_team
task_description = (
f"{description}\n\n"
f"---\n"
f"RESOURCE ALLOCATION: This task has been assessed as requiring "
f"team collaboration.\n"
f"Use the 'team' tool with action='run', name='{team_name}', "
f"and the task description above to execute with the {team_name}.\n"
f"The team's Manager will coordinate the roles automatically."
)
task = Task(
title=f"[{message.channel_type}] {description[:60]}",
description=task_description,
task_type=task_type,
origin_channel=message.channel_type,
origin_channel_id=message.channel_id,
origin_metadata=message.metadata,
parent_task_id=parent_task_id,
)
await self.task_queue.add(task)
# Set active scope for new root tasks (no parent = new scope)
if not parent_task_id and settings.scope_detection_enabled:
scope = ScopeInfo(
scope_id=task.id,