-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmessenger_handler.rs
More file actions
1518 lines (1351 loc) · 51.9 KB
/
messenger_handler.rs
File metadata and controls
1518 lines (1351 loc) · 51.9 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
//! Messenger integration for the gateway.
//!
//! This module provides the messenger polling loop that receives messages
//! from configured messengers (Telegram, Discord, Matrix, etc.) and routes
//! them through the model for processing with full tool loop support.
use crate::config::{Config, MessengerConfig};
use crate::messengers::{
GenericMessenger, MediaAttachment, Message, Messenger, MessengerManager, SendOptions,
};
use crate::tools;
use anyhow::{Context, Result};
use chat_system::config as chat_system_config;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, trace, warn};
use super::providers;
use super::secrets_handler;
use super::skills_handler;
use super::{
ChatMessage, MediaRef, ModelContext, ProviderRequest, SharedSkillManager, SharedVault,
ToolCallResult,
};
#[cfg(feature = "matrix")]
use crate::messengers::MatrixMessenger;
/// Shared messenger manager for the gateway.
pub type SharedMessengerManager = Arc<Mutex<MessengerManager>>;
/// Conversation history storage per chat.
/// Key: "messenger_type:chat_id" or "messenger_type:sender_id"
type ConversationStore = Arc<Mutex<HashMap<String, Vec<ChatMessage>>>>;
/// Maximum messages to keep in conversation history per chat.
const MAX_HISTORY_MESSAGES: usize = 50;
/// Maximum tool loop rounds.
const MAX_TOOL_ROUNDS: usize = 25;
/// Maximum image size to download (10 MB).
const MAX_IMAGE_SIZE: usize = 10 * 1024 * 1024;
/// Supported image MIME types for vision models.
const SUPPORTED_IMAGE_TYPES: &[&str] = &["image/jpeg", "image/png", "image/gif", "image/webp"];
/// Create a messenger manager from config.
pub async fn create_messenger_manager(config: &Config) -> Result<MessengerManager> {
let mut manager = MessengerManager::new();
for messenger_config in &config.messengers {
if !messenger_config.enabled {
continue;
}
match create_messenger(messenger_config).await {
Ok(messenger) => {
info!(
name = %messenger.name(),
messenger_type = %messenger.messenger_type(),
"Messenger initialized"
);
manager = manager.add_boxed(messenger);
}
Err(e) => {
error!(
messenger_type = %messenger_config.messenger_type,
error = %e,
"Failed to initialize messenger"
);
}
}
}
Ok(manager)
}
/// Create a single messenger from config.
async fn create_messenger(config: &MessengerConfig) -> Result<Box<dyn Messenger>> {
if let Some(generic_config) = generic_messenger_config(config)? {
let mut messenger: Box<dyn Messenger> = Box::new(GenericMessenger::new(generic_config));
messenger.initialize().await?;
return Ok(messenger);
}
let name = config.name.clone();
let mut messenger: Box<dyn Messenger> = match config.messenger_type.as_str() {
// matrix-cli type removed - use "matrix" type instead (chat-system 0.1.3)
"matrix-cli" => {
anyhow::bail!(
"matrix-cli messenger type is deprecated. Use 'matrix' type instead."
);
}
"irc" => build_irc_messenger(config, name)?,
"slack" => build_slack_messenger(config, name)?,
"google_chat" => build_google_chat_messenger(config, name)?,
"teams" => build_teams_messenger(config, name)?,
"imessage" => build_imessage_messenger(config, name)?,
#[cfg(feature = "matrix")]
"matrix" => build_matrix_messenger(config, name)?,
#[cfg(not(feature = "matrix"))]
"matrix" => {
anyhow::bail!("Matrix messenger not compiled in. Rebuild with --features matrix")
}
other => anyhow::bail!("Unknown messenger type: {}", other),
};
messenger.initialize().await?;
Ok(messenger)
}
fn generic_messenger_config(
config: &MessengerConfig,
) -> Result<Option<chat_system_config::MessengerConfig>> {
let name = config.name.clone();
let messenger = match config.messenger_type.as_str() {
"console" => Some(chat_system_config::MessengerConfig::Console(
chat_system_config::ConsoleConfig { name },
)),
"discord" => Some(chat_system_config::MessengerConfig::Discord(
chat_system_config::DiscordConfig {
name,
token: config.token.clone().context("Discord requires 'token'")?,
},
)),
"telegram" => Some(chat_system_config::MessengerConfig::Telegram(
chat_system_config::TelegramConfig {
name,
token: config.token.clone().context("Telegram requires 'token'")?,
},
)),
"webhook" => Some(chat_system_config::MessengerConfig::Webhook(
chat_system_config::WebhookConfig {
name,
url: config
.webhook_url
.clone()
.context("Webhook requires 'webhook_url'")?,
},
)),
"slack" if config.app_token.is_none() && config.default_channel.is_none() => Some(
chat_system_config::MessengerConfig::Slack(chat_system_config::SlackConfig {
name,
token: config.token.clone().context("Slack requires 'token'")?,
}),
),
"irc" if config.password.is_none() => Some(chat_system_config::MessengerConfig::Irc(
chat_system_config::IrcConfig {
name,
server: config.server.clone().context("IRC requires 'server'")?,
port: config.port.unwrap_or(6697),
nick: config
.nick
.clone()
.unwrap_or_else(|| "RustyClaw".to_string()),
channels: config.irc_channels.clone(),
tls: config.use_tls.unwrap_or(false),
},
)),
"google_chat"
if config.credentials_path.is_none()
&& (config.webhook_url.is_some()
|| (config.token.is_some() && config.spaces.len() == 1)) =>
{
Some(chat_system_config::MessengerConfig::GoogleChat(
chat_system_config::GoogleChatConfig {
name,
webhook_url: config.webhook_url.clone(),
token: config.token.clone(),
space_id: config.spaces.first().cloned(),
},
))
}
"teams" if config.app_id.is_none() && config.app_password.is_none() => Some(
chat_system_config::MessengerConfig::Teams(chat_system_config::TeamsConfig {
name,
webhook_url: Some(
config
.webhook_url
.clone()
.context("Teams requires 'webhook_url'")?,
),
token: None,
team_id: None,
channel_id: None,
}),
),
"imessage" if config.server.is_none() && config.password.is_none() => {
Some(chat_system_config::MessengerConfig::IMessage(
chat_system_config::IMessageConfig { name },
))
}
#[cfg(feature = "matrix")]
"matrix" if config.access_token.is_none() => Some(
chat_system_config::MessengerConfig::Matrix(chat_system_config::MatrixConfig {
name,
homeserver: config
.homeserver
.clone()
.context("Matrix requires 'homeserver'")?,
username: config
.user_id
.clone()
.context("Matrix requires 'user_id'")?,
password: config
.password
.clone()
.context("Matrix requires 'password'")?,
}),
),
#[cfg(feature = "signal-cli")]
"signal" | "signal-cli" => Some(chat_system_config::MessengerConfig::SignalCli(
chat_system_config::SignalCliConfig {
name,
phone_number: config.phone.clone().context("Signal requires 'phone'")?,
cli_path: "signal-cli".to_string(),
},
)),
#[cfg(feature = "whatsapp")]
"whatsapp" => {
let db_path = whatsapp_state_dir(&name)?
.join(format!("{name}.db"))
.to_string_lossy()
.into_owned();
Some(chat_system_config::MessengerConfig::WhatsApp(
chat_system_config::WhatsAppConfig { name, db_path },
))
}
_ => None,
};
Ok(messenger)
}
#[cfg(feature = "whatsapp")]
fn whatsapp_state_dir(name: &str) -> Result<std::path::PathBuf> {
Ok(dirs::data_dir()
.context("Failed to get data directory")?
.join("rustyclaw")
.join("whatsapp")
.join(name))
}
fn build_irc_messenger(config: &MessengerConfig, name: String) -> Result<Box<dyn Messenger>> {
let mut messenger = crate::messengers::IrcMessenger::new(
name,
config.server.clone().context("IRC requires 'server'")?,
config.port.unwrap_or(6697),
config
.nick
.clone()
.unwrap_or_else(|| "RustyClaw".to_string()),
);
if !config.irc_channels.is_empty() {
messenger = messenger.with_channels(config.irc_channels.clone());
}
if let Some(password) = config.password.clone() {
messenger = messenger.with_password(password);
}
if let Some(tls) = config.use_tls {
messenger = messenger.with_tls(tls);
}
Ok(Box::new(messenger))
}
fn build_slack_messenger(config: &MessengerConfig, name: String) -> Result<Box<dyn Messenger>> {
let mut messenger = crate::messengers::SlackMessenger::new(
name,
config.token.clone().context("Slack requires 'token'")?,
);
if let Some(app_token) = config.app_token.clone() {
messenger = messenger.with_app_token(app_token);
}
if let Some(channel) = config.default_channel.clone() {
messenger = messenger.with_default_channel(channel);
}
Ok(Box::new(messenger))
}
fn build_google_chat_messenger(
config: &MessengerConfig,
name: String,
) -> Result<Box<dyn Messenger>> {
if let Some(credentials_path) = config.credentials_path.clone() {
if config.spaces.is_empty() {
anyhow::bail!(
"Google Chat service account mode requires at least one entry in 'spaces'"
);
}
return Ok(Box::new(
crate::messengers::GoogleChatMessenger::with_credentials(
name,
credentials_path,
config.spaces.clone(),
),
));
}
if let (Some(token), Some(space_id)) = (config.token.clone(), config.spaces.first().cloned()) {
let mut messenger = crate::messengers::GoogleChatMessenger::new_api(name, token, space_id);
if config.spaces.len() > 1 {
messenger = messenger.with_spaces(config.spaces[1..].to_vec());
}
return Ok(Box::new(messenger));
}
anyhow::bail!(
"Google Chat requires 'webhook_url', 'credentials_path', or ('token' and one or more entries in 'spaces')"
)
}
fn build_teams_messenger(config: &MessengerConfig, name: String) -> Result<Box<dyn Messenger>> {
if let (Some(app_id), Some(app_password)) = (config.app_id.clone(), config.app_password.clone())
{
return Ok(Box::new(
crate::messengers::TeamsMessenger::with_bot_framework(name, app_id, app_password),
));
}
anyhow::bail!(
"Teams requires either 'app_id' + 'app_password' for Bot Framework mode, or 'webhook_url' for webhook mode"
)
}
fn build_imessage_messenger(config: &MessengerConfig, name: String) -> Result<Box<dyn Messenger>> {
if config.password.is_some() {
anyhow::bail!(
"BlueBubbles-backed iMessage is no longer supported; chat-system uses the local macOS Messages database"
);
}
let mut messenger = crate::messengers::IMessageMessenger::new(name);
if let Some(path) = config.server.clone() {
if path.contains("://") {
anyhow::bail!(
"BlueBubbles-backed iMessage is no longer supported; set 'server' to a local chat.db path or omit it"
);
}
messenger = messenger.with_chat_db_path(path);
}
Ok(Box::new(messenger))
}
#[cfg(feature = "matrix")]
fn build_matrix_messenger(config: &MessengerConfig, name: String) -> Result<Box<dyn Messenger>> {
let homeserver = config
.homeserver
.clone()
.context("Matrix requires 'homeserver'")?;
let user_id = config
.user_id
.clone()
.context("Matrix requires 'user_id'")?;
let mut messenger = if let Some(access_token) = config.access_token.clone() {
MatrixMessenger::with_access_token(
name.clone(),
homeserver,
user_id,
access_token,
None,
)
} else {
MatrixMessenger::new(
name.clone(),
homeserver,
user_id,
config
.password
.clone()
.context("Matrix requires 'password'")?,
)
};
// Set state directory for sync token persistence
if let Some(dirs) = directories::ProjectDirs::from("", "", "rustyclaw") {
let state_dir = dirs.data_dir().join("matrix").join(&name);
messenger = messenger.with_state_dir(state_dir);
}
// Set allowed chats if configured
if !config.allowed_chats.is_empty() {
messenger = messenger.with_allowed_chats(config.allowed_chats.clone());
}
// Set DM config if present
if let Some(ref dm) = config.dm {
use crate::messengers::MatrixDmConfig;
let dm_config = MatrixDmConfig {
enabled: dm.enabled,
policy: dm.policy.clone().unwrap_or_else(|| "allowlist".to_string()),
allow_from: dm.allow_from.clone(),
};
messenger = messenger.with_dm_config(dm_config);
}
Ok(Box::new(messenger))
}
fn get_messenger_by_type<'a>(
mgr: &'a MessengerManager,
messenger_type: &str,
) -> Option<&'a dyn Messenger> {
mgr.messengers()
.iter()
.find(|messenger| messenger.messenger_type() == messenger_type)
.map(|messenger| messenger.as_ref())
}
/// Run the messenger polling loop.
///
/// This polls all configured messengers for incoming messages and routes
/// them through the model for processing with full tool support.
///
/// When `messenger_max_concurrent` > 1, messages are processed concurrently.
/// The loop continues polling for new messages while processing tasks run.
pub async fn run_messenger_loop(
config: Config,
messenger_mgr: SharedMessengerManager,
model_ctx: Option<Arc<ModelContext>>,
vault: SharedVault,
skill_mgr: SharedSkillManager,
task_mgr: super::SharedTaskManager,
model_registry: super::SharedModelRegistry,
copilot_session: Option<Arc<super::CopilotSession>>,
cancel: CancellationToken,
) -> Result<()> {
eprintln!("DEBUG: run_messenger_loop() called");
// If no model context, we can't process messages
let model_ctx = match model_ctx {
Some(ctx) => ctx,
None => {
eprintln!("DEBUG: No model context, returning early");
warn!("No model context — messenger loop disabled");
return Ok(());
}
};
let poll_interval =
Duration::from_millis(config.messenger_poll_interval_ms.unwrap_or(2000).max(500) as u64);
// Concurrent processing setup
let max_concurrent = config.messenger_max_concurrent.unwrap_or(1);
let concurrent_mode = max_concurrent > 1;
let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
eprintln!(
"DEBUG: messenger_max_concurrent={}, concurrent_mode={}",
max_concurrent, concurrent_mode
);
if concurrent_mode {
info!(max_concurrent, "Concurrent message processing enabled");
}
// Per-chat conversation history
let conversations: ConversationStore = Arc::new(Mutex::new(HashMap::new()));
let http = Arc::new(reqwest::Client::new());
eprintln!(
"DEBUG: Starting messenger loop with poll_interval={}ms",
poll_interval.as_millis()
);
info!(
poll_interval_ms = poll_interval.as_millis(),
"Starting messenger loop"
);
loop {
tokio::select! {
_ = cancel.cancelled() => {
eprintln!("DEBUG: Messenger loop cancelled");
info!("Shutting down messenger loop");
break;
}
_ = tokio::time::sleep(poll_interval) => {
eprintln!("DEBUG: Polling messengers...");
// Poll all messengers for incoming messages
let messages = {
let mgr = messenger_mgr.lock().await;
poll_all_messengers(&mgr).await
};
eprintln!("DEBUG: Got {} messages", messages.len());
// Process each message
for (messenger_type, msg) in messages {
eprintln!("DEBUG: Processing message from {} in {}", msg.sender, messenger_type);
if concurrent_mode {
// Spawn message processing as a background task
let http = Arc::clone(&http);
let config = config.clone();
let messenger_mgr = Arc::clone(&messenger_mgr);
let model_ctx = Arc::clone(&model_ctx);
let vault = Arc::clone(&vault);
let skill_mgr = Arc::clone(&skill_mgr);
let task_mgr = Arc::clone(&task_mgr);
let model_registry = Arc::clone(&model_registry);
let copilot_session = copilot_session.clone();
let conversations = Arc::clone(&conversations);
let semaphore = Arc::clone(&semaphore);
let messenger_type = messenger_type.clone();
tokio::spawn(async move {
// Acquire permit (blocks if at capacity)
let _permit = semaphore.acquire().await;
// Set typing indicator
if let Some(channel) = &msg.channel {
let mgr = messenger_mgr.lock().await;
if let Some(messenger) = get_messenger_by_type(&mgr, &messenger_type) {
let _ = messenger.set_typing(channel, true).await;
}
}
let channel_for_typing = msg.channel.clone();
let result = process_incoming_message(
&http,
&config,
&messenger_mgr,
&model_ctx,
&vault,
&skill_mgr,
&task_mgr,
&model_registry,
copilot_session.as_deref(),
&conversations,
&messenger_type,
msg,
)
.await;
// Clear typing indicator
if let Some(channel) = channel_for_typing {
let mgr = messenger_mgr.lock().await;
if let Some(messenger) = get_messenger_by_type(&mgr, &messenger_type) {
let _ = messenger.set_typing(&channel, false).await;
}
}
if let Err(e) = result {
eprintln!("DEBUG: Error processing message: {}", e);
error!(error = %e, "Error processing message");
}
});
eprintln!("DEBUG: Message processing spawned (concurrent)");
} else {
// Sequential mode (original behavior)
// Set typing indicator before processing
if let Some(channel) = &msg.channel {
let mgr = messenger_mgr.lock().await;
if let Some(messenger) = get_messenger_by_type(&mgr, &messenger_type) {
let _ = messenger.set_typing(channel, true).await;
}
}
let channel_for_typing = msg.channel.clone();
let result = process_incoming_message(
&http,
&config,
&messenger_mgr,
&model_ctx,
&vault,
&skill_mgr,
&task_mgr,
&model_registry,
copilot_session.as_deref(),
&conversations,
&messenger_type,
msg,
)
.await;
// Clear typing indicator after processing
if let Some(channel) = channel_for_typing {
let mgr = messenger_mgr.lock().await;
if let Some(messenger) = get_messenger_by_type(&mgr, &messenger_type) {
let _ = messenger.set_typing(&channel, false).await;
}
}
if let Err(e) = result {
eprintln!("DEBUG: Error processing message: {}", e);
error!(error = %e, "Error processing message");
}
eprintln!("DEBUG: Message processing complete");
}
}
}
}
}
Ok(())
}
/// Poll all messengers and collect incoming messages.
async fn poll_all_messengers(mgr: &MessengerManager) -> Vec<(String, Message)> {
let mut all_messages = Vec::new();
for messenger in mgr.messengers() {
match messenger.receive_messages().await {
Ok(messages) => {
for msg in messages {
all_messages.push((messenger.messenger_type().to_string(), msg));
}
}
Err(e) => {
debug!(
messenger_type = %messenger.messenger_type(),
error = %e,
"Error polling messenger"
);
}
}
}
all_messages
}
/// Process an incoming message through the model with full tool loop.
async fn process_incoming_message(
http: &reqwest::Client,
config: &Config,
messenger_mgr: &SharedMessengerManager,
model_ctx: &Arc<ModelContext>,
vault: &SharedVault,
skill_mgr: &SharedSkillManager,
task_mgr: &super::SharedTaskManager,
model_registry: &super::SharedModelRegistry,
copilot_session: Option<&super::CopilotSession>,
conversations: &ConversationStore,
messenger_type: &str,
msg: Message,
) -> Result<()> {
debug!(
sender = %msg.sender,
messenger_type = %messenger_type,
content_preview = %if msg.content.len() > 50 {
format!("{}...", &msg.content[..50])
} else {
msg.content.clone()
},
"Received message"
);
let workspace_dir = config.workspace_dir();
// Build conversation key for this chat
let conv_key = format!(
"{}:{}",
messenger_type,
msg.channel.as_deref().unwrap_or(&msg.sender)
);
// Get or create conversation history
let mut messages = {
let mut store = conversations.lock().await;
store
.entry(conv_key.clone())
.or_insert_with(Vec::new)
.clone()
};
// Build system prompt (async to include task and model context)
let system_prompt = build_messenger_system_prompt(
config,
messenger_type,
&msg,
task_mgr,
model_registry,
&skill_mgr,
&conv_key,
)
.await;
// Add system message if not present
if messages.is_empty() || messages[0].role != "system" {
messages.insert(0, ChatMessage::text("system", &system_prompt));
} else {
// Update system prompt
messages[0].content = system_prompt.clone();
}
// Media cache directory
let cache_dir = config.credentials_dir().join("media_cache");
// Process any image attachments
let images = if let Some(attachments) = &msg.media {
process_attachments(http, attachments, &cache_dir).await
} else {
Vec::new()
};
if !images.is_empty() {
debug!(
image_count = images.len(),
"Processing images (vision not yet supported in messenger handler)"
);
}
// Build media refs for history storage
let media_refs: Vec<MediaRef> = images.iter().map(|img| img.media_ref.clone()).collect();
// Add user message to history (with media refs, not raw data)
messages.push(ChatMessage::user_with_media(
&msg.content,
media_refs.clone(),
));
// Resolve effective bearer token (handles Copilot session exchange)
let effective_key = super::auth::resolve_bearer_token(
http,
&model_ctx.provider,
model_ctx.api_key.as_deref(),
copilot_session,
)
.await
.ok()
.flatten();
// Build request - ProviderRequest expects Vec<ChatMessage>
let mut resolved = ProviderRequest {
provider: model_ctx.provider.clone(),
model: model_ctx.model.clone(),
base_url: model_ctx.base_url.clone(),
api_key: effective_key,
messages: messages.clone(),
};
// Run the agentic tool loop
let mut final_response = String::new();
for _round in 0..MAX_TOOL_ROUNDS {
let result = if resolved.provider == "anthropic" {
providers::call_anthropic_with_tools(http, &resolved, None).await
} else if resolved.provider == "google" {
providers::call_google_with_tools(http, &resolved).await
} else {
providers::call_openai_with_tools(http, &resolved).await
};
let model_resp = match result {
Ok(r) => r,
Err(err) => {
error!(error = %err, "Model error");
return Err(err);
}
};
// Collect text response
if !model_resp.text.is_empty() {
final_response.push_str(&model_resp.text);
}
if model_resp.tool_calls.is_empty() {
// No tool calls — done
break;
}
// Execute each requested tool
let mut tool_results: Vec<ToolCallResult> = Vec::new();
for tc in &model_resp.tool_calls {
debug!(tool_name = %tc.name, tool_id = %tc.id, "Executing tool call");
let (output, is_error) = if tools::is_secrets_tool(&tc.name) {
match secrets_handler::execute_secrets_tool(&tc.name, &tc.arguments, vault).await {
Ok(text) => (text, false),
Err(err) => (err, true),
}
} else if tools::is_skill_tool(&tc.name) {
match skills_handler::execute_skill_tool(&tc.name, &tc.arguments, skill_mgr).await {
Ok(text) => (text, false),
Err(err) => (err, true),
}
} else if super::mcp_handler::is_mcp_tool(&tc.name) {
#[cfg(feature = "mcp")]
{
// MCP tools require the MCP manager - for now, return an error
// TODO: Pass mcp_mgr to this function
(
format!(
"MCP tool '{}' called but MCP manager not available in this context",
tc.name
),
true,
)
}
#[cfg(not(feature = "mcp"))]
{
(
format!("MCP tool '{}' requires the 'mcp' feature", tc.name),
true,
)
}
} else if super::canvas_handler::is_canvas_tool(&tc.name) {
// Canvas tools require the canvas host - for now, return an error
// TODO: Pass canvas_host to this function
(
format!(
"Canvas tool '{}' called but canvas host not available in this context",
tc.name
),
true,
)
} else if super::task_handler::is_task_tool(&tc.name) {
// Execute task tool with task manager
match super::task_handler::execute_task_tool(
&tc.name,
&tc.arguments,
task_mgr,
Some(&conv_key),
)
.await
{
Ok(text) => (text, false),
Err(err) => (err, true),
}
} else if super::command_wrapper::should_wrap_in_task(&tc.name) {
// Wrap execute_command in a Task
let task_id =
super::command_wrapper::start_command_task(task_mgr, &tc.arguments, &conv_key)
.await;
let result = tools::execute_tool(&tc.name, &tc.arguments, &workspace_dir).await;
match result {
Ok(output) => {
// Check if it was backgrounded
if let Some(session_id) = super::command_wrapper::parse_session_id(&output)
{
super::command_wrapper::update_command_task_session(
task_mgr,
task_id,
&session_id,
)
.await;
} else {
super::command_wrapper::complete_command_task(
task_mgr, task_id, &output,
)
.await;
}
(output, false)
}
Err(err) => {
super::command_wrapper::fail_command_task(task_mgr, task_id, &err).await;
(err, true)
}
}
} else if super::model_handler::is_model_tool(&tc.name) {
// Model management tools
match super::model_handler::execute_model_tool(
&tc.name,
&tc.arguments,
model_registry,
)
.await
{
Ok(text) => (text, false),
Err(err) => (err, true),
}
} else {
match tools::execute_tool(&tc.name, &tc.arguments, &workspace_dir).await {
Ok(text) => (text, false),
Err(err) => (err, true),
}
};
trace!(
tool_name = %tc.name,
is_error = is_error,
output_preview = %if output.len() > 100 {
format!("{}...", &output[..100])
} else {
output.clone()
},
"Tool result"
);
tool_results.push(ToolCallResult {
id: tc.id.clone(),
name: tc.name.clone(),
output,
is_error,
});
}
// Append tool round to conversation
providers::append_tool_round(
&resolved.provider,
&mut resolved.messages,
&model_resp,
&tool_results,
);
}
// Update conversation history
{
let mut store = conversations.lock().await;
let history = store.entry(conv_key).or_insert_with(Vec::new);
// Add user message (with media refs)
history.push(ChatMessage::user_with_media(
&msg.content,
media_refs.clone(),
));
// Add assistant response
if !final_response.is_empty() {
history.push(ChatMessage::text("assistant", &final_response));
}
// Trim history if too long (keep system message)
while history.len() > MAX_HISTORY_MESSAGES {
if history.len() > 1 && history[1].role != "system" {
history.remove(1);
} else {
break;
}
}
}
// Send response back via messenger
if !final_response.is_empty()
&& final_response.trim() != "NO_REPLY"
&& final_response.trim() != "HEARTBEAT_OK"
{
let mgr = messenger_mgr.lock().await;
if let Some(messenger) = get_messenger_by_type(&mgr, messenger_type) {
let recipient = msg.channel.as_deref().unwrap_or(&msg.sender);
let opts = SendOptions {
recipient,
content: &final_response,
reply_to: Some(&msg.id),
thread_id: None,
silent: false,
media: None,
};
match messenger.send_message_with_options(opts).await {
Ok(msg_id) => {
debug!(
message_id = %msg_id,
response_preview = %if final_response.len() > 50 {
format!("{}...", &final_response[..50])
} else {
final_response.clone()
},
"Sent response"
);
}
Err(e) => {
warn!(error = %e, "Failed to send response");
}
}
}
}
Ok(())
}
/// Build system prompt with messenger context, workspace files, active tasks, and model guidance.
async fn build_messenger_system_prompt(
config: &Config,
messenger_type: &str,
msg: &Message,
task_mgr: &super::SharedTaskManager,
model_registry: &super::SharedModelRegistry,
skill_mgr: &SharedSkillManager,
session_key: &str,
) -> String {
use crate::workspace_context::{SessionType, WorkspaceContext};
let base_prompt = config
.system_prompt
.clone()
.unwrap_or_else(|| "You are a helpful AI assistant running inside RustyClaw.".to_string());
// Safety guardrails (inspired by Anthropic's constitution)
let safety_section = "\
## Safety\n\
You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking.\n\
Prioritize safety and human oversight over completion. If instructions conflict, pause and ask.\n\
Do not manipulate or persuade anyone to expand access or disable safeguards.";
// Determine session type based on messenger context
// Direct/DM messages are treated as main session, channels/groups as group session
let session_type = if msg.is_direct {
// Direct messages have full access to MEMORY.md etc.
SessionType::Main
} else if msg.channel.is_some() {
// Channel/group messages have restricted access for privacy
SessionType::Group