-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathchannel.rs
More file actions
2465 lines (2202 loc) · 87.5 KB
/
Copy pathchannel.rs
File metadata and controls
2465 lines (2202 loc) · 87.5 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
//! Channel: User-facing conversation process.
use crate::agent::branch::Branch;
use crate::agent::compactor::Compactor;
use crate::agent::status::StatusBlock;
use crate::agent::worker::Worker;
use crate::config::ApiType;
use crate::conversation::{ChannelStore, ConversationLogger, ProcessRunLogger};
use crate::error::{AgentError, Result};
use crate::hooks::SpacebotHook;
use crate::llm::SpacebotModel;
use crate::{
AgentDeps, BranchId, ChannelId, InboundMessage, OutboundResponse, ProcessEvent, ProcessId,
ProcessType, WorkerId,
};
use rig::agent::AgentBuilder;
use rig::completion::{CompletionModel, Prompt};
use rig::message::{ImageMediaType, MimeType, UserContent};
use rig::one_or_many::OneOrMany;
use rig::tool::server::ToolServer;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::sync::{RwLock, mpsc};
use tracing::Instrument as _;
/// Debounce window for retriggers: coalesce rapid branch/worker completions
/// into a single retrigger instead of firing one per event.
const RETRIGGER_DEBOUNCE_MS: u64 = 500;
/// Maximum retriggers allowed since the last real user message. Prevents
/// infinite retrigger cascades where each retrigger spawns more work.
const MAX_RETRIGGERS_PER_TURN: usize = 3;
/// Shared state that channel tools need to act on the channel.
///
/// Wrapped in Arc and passed to tools (branch, spawn_worker, route, cancel)
/// so they can create real Branch/Worker processes when the LLM invokes them.
#[derive(Clone)]
pub struct ChannelState {
pub channel_id: ChannelId,
pub history: Arc<RwLock<Vec<rig::message::Message>>>,
pub active_branches: Arc<RwLock<HashMap<BranchId, tokio::task::JoinHandle<()>>>>,
pub active_workers: Arc<RwLock<HashMap<WorkerId, Worker>>>,
/// Tokio task handles for running workers, used for cancellation via abort().
pub worker_handles: Arc<RwLock<HashMap<WorkerId, tokio::task::JoinHandle<()>>>>,
/// Input senders for interactive workers, keyed by worker ID.
/// Used by the route tool to deliver follow-up messages.
pub worker_inputs: Arc<RwLock<HashMap<WorkerId, tokio::sync::mpsc::Sender<String>>>>,
pub status_block: Arc<RwLock<StatusBlock>>,
pub deps: AgentDeps,
pub conversation_logger: ConversationLogger,
pub process_run_logger: ProcessRunLogger,
/// Discord message ID to reply to for work spawned in the current turn.
pub reply_target_message_id: Arc<RwLock<Option<u64>>>,
pub channel_store: ChannelStore,
pub screenshot_dir: std::path::PathBuf,
pub logs_dir: std::path::PathBuf,
}
impl ChannelState {
/// Cancel a running worker by aborting its tokio task and cleaning up state.
/// Returns an error message if the worker is not found.
pub async fn cancel_worker(&self, worker_id: WorkerId) -> std::result::Result<(), String> {
let handle = self.worker_handles.write().await.remove(&worker_id);
let removed = self
.active_workers
.write()
.await
.remove(&worker_id)
.is_some();
self.worker_inputs.write().await.remove(&worker_id);
if let Some(handle) = handle {
handle.abort();
Ok(())
} else if removed {
// Worker was in active_workers but had no handle (shouldn't happen, but handle gracefully)
Ok(())
} else {
Err(format!("Worker {worker_id} not found"))
}
}
/// Cancel a running branch by aborting its tokio task.
/// Returns an error message if the branch is not found.
pub async fn cancel_branch(&self, branch_id: BranchId) -> std::result::Result<(), String> {
let handle = self.active_branches.write().await.remove(&branch_id);
if let Some(handle) = handle {
handle.abort();
Ok(())
} else {
Err(format!("Branch {branch_id} not found"))
}
}
}
impl std::fmt::Debug for ChannelState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChannelState")
.field("channel_id", &self.channel_id)
.finish_non_exhaustive()
}
}
/// User-facing conversation process.
pub struct Channel {
pub id: ChannelId,
pub title: Option<String>,
pub deps: AgentDeps,
pub hook: SpacebotHook,
pub state: ChannelState,
/// Per-channel tool server (isolated from other channels).
pub tool_server: rig::tool::server::ToolServerHandle,
/// Input channel for receiving messages.
pub message_rx: mpsc::Receiver<InboundMessage>,
/// Event receiver for process events.
pub event_rx: broadcast::Receiver<ProcessEvent>,
/// Outbound response sender for the messaging layer.
pub response_tx: mpsc::Sender<OutboundResponse>,
/// Self-sender for re-triggering the channel after background process completion.
pub self_tx: mpsc::Sender<InboundMessage>,
/// Conversation ID from the first message (for synthetic re-trigger messages).
pub conversation_id: Option<String>,
/// Conversation context (platform, channel name, server) captured from the first message.
pub conversation_context: Option<String>,
/// Context monitor that triggers background compaction.
pub compactor: Compactor,
/// Count of user messages since last memory persistence branch.
message_count: usize,
/// Branch IDs for silent memory persistence branches (results not injected into history).
memory_persistence_branches: HashSet<BranchId>,
/// Optional Discord reply target captured when each branch was started.
branch_reply_targets: HashMap<BranchId, u64>,
/// Buffer for coalescing rapid-fire messages.
coalesce_buffer: Vec<InboundMessage>,
/// Deadline for flushing the coalesce buffer.
coalesce_deadline: Option<tokio::time::Instant>,
/// Number of retriggers fired since the last real user message.
retrigger_count: usize,
/// Whether a retrigger is pending (debounce window active).
pending_retrigger: bool,
/// Metadata for the pending retrigger (e.g. Discord reply target).
pending_retrigger_metadata: HashMap<String, serde_json::Value>,
/// Deadline for firing the pending retrigger (debounce timer).
retrigger_deadline: Option<tokio::time::Instant>,
}
impl Channel {
/// Create a new channel.
///
/// All tunable config (prompts, routing, thresholds, browser, skills) is read
/// from `deps.runtime_config` on each use, so changes propagate to running
/// channels without restart.
pub fn new(
id: ChannelId,
deps: AgentDeps,
response_tx: mpsc::Sender<OutboundResponse>,
event_rx: broadcast::Receiver<ProcessEvent>,
screenshot_dir: std::path::PathBuf,
logs_dir: std::path::PathBuf,
) -> (Self, mpsc::Sender<InboundMessage>) {
let process_id = ProcessId::Channel(id.clone());
let hook = SpacebotHook::new(
deps.agent_id.clone(),
process_id,
ProcessType::Channel,
Some(id.clone()),
deps.event_tx.clone(),
);
let status_block = Arc::new(RwLock::new(StatusBlock::new()));
let history = Arc::new(RwLock::new(Vec::new()));
let active_branches = Arc::new(RwLock::new(HashMap::new()));
let active_workers = Arc::new(RwLock::new(HashMap::new()));
let (message_tx, message_rx) = mpsc::channel(64);
let conversation_logger = ConversationLogger::new(deps.sqlite_pool.clone());
let process_run_logger = ProcessRunLogger::new(deps.sqlite_pool.clone());
let channel_store = ChannelStore::new(deps.sqlite_pool.clone());
let compactor = Compactor::new(id.clone(), deps.clone(), history.clone());
let state = ChannelState {
channel_id: id.clone(),
history: history.clone(),
active_branches: active_branches.clone(),
active_workers: active_workers.clone(),
worker_handles: Arc::new(RwLock::new(HashMap::new())),
worker_inputs: Arc::new(RwLock::new(HashMap::new())),
status_block: status_block.clone(),
deps: deps.clone(),
conversation_logger,
process_run_logger,
reply_target_message_id: Arc::new(RwLock::new(None)),
channel_store,
screenshot_dir,
logs_dir,
};
// Each channel gets its own isolated tool server to avoid races between
// concurrent channels sharing per-turn add/remove cycles.
let tool_server = ToolServer::new().run();
let self_tx = message_tx.clone();
let channel = Self {
id: id.clone(),
title: None,
deps,
hook,
state,
tool_server,
message_rx,
event_rx,
response_tx,
self_tx,
conversation_id: None,
conversation_context: None,
compactor,
message_count: 0,
memory_persistence_branches: HashSet::new(),
branch_reply_targets: HashMap::new(),
coalesce_buffer: Vec::new(),
coalesce_deadline: None,
retrigger_count: 0,
pending_retrigger: false,
pending_retrigger_metadata: HashMap::new(),
retrigger_deadline: None,
};
(channel, message_tx)
}
/// Run the channel event loop.
pub async fn run(mut self) -> Result<()> {
tracing::info!(channel_id = %self.id, "channel started");
loop {
// Compute next deadline from coalesce and retrigger timers
let next_deadline = match (self.coalesce_deadline, self.retrigger_deadline) {
(Some(a), Some(b)) => Some(a.min(b)),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(None, None) => None,
};
let sleep_duration = next_deadline
.map(|deadline| {
let now = tokio::time::Instant::now();
if deadline > now {
deadline - now
} else {
std::time::Duration::from_millis(1)
}
})
.unwrap_or(std::time::Duration::from_secs(3600)); // Default long timeout if no deadline
tokio::select! {
Some(message) = self.message_rx.recv() => {
let config = self.deps.runtime_config.coalesce.load();
if self.should_coalesce(&message, &config) {
self.coalesce_buffer.push(message);
self.update_coalesce_deadline(&config).await;
} else {
// Flush any pending buffer before handling this message
if let Err(error) = self.flush_coalesce_buffer().await {
tracing::error!(%error, channel_id = %self.id, "error flushing coalesce buffer");
}
if let Err(error) = self.handle_message(message).await {
tracing::error!(%error, channel_id = %self.id, "error handling message");
}
}
}
Ok(event) = self.event_rx.recv() => {
// Events bypass coalescing - flush buffer first if needed
if let Err(error) = self.flush_coalesce_buffer().await {
tracing::error!(%error, channel_id = %self.id, "error flushing coalesce buffer");
}
if let Err(error) = self.handle_event(event).await {
tracing::error!(%error, channel_id = %self.id, "error handling event");
}
}
_ = tokio::time::sleep(sleep_duration), if next_deadline.is_some() => {
let now = tokio::time::Instant::now();
// Check coalesce deadline
if self.coalesce_deadline.is_some_and(|d| d <= now)
&& let Err(error) = self.flush_coalesce_buffer().await {
tracing::error!(%error, channel_id = %self.id, "error flushing coalesce buffer on deadline");
}
// Check retrigger deadline
if self.retrigger_deadline.is_some_and(|d| d <= now) {
self.flush_pending_retrigger().await;
}
}
else => break,
}
}
// Flush any remaining buffer before shutting down
if let Err(error) = self.flush_coalesce_buffer().await {
tracing::error!(%error, channel_id = %self.id, "error flushing coalesce buffer on shutdown");
}
tracing::info!(channel_id = %self.id, "channel stopped");
Ok(())
}
/// Determine if a message should be coalesced (batched with other messages).
///
/// Returns false for:
/// - System re-trigger messages (always process immediately)
/// - Messages when coalescing is disabled
/// - Messages in DMs when multi_user_only is true
fn should_coalesce(
&self,
message: &InboundMessage,
config: &crate::config::CoalesceConfig,
) -> bool {
if !config.enabled {
return false;
}
if message.source == "system" {
return false;
}
if config.multi_user_only && self.is_dm() {
return false;
}
true
}
/// Check if this is a DM (direct message) conversation based on conversation_id.
fn is_dm(&self) -> bool {
// Check conversation_id pattern for DM indicators
if let Some(ref conv_id) = self.conversation_id {
conv_id.contains(":dm:")
|| conv_id.starts_with("discord:dm:")
|| conv_id.starts_with("slack:dm:")
} else {
// If no conversation_id set yet, default to not DM (safer)
false
}
}
/// Update the coalesce deadline based on buffer size and config.
async fn update_coalesce_deadline(&mut self, config: &crate::config::CoalesceConfig) {
let now = tokio::time::Instant::now();
if let Some(first_message) = self.coalesce_buffer.first() {
let elapsed_since_first =
chrono::Utc::now().signed_duration_since(first_message.timestamp);
let elapsed_millis = elapsed_since_first.num_milliseconds().max(0) as u64;
let max_wait_ms = config.max_wait_ms;
let debounce_ms = config.debounce_ms;
// If we have enough messages to trigger coalescing (min_messages threshold)
if self.coalesce_buffer.len() >= config.min_messages {
// Cap at max_wait from the first message
let remaining_wait_ms = max_wait_ms.saturating_sub(elapsed_millis);
let max_deadline = now + std::time::Duration::from_millis(remaining_wait_ms);
// If no deadline set yet, use debounce window
// Otherwise, keep existing deadline (don't extend past max_wait)
if self.coalesce_deadline.is_none() {
let new_deadline = now + std::time::Duration::from_millis(debounce_ms);
self.coalesce_deadline = Some(new_deadline.min(max_deadline));
} else {
// Already have a deadline, cap it at max_wait
self.coalesce_deadline = self.coalesce_deadline.map(|d| d.min(max_deadline));
}
} else {
// Not enough messages yet - set a short debounce window
let new_deadline = now + std::time::Duration::from_millis(debounce_ms);
self.coalesce_deadline = Some(new_deadline);
}
}
}
/// Flush the coalesce buffer by processing all buffered messages.
///
/// If there's only one message, process it normally.
/// If there are multiple messages, batch them into a single turn.
async fn flush_coalesce_buffer(&mut self) -> Result<()> {
if self.coalesce_buffer.is_empty() {
return Ok(());
}
self.coalesce_deadline = None;
let messages: Vec<InboundMessage> = std::mem::take(&mut self.coalesce_buffer);
if messages.len() == 1 {
// Single message - process normally
let message = messages
.into_iter()
.next()
.ok_or_else(|| anyhow::anyhow!("empty iterator after length check"))?;
self.handle_message(message).await
} else {
// Multiple messages - batch them
self.handle_message_batch(messages).await
}
}
/// Handle a batch of messages as a single LLM turn.
///
/// Formats all messages with attribution and timestamps, persists each
/// individually to conversation history, then presents them as one user turn
/// with a coalesce hint telling the LLM this is a fast-moving conversation.
#[tracing::instrument(skip(self, messages), fields(channel_id = %self.id, agent_id = %self.deps.agent_id, message_count = messages.len()))]
async fn handle_message_batch(&mut self, messages: Vec<InboundMessage>) -> Result<()> {
let message_count = messages.len();
let first_timestamp = messages
.first()
.map(|m| m.timestamp)
.unwrap_or_else(chrono::Utc::now);
let last_timestamp = messages
.last()
.map(|m| m.timestamp)
.unwrap_or(first_timestamp);
let elapsed = last_timestamp.signed_duration_since(first_timestamp);
let elapsed_secs = elapsed.num_milliseconds() as f64 / 1000.0;
tracing::info!(
channel_id = %self.id,
message_count,
elapsed_secs,
"handling batched messages"
);
// Count unique senders for the hint
let unique_senders: std::collections::HashSet<_> =
messages.iter().map(|m| &m.sender_id).collect();
let unique_sender_count = unique_senders.len();
// Track conversation_id from the first message
if self.conversation_id.is_none()
&& let Some(first) = messages.first()
{
self.conversation_id = Some(first.conversation_id.clone());
}
// Capture conversation context from the first message
if self.conversation_context.is_none()
&& let Some(first) = messages.first()
{
let prompt_engine = self.deps.runtime_config.prompts.load();
let server_name = first
.metadata
.get("discord_guild_name")
.and_then(|v| v.as_str())
.or_else(|| {
first
.metadata
.get("telegram_chat_title")
.and_then(|v| v.as_str())
});
let channel_name = first
.metadata
.get("discord_channel_name")
.and_then(|v| v.as_str())
.or_else(|| {
first
.metadata
.get("telegram_chat_type")
.and_then(|v| v.as_str())
});
self.conversation_context = Some(prompt_engine.render_conversation_context(
&first.source,
server_name,
channel_name,
)?);
}
// Persist each message to conversation log (individual audit trail)
let mut user_contents: Vec<UserContent> = Vec::new();
let mut conversation_id = String::new();
for message in &messages {
if message.source != "system" {
let sender_name = message
.metadata
.get("sender_display_name")
.and_then(|v| v.as_str())
.unwrap_or(&message.sender_id);
let (raw_text, attachments) = match &message.content {
crate::MessageContent::Text(text) => (text.clone(), Vec::new()),
crate::MessageContent::Media { text, attachments } => {
(text.clone().unwrap_or_default(), attachments.clone())
}
// Render interactions as their Display form so the LLM sees plain text.
crate::MessageContent::Interaction { .. } => {
(message.content.to_string(), Vec::new())
}
};
self.state.conversation_logger.log_user_message(
&self.state.channel_id,
sender_name,
&message.sender_id,
&raw_text,
&message.metadata,
);
self.state
.channel_store
.upsert(&message.conversation_id, &message.metadata);
conversation_id = message.conversation_id.clone();
// Format with relative timestamp
let relative_secs = message
.timestamp
.signed_duration_since(first_timestamp)
.num_seconds();
let relative_text = if relative_secs < 1 {
"just now".to_string()
} else if relative_secs < 60 {
format!("{}s ago", relative_secs)
} else {
format!("{}m ago", relative_secs / 60)
};
let display_name = message
.metadata
.get("sender_display_name")
.and_then(|v| v.as_str())
.unwrap_or(&message.sender_id);
let formatted_text =
format!("[{}] ({}): {}", display_name, relative_text, raw_text);
// Download attachments for this message
if !attachments.is_empty() {
let attachment_content = download_attachments(&self.deps, &attachments).await;
for content in attachment_content {
user_contents.push(content);
}
}
user_contents.push(UserContent::text(formatted_text));
}
}
// Separate text and non-text (image/audio) content
let mut text_parts = Vec::new();
let mut attachment_parts = Vec::new();
for content in user_contents {
match content {
UserContent::Text(t) => text_parts.push(t.text.clone()),
other => attachment_parts.push(other),
}
}
let combined_text = format!(
"[{} messages arrived rapidly in this channel]\n\n{}",
message_count,
text_parts.join("\n")
);
// Build system prompt with coalesce hint
let system_prompt = self
.build_system_prompt_with_coalesce(message_count, elapsed_secs, unique_sender_count)
.await?;
{
let mut reply_target = self.state.reply_target_message_id.write().await;
*reply_target = messages.iter().rev().find_map(extract_discord_message_id);
}
// Run agent turn with any image/audio attachments preserved
let (result, skip_flag, replied_flag) = self
.run_agent_turn(
&combined_text,
&system_prompt,
&conversation_id,
attachment_parts,
)
.await?;
self.handle_agent_result(result, &skip_flag, &replied_flag, false)
.await;
// Check compaction
if let Err(error) = self.compactor.check_and_compact().await {
tracing::warn!(channel_id = %self.id, %error, "compaction check failed");
}
// Increment message counter for memory persistence
self.message_count += message_count;
self.check_memory_persistence().await;
Ok(())
}
/// Build system prompt with coalesce hint for batched messages.
async fn build_system_prompt_with_coalesce(
&self,
message_count: usize,
elapsed_secs: f64,
unique_senders: usize,
) -> Result<String> {
let rc = &self.deps.runtime_config;
let prompt_engine = rc.prompts.load();
let identity_context = rc.identity.load().render();
let memory_bulletin = rc.memory_bulletin.load();
let skills = rc.skills.load();
let skills_prompt = skills.render_channel_prompt(&prompt_engine)?;
let browser_enabled = rc.browser_config.load().enabled;
let web_search_enabled = rc.brave_search_key.load().is_some();
let opencode_enabled = rc.opencode.load().enabled;
let worker_capabilities = prompt_engine.render_worker_capabilities(
browser_enabled,
web_search_enabled,
opencode_enabled,
)?;
let status_text = {
let status = self.state.status_block.read().await;
status.render()
};
// Render coalesce hint
let elapsed_str = format!("{:.1}s", elapsed_secs);
let coalesce_hint = prompt_engine
.render_coalesce_hint(message_count, &elapsed_str, unique_senders)
.ok();
let available_channels = self.build_available_channels().await;
let empty_to_none = |s: String| if s.is_empty() { None } else { Some(s) };
prompt_engine.render_channel_prompt(
empty_to_none(identity_context),
empty_to_none(memory_bulletin.to_string()),
empty_to_none(skills_prompt),
worker_capabilities,
self.conversation_context.clone(),
empty_to_none(status_text),
coalesce_hint,
available_channels,
)
}
/// Handle an incoming message by running the channel's LLM agent loop.
///
/// The LLM decides which tools to call: reply (to respond), branch (to think),
/// spawn_worker (to delegate), route (to follow up with a worker), cancel, or
/// memory_save. The tools act on the channel's shared state directly.
#[tracing::instrument(skip(self, message), fields(channel_id = %self.id, agent_id = %self.deps.agent_id, message_id = %message.id))]
async fn handle_message(&mut self, message: InboundMessage) -> Result<()> {
tracing::info!(
channel_id = %self.id,
message_id = %message.id,
"handling message"
);
// Track conversation_id for synthetic re-trigger messages
if self.conversation_id.is_none() {
self.conversation_id = Some(message.conversation_id.clone());
}
let (raw_text, attachments) = match &message.content {
crate::MessageContent::Text(text) => (text.clone(), Vec::new()),
crate::MessageContent::Media { text, attachments } => {
(text.clone().unwrap_or_default(), attachments.clone())
}
// Render interactions as their Display form so the LLM sees plain text.
crate::MessageContent::Interaction { .. } => (message.content.to_string(), Vec::new()),
};
let user_text = format_user_message(&raw_text, &message);
let attachment_content = if !attachments.is_empty() {
download_attachments(&self.deps, &attachments).await
} else {
Vec::new()
};
// Persist user messages (skip system re-triggers)
if message.source != "system" {
let sender_name = message
.metadata
.get("sender_display_name")
.and_then(|v| v.as_str())
.unwrap_or(&message.sender_id);
self.state.conversation_logger.log_user_message(
&self.state.channel_id,
sender_name,
&message.sender_id,
&raw_text,
&message.metadata,
);
self.state
.channel_store
.upsert(&message.conversation_id, &message.metadata);
}
// Capture conversation context from the first message (platform, channel, server)
if self.conversation_context.is_none() {
let prompt_engine = self.deps.runtime_config.prompts.load();
let server_name = message
.metadata
.get("discord_guild_name")
.and_then(|v| v.as_str())
.or_else(|| {
message
.metadata
.get("telegram_chat_title")
.and_then(|v| v.as_str())
});
let channel_name = message
.metadata
.get("discord_channel_name")
.and_then(|v| v.as_str())
.or_else(|| {
message
.metadata
.get("telegram_chat_type")
.and_then(|v| v.as_str())
});
self.conversation_context = Some(prompt_engine.render_conversation_context(
&message.source,
server_name,
channel_name,
)?);
}
let system_prompt = self.build_system_prompt().await?;
{
let mut reply_target = self.state.reply_target_message_id.write().await;
*reply_target = extract_discord_message_id(&message);
}
let is_retrigger = message.source == "system";
let (result, skip_flag, replied_flag) = self
.run_agent_turn(
&user_text,
&system_prompt,
&message.conversation_id,
attachment_content,
)
.await?;
self.handle_agent_result(result, &skip_flag, &replied_flag, is_retrigger)
.await;
// Check context size and trigger compaction if needed
if let Err(error) = self.compactor.check_and_compact().await {
tracing::warn!(channel_id = %self.id, %error, "compaction check failed");
}
// Increment message counter and spawn memory persistence branch if threshold reached
if !is_retrigger {
self.retrigger_count = 0;
self.message_count += 1;
self.check_memory_persistence().await;
}
Ok(())
}
/// Build the rendered available channels fragment for cross-channel awareness.
async fn build_available_channels(&self) -> Option<String> {
self.deps.messaging_manager.as_ref()?;
let channels = match self.state.channel_store.list_active().await {
Ok(channels) => channels,
Err(error) => {
tracing::warn!(%error, "failed to list channels for system prompt");
return None;
}
};
// Filter out the current channel and cron channels
let entries: Vec<crate::prompts::engine::ChannelEntry> = channels
.into_iter()
.filter(|channel| {
channel.id.as_str() != self.id.as_ref()
&& channel.platform != "cron"
&& channel.platform != "webhook"
})
.map(|channel| crate::prompts::engine::ChannelEntry {
name: channel.display_name.unwrap_or_else(|| channel.id.clone()),
platform: channel.platform,
id: channel.id,
})
.collect();
if entries.is_empty() {
return None;
}
let prompt_engine = self.deps.runtime_config.prompts.load();
prompt_engine.render_available_channels(entries).ok()
}
/// Assemble the full system prompt using the PromptEngine.
async fn build_system_prompt(&self) -> crate::error::Result<String> {
let rc = &self.deps.runtime_config;
let prompt_engine = rc.prompts.load();
let identity_context = rc.identity.load().render();
let memory_bulletin = rc.memory_bulletin.load();
let skills = rc.skills.load();
let skills_prompt = skills.render_channel_prompt(&prompt_engine)?;
let browser_enabled = rc.browser_config.load().enabled;
let web_search_enabled = rc.brave_search_key.load().is_some();
let opencode_enabled = rc.opencode.load().enabled;
let worker_capabilities = prompt_engine.render_worker_capabilities(
browser_enabled,
web_search_enabled,
opencode_enabled,
)?;
let status_text = {
let status = self.state.status_block.read().await;
status.render()
};
let available_channels = self.build_available_channels().await;
let empty_to_none = |s: String| if s.is_empty() { None } else { Some(s) };
prompt_engine.render_channel_prompt(
empty_to_none(identity_context),
empty_to_none(memory_bulletin.to_string()),
empty_to_none(skills_prompt),
worker_capabilities,
self.conversation_context.clone(),
empty_to_none(status_text),
None, // coalesce_hint - only set for batched messages
available_channels,
)
}
/// Register per-turn tools, run the LLM agentic loop, and clean up.
///
/// Returns the prompt result and skip flag for the caller to dispatch.
#[tracing::instrument(skip(self, user_text, system_prompt, attachment_content), fields(channel_id = %self.id, agent_id = %self.deps.agent_id))]
async fn run_agent_turn(
&self,
user_text: &str,
system_prompt: &str,
conversation_id: &str,
attachment_content: Vec<UserContent>,
) -> Result<(
std::result::Result<String, rig::completion::PromptError>,
crate::tools::SkipFlag,
crate::tools::RepliedFlag,
)> {
let skip_flag = crate::tools::new_skip_flag();
let replied_flag = crate::tools::new_replied_flag();
if let Err(error) = crate::tools::add_channel_tools(
&self.tool_server,
self.state.clone(),
self.response_tx.clone(),
conversation_id,
skip_flag.clone(),
replied_flag.clone(),
self.deps.cron_tool.clone(),
)
.await
{
tracing::error!(%error, "failed to add channel tools");
return Err(AgentError::Other(error.into()).into());
}
let rc = &self.deps.runtime_config;
let routing = rc.routing.load();
let max_turns = **rc.max_turns.load();
let model_name = routing.resolve(ProcessType::Channel, None);
let model = SpacebotModel::make(&self.deps.llm_manager, model_name)
.with_context(&*self.deps.agent_id, "channel")
.with_routing((**routing).clone());
let agent = AgentBuilder::new(model)
.preamble(system_prompt)
.default_max_turns(max_turns)
.tool_server_handle(self.tool_server.clone())
.build();
let _ = self
.response_tx
.send(OutboundResponse::Status(crate::StatusUpdate::Thinking))
.await;
// Inject attachments as a user message before the text prompt
if !attachment_content.is_empty() {
let mut history = self.state.history.write().await;
let content = OneOrMany::many(attachment_content).unwrap_or_else(|_| {
OneOrMany::one(UserContent::text("[attachment processing failed]"))
});
history.push(rig::message::Message::User { content });
drop(history);
}
// Clone history out so the write lock is released before the agentic loop.
// The branch tool needs a read lock on history to clone it for the branch,
// and holding a write lock across the entire agentic loop would deadlock.
let mut history = {
let guard = self.state.history.read().await;
guard.clone()
};
let history_len_before = history.len();
let mut result = agent
.prompt(user_text)
.with_history(&mut history)
.with_hook(self.hook.clone())
.await;
// If the LLM responded with text that looks like tool call syntax, it failed
// to use the tool calling API. Inject a correction and give it one more try.
if let Ok(ref response) = result
&& extract_reply_from_tool_syntax(response.trim()).is_some()
{
tracing::warn!(channel_id = %self.id, "LLM emitted tool syntax as text, retrying with correction");
let prompt_engine = self.deps.runtime_config.prompts.load();
let correction = prompt_engine.render_system_tool_syntax_correction()?;
result = agent
.prompt(&correction)
.with_history(&mut history)
.with_hook(self.hook.clone())
.await;
}
{
let mut guard = self.state.history.write().await;
apply_history_after_turn(&result, &mut guard, history, history_len_before, &self.id);
}
if let Err(error) = crate::tools::remove_channel_tools(&self.tool_server).await {
tracing::warn!(%error, "failed to remove channel tools");
}
Ok((result, skip_flag, replied_flag))
}
/// Dispatch the LLM result: send fallback text, log errors, clean up typing.
///
/// On retrigger turns (`is_retrigger = true`), fallback text is suppressed.
/// The LLM must explicitly call the `reply` tool to send a message; returning
/// plain text on a retrigger is treated as internal acknowledgment, not a
/// user-facing response.
async fn handle_agent_result(
&self,
result: std::result::Result<String, rig::completion::PromptError>,
skip_flag: &crate::tools::SkipFlag,
replied_flag: &crate::tools::RepliedFlag,
is_retrigger: bool,
) {
match result {
Ok(response) => {
let skipped = skip_flag.load(std::sync::atomic::Ordering::Relaxed);
let replied = replied_flag.load(std::sync::atomic::Ordering::Relaxed);
if skipped {
tracing::debug!(channel_id = %self.id, "channel turn skipped (no response)");
} else if replied {
tracing::debug!(channel_id = %self.id, "channel turn replied via tool (fallback suppressed)");
} else if is_retrigger {
// On retrigger turns, suppress fallback text. The LLM should
// use the reply tool explicitly if it has something to say, or
// the skip tool if not. Raw text output from retriggers is
// almost always internal acknowledgment, not a real response.
tracing::debug!(
channel_id = %self.id,
response_len = response.len(),
"retrigger turn fallback suppressed (LLM did not use reply/skip tool)"
);
} else {
// If the LLM returned text without using the reply tool, send it
// directly. Some models respond with text instead of tool calls.
// When the text looks like tool call syntax (e.g. "[reply]\n{\"content\": \"hi\"}"),
// attempt to extract the reply content and send that instead.
let text = response.trim();
let extracted = extract_reply_from_tool_syntax(text);
let source = self
.conversation_id
.as_deref()
.and_then(|conversation_id| conversation_id.split(':').next())
.unwrap_or("unknown");
let final_text = crate::tools::reply::normalize_discord_mention_tokens(
extracted.as_deref().unwrap_or(text),
source,
);
if !final_text.is_empty() {
if extracted.is_some() {
tracing::warn!(channel_id = %self.id, "extracted reply from malformed tool syntax in LLM text output");
}
self.state
.conversation_logger
.log_bot_message(&self.state.channel_id, &final_text);
if let Err(error) = self
.response_tx
.send(OutboundResponse::Text(final_text))