-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathevent_loop.rs
More file actions
7503 lines (6752 loc) · 305 KB
/
event_loop.rs
File metadata and controls
7503 lines (6752 loc) · 305 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
//! Main event loop for Cortex TUI.
//!
//! This module provides the heart of the application - the main event loop that
//! coordinates the 120 FPS render loop with Cortex-core backend events using
//! `tokio::select!`.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │ EventLoop │
//! │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌────────────┐ │
//! │ │ FrameEngine │ │SessionBridge│ │StreamControl│ │ActionMapper│ │
//! │ │ (120 FPS) │ │ (Backend) │ │ (State) │ │ (Bindings) │ │
//! │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬─────┘ │
//! │ │ │ │ │ │
//! │ │ tokio::select! │ │ │
//! │ ▼ ▼ ▼ ▼ │
//! │ ┌──────────────────────────────────────────────────────────────┐ │
//! │ │ Main Event Loop │ │
//! │ │ • Engine events (ticks, keys, mouse, resize) │ │
//! │ │ • Backend events (streaming, tools, errors) │ │
//! │ │ • Action dispatch and state updates │ │
//! │ │ • View rendering │ │
//! │ └──────────────────────────────────────────────────────────────┘ │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Example
//!
//! ```rust,ignore
//! use cortex_tui::app::AppState;
//! use cortex_tui::runner::{CortexTerminal, EventLoop};
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let mut terminal = CortexTerminal::new()?;
//! let app_state = AppState::new();
//!
//! let mut event_loop = EventLoop::new(app_state);
//! event_loop.run(&mut terminal).await?;
//!
//! Ok(())
//! }
//! ```
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use anyhow::Result;
use ratatui::prelude::*;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_stream::StreamExt;
use crate::actions::{ActionContext, ActionMapper, KeyAction};
use crate::app::{
AppState, AppView, ApprovalMode, AutocompleteItem, AutocompleteTrigger, FocusTarget,
PendingToolResult, SubagentDisplayStatus, SubagentTaskDisplay,
};
use crate::bridge::{SessionBridge, StreamController, adapt_event};
use crate::commands::{CommandExecutor, CommandResult, FormRegistry, ModalType, ViewType};
use crate::events::{AppEvent, SubagentEvent, ToolEvent};
use crate::input::{ClickZoneId, ClickZoneRegistry, MouseAction, MouseButton, MouseHandler};
use crate::modal::{Modal, ModalAction, ModalResult, ModalStack};
use crate::permissions::PermissionManager;
use crate::providers::ProviderManager;
use crate::question::{QuestionRequest, QuestionState};
use crate::runner::card_handler::CardHandler;
use crate::runner::terminal::CortexTerminal;
use crate::session::{CortexSession, ExportFormat, StoredToolCall, export_session};
use crate::views::tool_call::{ToolStatus, format_result_summary};
use crate::views::{ApprovalView, QuestionClickZones, QuestionHit, QuestionPromptView};
use cortex_engine::client::{Message, ResponseEvent, ToolDefinition as ClientToolDefinition};
use cortex_engine::streaming::StreamEvent;
use cortex_engine::tools::handlers::subagent::{ProgressEvent, SubagentExecutor};
use cortex_engine::tools::{ToolRegistry, UnifiedToolExecutor};
use crate::agent::build_system_prompt;
use cortex_core::{EngineEvent, frame_engine::FrameEngine};
// ============================================================================
// EVENT LOOP STRUCT
// ============================================================================
/// Main event loop for the Cortex TUI application.
///
/// This struct coordinates the 120 FPS render loop with backend events,
/// handling user input, streaming responses, tool executions, and UI updates.
pub struct EventLoop {
/// Application state containing all UI state.
pub app_state: AppState,
/// Frame engine for 120 FPS rendering.
frame_engine: Option<FrameEngine>,
/// Session bridge for backend communication.
session_bridge: Option<SessionBridge>,
/// Stream controller for managing streaming state.
stream_controller: StreamController,
/// Action mapper for keybindings.
action_mapper: ActionMapper,
/// Click zone registry for mouse interaction.
click_zones: ClickZoneRegistry,
/// Mouse handler for click/drag/scroll.
mouse_handler: MouseHandler,
/// Modal stack for overlay dialogs.
modal_stack: ModalStack,
/// Command executor for slash commands.
command_executor: CommandExecutor,
/// Form registry for command forms.
form_registry: FormRegistry,
/// Permission manager for tool approvals.
permission_manager: PermissionManager,
/// Provider manager for AI providers.
provider_manager: Option<Arc<tokio::sync::RwLock<ProviderManager>>>,
/// Tool executor for running tools.
tool_executor: Option<Arc<UnifiedToolExecutor>>,
/// Subagent executor for running subagents.
subagent_executor: Option<Arc<SubagentExecutor>>,
/// Whether the event loop is running.
running: Arc<AtomicBool>,
/// Background task handles.
background_tasks: Vec<JoinHandle<()>>,
/// Last render timestamp for frame timing.
last_render: Instant,
/// Minimum frame time for 120 FPS.
min_frame_time: Duration,
/// Current Cortex session.
cortex_session: Option<CortexSession>,
/// Tool registry for available tools.
tool_registry: Option<Arc<ToolRegistry>>,
/// Whether streaming was cancelled.
streaming_cancelled: Arc<AtomicBool>,
/// Whether stream done was received.
stream_done_received: bool,
/// Receiver for streaming events.
streaming_rx: Option<mpsc::Receiver<StreamEvent>>,
/// Handle to the streaming task.
streaming_task: Option<JoinHandle<()>>,
/// Card handler for card-based UI.
card_handler: CardHandler,
/// Unified tool executor.
unified_executor: Option<Arc<UnifiedToolExecutor>>,
/// Pending assistant tool calls.
pending_assistant_tool_calls: Vec<PendingToolCall>,
/// Running tool tasks.
running_tool_tasks: std::collections::HashMap<String, JoinHandle<()>>,
/// Running subagents.
running_subagents: std::collections::HashMap<String, JoinHandle<()>>,
/// Tool execution started flag.
tool_execution_started: bool,
/// Channel for receiving tool execution events.
tool_event_tx: mpsc::Sender<ToolEvent>,
tool_event_rx: Option<mpsc::Receiver<ToolEvent>>,
/// Whether the current streaming is a continuation after tool results.
/// When true, tool calls should NOT be cleared on StreamEvent::Done.
is_continuation: bool,
/// Undo stack for session message exchanges.
/// Each entry is a pair of (user_message, assistant_message).
undo_stack: Vec<Vec<cortex_core::widgets::Message>>,
}
/// Pending tool call information.
#[derive(Debug, Clone)]
pub struct PendingToolCall {
/// Tool call ID.
pub id: String,
/// Tool name.
pub name: String,
/// Tool arguments.
pub arguments: serde_json::Value,
}
impl EventLoop {
/// Creates a new EventLoop with the given application state.
pub fn new(app_state: AppState) -> Self {
// Create channel for tool execution events
let (tool_event_tx, tool_event_rx) = mpsc::channel::<ToolEvent>(100);
Self {
app_state,
frame_engine: None,
session_bridge: None,
stream_controller: StreamController::new(),
action_mapper: ActionMapper::default(),
click_zones: ClickZoneRegistry::new(),
mouse_handler: MouseHandler::new(),
modal_stack: ModalStack::new(),
command_executor: CommandExecutor::new(),
form_registry: FormRegistry::new(),
permission_manager: PermissionManager::new(),
provider_manager: None,
tool_executor: None,
subagent_executor: None,
running: Arc::new(AtomicBool::new(false)),
background_tasks: Vec::new(),
last_render: Instant::now(),
min_frame_time: Duration::from_micros(8333), // ~120 FPS
cortex_session: None,
tool_registry: None,
streaming_cancelled: Arc::new(AtomicBool::new(false)),
stream_done_received: false,
streaming_rx: None,
streaming_task: None,
card_handler: CardHandler::new(),
unified_executor: None,
pending_assistant_tool_calls: Vec::new(),
running_tool_tasks: std::collections::HashMap::new(),
running_subagents: std::collections::HashMap::new(),
tool_execution_started: false,
tool_event_tx,
tool_event_rx: Some(tool_event_rx),
is_continuation: false,
undo_stack: Vec::new(),
}
}
/// Sets the provider manager.
pub fn with_provider_manager(mut self, manager: ProviderManager) -> Self {
self.provider_manager = Some(Arc::new(tokio::sync::RwLock::new(manager)));
self
}
/// Sets the unified executor.
pub fn with_unified_executor(mut self, executor: Arc<UnifiedToolExecutor>) -> Self {
self.unified_executor = Some(executor);
self
}
/// Sets the session bridge.
pub fn with_session(mut self, bridge: SessionBridge) -> Self {
self.session_bridge = Some(bridge);
self
}
/// Sets the cortex session.
pub fn with_cortex_session(mut self, session: CortexSession) -> Self {
self.cortex_session = Some(session);
self
}
/// Sets the tool registry for executing tools.
pub fn with_tool_registry(mut self, registry: Arc<ToolRegistry>) -> Self {
self.tool_registry = Some(registry);
self
}
/// Runs the main event loop.
///
/// This method initializes the FrameEngine to poll keyboard, mouse, and
/// terminal events, then dispatches them to `handle_engine_event()` for
/// processing. It also polls streaming events from the LLM backend.
pub async fn run(&mut self, terminal: &mut CortexTerminal) -> Result<()> {
self.running.store(true, Ordering::SeqCst);
// Create channel for receiving events from FrameEngine
let (action_tx, mut action_rx) = tokio::sync::mpsc::channel::<EngineEvent>(256);
// Create and spawn the FrameEngine
let running = self.running.clone();
let mut frame_engine = FrameEngine::new(action_tx, running);
let engine_handle = tokio::spawn(async move {
if let Err(e) = frame_engine.run().await {
tracing::error!("FrameEngine error: {}", e);
}
});
// Initial render
self.render(terminal)?;
// Main event loop: poll BOTH FrameEngine events AND streaming events
loop {
// Check exit conditions
if !self.running.load(Ordering::SeqCst) || self.app_state.should_quit() {
break;
}
// Use tokio::select! to poll multiple event sources concurrently
tokio::select! {
// Branch 1: FrameEngine events (keyboard, mouse, ticks, resize)
Some(event) = action_rx.recv() => {
// Handle quit event
if matches!(event, EngineEvent::Quit) {
self.app_state.set_quit();
break;
}
// Dispatch event to handler
if let Err(e) = self.handle_engine_event(event, terminal).await {
tracing::error!("Error handling engine event: {}", e);
}
}
// Branch 2: Streaming events from LLM (Delta, Done, Error, ToolCall)
Some(stream_event) = async {
match self.streaming_rx.as_mut() {
Some(rx) => rx.recv().await,
None => std::future::pending().await,
}
} => {
self.handle_stream_event(stream_event).await;
// Re-render after streaming update to show new content
if let Err(e) = self.render(terminal) {
tracing::error!("Error rendering after stream event: {}", e);
}
}
// Branch 3: Tool execution events (Started, Output, Completed, Failed)
Some(tool_event) = async {
match self.tool_event_rx.as_mut() {
Some(rx) => rx.recv().await,
None => std::future::pending().await,
}
} => {
self.handle_tool_event(tool_event).await;
// Re-render after tool event to show status update
if let Err(e) = self.render(terminal) {
tracing::error!("Error rendering after tool event: {}", e);
}
}
}
}
// Cleanup: signal engine to stop and wait for it
self.running.store(false, Ordering::SeqCst);
let _ = engine_handle.await;
Ok(())
}
/// Spawns a subagent task (for Task tool).
/// Based on OpenCode's task.ts implementation.
fn spawn_subagent(&mut self, tool_call_id: String, args: serde_json::Value) {
tracing::info!("Spawning subagent for tool call: {}", tool_call_id);
// Parse args: { description, prompt, subagent_type, session_id? }
let description = args
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("Subagent task")
.to_string();
let prompt = args
.get("prompt")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let subagent_type = args
.get("subagent_type")
.and_then(|v| v.as_str())
.unwrap_or("default")
.to_string();
if prompt.is_empty() {
self.app_state.add_pending_tool_result(
tool_call_id,
"Task".to_string(),
"Task tool requires a 'prompt' parameter.".to_string(),
false,
);
return;
}
// Get dependencies for the spawned task
let Some(registry) = self.tool_registry.clone() else {
self.app_state.add_pending_tool_result(
tool_call_id,
"Task".to_string(),
"Tool registry not available for subagent.".to_string(),
false,
);
return;
};
let Some(provider_manager) = self.provider_manager.clone() else {
self.app_state.add_pending_tool_result(
tool_call_id,
"Task".to_string(),
"Provider not configured for subagent.".to_string(),
false,
);
return;
};
let tool_tx = self.tool_event_tx.clone();
let id = tool_call_id.clone();
// Add to UI display (session_id, tool_call_id, description, agent_type)
self.app_state.add_subagent_task(SubagentTaskDisplay::new(
format!("subagent_{}", id), // session_id
id.clone(), // tool_call_id
description.clone(),
subagent_type.clone(),
));
// Spawn background task with full agentic loop (like OpenCode)
let task = tokio::spawn(async move {
let started_at = Instant::now();
// Send started event
let _ = tool_tx
.send(ToolEvent::Started {
id: id.clone(),
name: "Task".to_string(),
started_at,
})
.await;
// Build subagent system prompt (like OpenCode)
let system_prompt = format!(
"You are a specialized {} subagent working on: {}\n\n\
You have access to tools like Read, Edit, Grep, Glob, LS, Execute, Batch, etc.\n\
Note: You cannot use Task, TodoWrite, or TodoRead tools (they are disabled for subagents).\n\
Use Batch to execute multiple tools in parallel for efficiency.\n\
If a tool fails, try an alternative approach instead of giving up.\n\
Complete the task and provide a clear summary when done.",
subagent_type, description
);
// Build initial messages for subagent
let mut messages = vec![Message::system(system_prompt), Message::user(&prompt)];
// Get tool definitions - filter based on subagent permissions (like OpenCode)
let tools: Vec<ClientToolDefinition> = registry
.get_definitions()
.into_iter()
.filter(|t| {
let name_lower = t.name.to_lowercase();
name_lower != "task" && name_lower != "todowrite" && name_lower != "todoread"
})
.map(|t| ClientToolDefinition::function(t.name, t.description, t.parameters))
.collect();
// Get model info
let model = {
let pm = provider_manager.read().await;
pm.current_model().to_string()
};
let mut final_content = String::new();
let mut tool_calls_executed: Vec<String> = Vec::new();
let max_iterations = 10; // Prevent infinite loops
// Agentic loop - continues until no more tool calls
for iteration in 0..max_iterations {
tracing::info!("Subagent iteration {}", iteration + 1);
// Get fresh client for each iteration
let client = {
let mut pm = provider_manager.write().await;
if let Err(e) = pm.ensure_client() {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: format!("Failed to initialize provider: {}", e),
duration: started_at.elapsed(),
})
.await;
return;
}
pm.take_client()
};
let Some(client) = client else {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: "No client available".to_string(),
duration: started_at.elapsed(),
})
.await;
return;
};
// Make LLM request
let request = cortex_engine::client::CompletionRequest {
messages: messages.clone(),
model: model.clone(),
max_tokens: Some(8192),
temperature: Some(0.7),
tools: tools.clone(),
stream: true,
};
let stream_result =
tokio::time::timeout(Duration::from_secs(120), client.complete(request)).await;
let mut stream = match stream_result {
Ok(Ok(s)) => s,
Ok(Err(e)) => {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: format!("Provider error: {}", e),
duration: started_at.elapsed(),
})
.await;
return;
}
Err(_) => {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: "Connection timeout".to_string(),
duration: started_at.elapsed(),
})
.await;
return;
}
};
// Collect response from this iteration
let mut iteration_content = String::new();
let mut iteration_tool_calls: Vec<(String, String, serde_json::Value)> = Vec::new(); // (id, name, args)
loop {
let event = tokio::time::timeout(Duration::from_secs(60), stream.next()).await;
match event {
Ok(Some(Ok(ResponseEvent::Delta(delta)))) => {
iteration_content.push_str(&delta);
}
Ok(Some(Ok(ResponseEvent::Done(_)))) => {
break;
}
Ok(Some(Ok(ResponseEvent::ToolCall(tc)))) => {
let args: serde_json::Value = serde_json::from_str(&tc.arguments)
.unwrap_or(serde_json::json!({}));
iteration_tool_calls.push((tc.id, tc.name, args));
}
Ok(Some(Ok(ResponseEvent::Error(e)))) => {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: e,
duration: started_at.elapsed(),
})
.await;
return;
}
Ok(Some(Err(e))) => {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: e.to_string(),
duration: started_at.elapsed(),
})
.await;
return;
}
Ok(None) => break,
Err(_) => {
let _ = tool_tx
.send(ToolEvent::Failed {
id: id.clone(),
name: "Task".to_string(),
error: "Response timeout".to_string(),
duration: started_at.elapsed(),
})
.await;
return;
}
_ => {}
}
}
// If no tool calls, we're done
if iteration_tool_calls.is_empty() {
final_content = iteration_content;
break;
}
// Execute tool calls and collect results
let mut tool_results: Vec<(String, String)> = Vec::new(); // (tool_call_id, output)
// Build tool_calls for the assistant message
let tool_calls_for_msg: Vec<cortex_engine::client::ToolCall> = iteration_tool_calls
.iter()
.map(
|(tc_id, tc_name, tc_args)| cortex_engine::client::ToolCall {
id: tc_id.clone(),
call_type: "function".to_string(),
function: cortex_engine::client::FunctionCall {
name: tc_name.clone(),
arguments: tc_args.to_string(),
},
},
)
.collect();
for (tc_id, tc_name, tc_args) in &iteration_tool_calls {
tracing::info!("Subagent executing tool: {} ({})", tc_name, tc_id);
let result = registry.execute(tc_name, tc_args.clone()).await;
match result {
Ok(tool_result) => {
let status = if tool_result.success {
"success"
} else {
"failed"
};
tool_calls_executed.push(format!("{}: {}", tc_name, status));
tool_results.push((tc_id.clone(), tool_result.output));
}
Err(e) => {
let error_msg = format!("Error executing {}: {}", tc_name, e);
tool_calls_executed.push(format!("{}: error", tc_name));
tool_results.push((tc_id.clone(), error_msg));
}
}
}
// Add assistant message with tool calls to conversation
let assistant_msg = Message {
role: cortex_engine::client::MessageRole::Assistant,
content: cortex_engine::client::MessageContent::Text(iteration_content.clone()),
tool_call_id: None,
tool_calls: Some(tool_calls_for_msg),
};
messages.push(assistant_msg);
// Add tool results to conversation
for (tc_id, output) in tool_results {
messages.push(Message::tool_result(&tc_id, &output));
}
// Store content for final output
if !iteration_content.is_empty() {
final_content = iteration_content;
}
}
// Build output with metadata
let tools_summary = if tool_calls_executed.is_empty() {
"No tools executed".to_string()
} else {
tool_calls_executed.join("\n")
};
let output = format!(
"{}\n\n\
Tools executed:\n{}\n\n\
<task_metadata>\n\
session_id: subagent_{}\n\
agent_type: {}\n\
description: {}\n\
</task_metadata>",
final_content, tools_summary, id, subagent_type, description
);
let duration = started_at.elapsed();
let _ = tool_tx
.send(ToolEvent::Completed {
id,
name: "Task".to_string(),
output,
success: true,
duration,
})
.await;
});
self.running_tool_tasks.insert(tool_call_id, task);
}
/// Spawns a tool execution task in the background.
fn spawn_tool_execution(
&mut self,
tool_call_id: String,
tool_name: String,
args: serde_json::Value,
) {
tracing::info!("Spawning tool execution: {} ({})", tool_name, tool_call_id);
// Get tool registry
let Some(registry) = self.tool_registry.clone() else {
tracing::warn!(
"Tool registry not initialized, cannot execute: {}",
tool_name
);
self.app_state.add_pending_tool_result(
tool_call_id,
tool_name,
"Tool registry not initialized. This is a configuration error.".to_string(),
false,
);
return;
};
let tool_tx = self.tool_event_tx.clone();
let id = tool_call_id.clone();
let name = tool_name.clone();
// Spawn background task for tool execution
let task = tokio::spawn(async move {
let started_at = Instant::now();
// Send started event
let _ = tool_tx
.send(ToolEvent::Started {
id: id.clone(),
name: name.clone(),
started_at,
})
.await;
// Execute the tool
let result = registry.execute(&name, args).await;
let duration = started_at.elapsed();
match result {
Ok(tool_result) => {
let _ = tool_tx
.send(ToolEvent::Completed {
id,
name,
output: tool_result.output,
success: tool_result.success,
duration,
})
.await;
}
Err(e) => {
let _ = tool_tx
.send(ToolEvent::Failed {
id,
name,
error: e.to_string(),
duration,
})
.await;
}
}
});
self.running_tool_tasks.insert(tool_call_id, task);
}
/// Syncs the permission mode between app state and permission manager.
fn sync_permission_mode(&mut self) {
self.permission_manager.mode = match self.app_state.permission_mode {
crate::permissions::PermissionMode::Yolo => crate::permissions::PermissionMode::Yolo,
crate::permissions::PermissionMode::Low => crate::permissions::PermissionMode::Low,
crate::permissions::PermissionMode::Medium => {
crate::permissions::PermissionMode::Medium
}
crate::permissions::PermissionMode::High => crate::permissions::PermissionMode::High,
};
}
/// Continues with tool results after execution - sends results back to LLM.
async fn continue_with_tool_results(&mut self) -> Result<()> {
// Check if there are pending tool results
if !self.app_state.has_pending_tool_results() {
return Ok(());
}
tracing::info!(
"Continuing with {} pending tool results",
self.app_state.pending_tool_results.len()
);
// Take pending results
let pending_results = std::mem::take(&mut self.app_state.pending_tool_results);
// Save tool results to session
if let Some(ref mut session) = self.cortex_session {
for result in &pending_results {
let stored_msg = crate::session::StoredMessage::tool_result(
&result.tool_call_id,
&result.output,
);
session.add_message_raw(stored_msg);
}
}
// Send tool results back to LLM to continue the conversation
// This triggers a new streaming request with the tool results
self.send_tool_results_to_llm(pending_results).await?;
Ok(())
}
/// Sends tool results to the LLM to continue the agentic loop.
/// This triggers a new streaming request with the tool results already in the session.
async fn send_tool_results_to_llm(&mut self, results: Vec<PendingToolResult>) -> Result<()> {
if results.is_empty() {
return Ok(());
}
tracing::info!(
"Sending {} tool results to LLM for continuation",
results.len()
);
// Mark as continuation - tool calls should NOT be cleared
self.is_continuation = true;
// Check provider exists
let provider_manager = match &self.provider_manager {
Some(pm) => pm.clone(),
None => {
tracing::warn!("No provider manager for tool result continuation");
return Ok(());
}
};
// Build system prompt
let system_prompt = build_system_prompt();
let system_message = Message::system(system_prompt);
// Build messages for API (includes tool results that were just added to session)
let session_messages: Vec<Message> = if let Some(ref session) = self.cortex_session {
session.messages_for_api()
} else {
tracing::warn!("No session for tool result continuation");
return Ok(());
};
// Prepend system prompt to messages
let mut messages: Vec<Message> = vec![system_message];
messages.extend(session_messages);
// Get tool definitions from registry
let tools: Vec<ClientToolDefinition> = self
.tool_registry
.as_ref()
.map(|r| r.get_definitions())
.unwrap_or_default()
.into_iter()
.map(|t| ClientToolDefinition::function(t.name, t.description, t.parameters))
.collect();
// Start streaming UI state
self.stream_controller.start_processing();
self.app_state.start_streaming(None);
// Reset cancellation flag and stream_done flag
self.streaming_cancelled.store(false, Ordering::SeqCst);
self.stream_done_received = false;
// Get completion request parameters
let (model, max_tokens, temperature, client) = {
let mut pm = provider_manager.write().await;
if let Err(e) = pm.ensure_client() {
self.stream_controller.set_error(e.to_string());
self.app_state.stop_streaming();
return Ok(());
}
let model = pm.current_model().to_string();
let max_tokens = pm.config().max_tokens;
let temperature = pm.config().temperature;
let client = pm.take_client();
(model, max_tokens, temperature, client)
};
if client.is_none() {
self.app_state.stop_streaming();
return Ok(());
}
// Create channel for streaming events
let (tx, rx) = mpsc::channel::<StreamEvent>(100);
self.streaming_rx = Some(rx);
let cancelled = self.streaming_cancelled.clone();
// Spawn background streaming task
let task = tokio::spawn(async move {
let client = client.unwrap();
let request = cortex_engine::client::CompletionRequest {
messages,
model,
max_tokens: Some(max_tokens),
temperature: Some(temperature),
tools,
stream: true,
};
let stream_result =
tokio::time::timeout(Duration::from_secs(60), client.complete(request)).await;
let mut stream = match stream_result {
Ok(Ok(s)) => s,
Ok(Err(e)) => {
let _ = tx
.send(StreamEvent::Error(format!("Provider error: {}", e)))
.await;
return;
}
Err(_) => {
let _ = tx
.send(StreamEvent::Error("Connection timeout".to_string()))
.await;
return;
}
};
let mut content = String::new();
let mut reasoning = String::new();
let mut tokens: Option<cortex_engine::streaming::StreamTokenUsage> = None;
loop {
if cancelled.load(Ordering::SeqCst) {
let _ = tx
.send(StreamEvent::Error("Cancelled by user".to_string()))
.await;
break;
}
let event = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;
match event {
Ok(Some(Ok(ResponseEvent::Delta(delta)))) => {
content.push_str(&delta);
if tx.send(StreamEvent::Delta(delta)).await.is_err() {
break;
}
}
Ok(Some(Ok(ResponseEvent::Reasoning(r)))) => {
reasoning.push_str(&r);
if tx.send(StreamEvent::Reasoning(r)).await.is_err() {
break;
}
}
Ok(Some(Ok(ResponseEvent::Done(response)))) => {
tokens = Some(cortex_engine::streaming::StreamTokenUsage::from(
response.usage,
));
let _ = tx
.send(StreamEvent::Done {
content,
reasoning,
tokens,
})
.await;
break;
}
Ok(Some(Ok(ResponseEvent::Error(e)))) => {
let _ = tx.send(StreamEvent::Error(e)).await;
break;
}
Ok(Some(Ok(ResponseEvent::ToolCall(tool_call)))) => {
let arguments = serde_json::from_str(&tool_call.arguments)
.unwrap_or_else(|_| serde_json::json!({"raw": tool_call.arguments}));
if tx
.send(StreamEvent::ToolCall {
id: tool_call.id.clone(),
name: tool_call.name.clone(),
arguments,
})
.await
.is_err()
{
break;
}